diff --git a/AUTHORS b/AUTHORS index f0d04a1..0464b3bb 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -504,6 +504,7 @@ Jaemin Seo <jaemin86.seo@samsung.com> Jaeseok Yoon <yjaeseok@gmail.com> Jaewon Choi <jaewon.james.choi@gmail.com> +Jaewon Jung <jw.jung@navercorp.com> Jaeyong Bae <jdragon.bae@gmail.com> Jagdish Chourasia <jagdish.c@samsung.com> Jaime Soriano Pastor <jsorianopastor@gmail.com>
diff --git a/DEPS b/DEPS index 8f59ab183..50d3b76 100644 --- a/DEPS +++ b/DEPS
@@ -301,7 +301,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '8d4f03e9239ad99cf248c235421bd2eb3c43980c', + 'skia_revision': 'b795c8f164cee3687c150919a5900e40c50a5120', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -309,7 +309,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '202fcb8d854a92bc18ac958bb7f863977bf7cb20', + 'angle_revision': '27727e501aee0c35e4d4572792131e3a77d099c4', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -328,7 +328,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:10.20221121.3.1', + 'fuchsia_version': 'version:10.20221122.0.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -372,7 +372,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '2b857d73ffd0ea3eedcded1ba16f14a80185e94f', + 'catapult_revision': 'cce68bc50e1127115eca0db671c1657f2750b6f5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -416,7 +416,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': 'd6d30f425653576f9a3da43f462a55327323b30f', + 'dawn_revision': 'f9c6633006e84f697996fb72e570114576cc32c3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -436,11 +436,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libavif # and whatever else without interference from each other. - 'libavif_revision': 'c3d978af5554fa8be89c82b0f6dd3b35d23a4813', + 'libavif_revision': '8833320506a092a45fe9c3dab2a75eb18559eb96', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling nearby # and whatever else without interference from each other. - 'nearby_revision': 'a3b6058753fb9f9590194f68e3853c2787fcf279', + 'nearby_revision': 'c499d18af696bf73b36a5db8c3388e01b5c41b0c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling securemessage # and whatever else without interference from each other. @@ -811,7 +811,7 @@ 'src/clank': { 'url': 'https://chrome-internal.googlesource.com/clank/internal/apps.git' + '@' + - 'baac8c9bd49b618c2a91b07d5195660133c356fb', + '655837ff5669ff84b4e0286e30fc3518320458ab', 'condition': 'checkout_android and checkout_src_internal', }, @@ -1000,7 +1000,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'ocp0y0IgrnQisPklXhrCVp0gzN79IpD6ooyCwFpNIlcC', + 'version': '0lQn_nLBNlXd0NzCrQC3IUe3JECb_xi20aRJ3bac0hcC', }, ], 'condition': 'checkout_android', @@ -1233,7 +1233,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'f71907ee5a49b35b73cd6839b68e26d24246f4a3', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'f2700e5aaeec4f4735e8a2cf2a13b3561c390448', 'condition': 'checkout_linux', }, @@ -1243,13 +1243,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '30e3ce8b1c670be00c4957fe773ffb8ff986ed8f', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '2fc7e1ffd58b00601b47a5126201e5162911e244', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + '99452bce3822b5f10dcbda92d7d6568f417b92dc', + 'url': 'https://chrome-internal.googlesource.com/devtools/devtools-internal.git' + '@' + '995a6e9561e92963f853b0895dcc45b17db77673', 'condition': 'checkout_src_internal', }, @@ -1664,7 +1664,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '4f6803dfe01e8e9f05957329f0475044dc658990', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '28b1da6e19569e744e05174357f7be40c8bc22db', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1849,7 +1849,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '39eb8086a4f030c8405f93ef770a6bfe8ab7fc55', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'dd35e244cec8b3af022ac92b2185465a422f2eec', + Var('webrtc_git') + '/src.git' + '@' + '8a8c455cce27c962572a4b466360409fc491bab9', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file. @@ -1919,7 +1919,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@741217d8d9786f651ac368429d84aac8eb3de49f', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@73bf092a07be5c7cbc9d9eae3a9e815c563af0bd', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/tools/cts_config/webview_cts_gcs_path.json b/android_webview/tools/cts_config/webview_cts_gcs_path.json index 8bb85348..ee800b15 100644 --- a/android_webview/tools/cts_config/webview_cts_gcs_path.json +++ b/android_webview/tools/cts_config/webview_cts_gcs_path.json
@@ -277,11 +277,6 @@ "match": "android.webkit.cts.WebViewClientTest#testOnSafeBrowsingHit", "arch": "x86", "_bug_id": "crbug.com/1245351" - }, - { - "match": "android.text.cts.EmojiTest#testEmojiGlyph", - "arch": "x86", - "_bug_id": "crbug.com/1379362" } ] }, @@ -313,14 +308,6 @@ "match": "android.widget.cts.RemoteViewsActivityTest#testWebView" } ] - }, - { - "apk": "android-cts/testcases/CtsTextTestCases.apk", - "includes": [ - { - "match": "android.text.cts.EmojiTest#testEmojiGlyph" - } - ] } ] },
diff --git a/ash/accelerators/accelerator_commands.cc b/ash/accelerators/accelerator_commands.cc index c2eb4ff..65b63eb 100644 --- a/ash/accelerators/accelerator_commands.cc +++ b/ash/accelerators/accelerator_commands.cc
@@ -41,6 +41,7 @@ #include "ash/system/ime_menu/ime_menu_tray.h" #include "ash/system/keyboard_brightness_control_delegate.h" #include "ash/system/model/system_tray_model.h" +#include "ash/system/notification_center/notification_center_tray.h" #include "ash/system/palette/palette_tray.h" #include "ash/system/power/power_button_controller.h" #include "ash/system/status_area_widget.h" @@ -114,6 +115,9 @@ constexpr char kVirtualDesksToastId[] = "virtual_desks_toast"; // Toast id for Assistant shortcuts. constexpr char kAssistantErrorToastId[] = "assistant_error"; +// Toast ID for the notification center tray "No notifications" toast. +constexpr char kNotificationCenterTrayNoNotificationsToastId[] = + "notification_center_tray_toast_ids.no_notifications"; // These values are written to logs. New enum values can be added, but existing // enums must never be renumbered or deleted and reused. @@ -1337,7 +1341,29 @@ } void ToggleMessageCenterBubble() { - HandleToggleSystemTrayBubbleInternal(true /*focus_message_center*/); + if (!features::IsQsRevampEnabled()) { + HandleToggleSystemTrayBubbleInternal(/*focus_message_center=*/true); + return; + } + aura::Window* target_root = Shell::GetRootWindowForNewWindows(); + NotificationCenterTray* tray = RootWindowController::ForWindow(target_root) + ->GetStatusAreaWidget() + ->notification_center_tray(); + + // Show a toast if there are no notifications. + if (!tray->GetVisible()) { + ShowToast(kNotificationCenterTrayNoNotificationsToastId, + ash::ToastCatalogName::kNotificationCenterTrayNoNotifications, + l10n_util::GetStringUTF16( + IDS_ASH_MESSAGE_CENTER_ACCELERATOR_NO_NOTIFICATIONS)); + return; + } + + if (tray->GetBubbleWidget()) { + tray->CloseBubble(); + } else { + tray->ShowBubble(); + } } void ToggleMirrorMode() {
diff --git a/ash/accelerators/ash_accelerator_configuration.cc b/ash/accelerators/ash_accelerator_configuration.cc index d3b9234a..6e0b9e13 100644 --- a/ash/accelerators/ash_accelerator_configuration.cc +++ b/ash/accelerators/ash_accelerator_configuration.cc
@@ -99,13 +99,11 @@ accelerators, base::make_span(kEnableWithPositionalAcceleratorsData, kEnableWithPositionalAcceleratorsDataLength)); - if (ash::features::IsImprovedDesksKeyboardShortcutsEnabled()) { - AppendAcceleratorData( - accelerators, - base::make_span( - kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorData, - kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorDataLength)); - } + AppendAcceleratorData( + accelerators, + base::make_span( + kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorData, + kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorDataLength)); } else if (::features::IsNewShortcutMappingEnabled()) { AppendAcceleratorData( accelerators,
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 4a009c0..7aab6f03 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -1534,7 +1534,7 @@ </message> <message name="IDS_ASH_PHONE_HUB_FULL_APPS_LIST_BUTTON_TITLE" desc="Text indicates that the button is to display full apps list."> More apps - </message> + </message> <message name="IDS_ASH_PHONE_HUB_RECENT_APPS_PLACEHOLDER" desc="The placeholder of the recently used apps section (where users relaunch it directly after an app is launched from a notification) in phone hub bubble."> When you stream your phone’s apps, they will appear here </message> @@ -3957,6 +3957,7 @@ Sign out </message> + <!-- TODO(b/259709518): Update naming from "Message center" to "Notification center" --> <!-- Message center --> <message name="IDS_ASH_MESSAGE_CENTER_ACCESSIBLE_NAME" desc="The spoken feedback name for when accessible focus moves to the message center"> Notification Center @@ -4029,6 +4030,9 @@ ChromiumOS </message> </if> + <message name="IDS_ASH_MESSAGE_CENTER_ACCELERATOR_NO_NOTIFICATIONS" desc="The toast message displayed when Alt+Shift+N is pressed but there are no notifications."> + No notifications + </message> <!-- Notification --> <message name="IDS_ASH_NOTIFICATION_EXPAND_TOOLTIP" desc="The tooltip for the expand button, indicating action to expand the notification.">
diff --git a/ash/ash_strings_grd/IDS_ASH_MESSAGE_CENTER_ACCELERATOR_NO_NOTIFICATIONS.png.sha1 b/ash/ash_strings_grd/IDS_ASH_MESSAGE_CENTER_ACCELERATOR_NO_NOTIFICATIONS.png.sha1 new file mode 100644 index 0000000..4592e22 --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_MESSAGE_CENTER_ACCELERATOR_NO_NOTIFICATIONS.png.sha1
@@ -0,0 +1 @@ +2766b11985be0ca446a276cfd827e13c2c248489 \ No newline at end of file
diff --git a/ash/components/phonehub/app_stream_launcher_data_model.cc b/ash/components/phonehub/app_stream_launcher_data_model.cc index 1a7c257..8726eb73 100644 --- a/ash/components/phonehub/app_stream_launcher_data_model.cc +++ b/ash/components/phonehub/app_stream_launcher_data_model.cc
@@ -4,13 +4,17 @@ #include "ash/components/phonehub/app_stream_launcher_data_model.h" -namespace ash { -namespace phonehub { +#include "ash/components/phonehub/notification.h" + +namespace ash::phonehub { AppStreamLauncherDataModel::AppStreamLauncherDataModel() = default; AppStreamLauncherDataModel::~AppStreamLauncherDataModel() = default; +void AppStreamLauncherDataModel::Observer::OnShouldShowMiniLauncherChanged() {} +void AppStreamLauncherDataModel::Observer::OnAppListChanged() {} + void AppStreamLauncherDataModel::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } @@ -46,6 +50,8 @@ const Notification::AppMetadata& b) { return a.visible_app_name < b.visible_app_name; }); + for (auto& observer : observer_list_) + observer.OnAppListChanged(); } const std::vector<Notification::AppMetadata>* @@ -58,5 +64,4 @@ return &apps_list_sorted_by_name_; } -} // namespace phonehub -} // namespace ash +} // namespace ash::phonehub
diff --git a/ash/components/phonehub/app_stream_launcher_data_model.h b/ash/components/phonehub/app_stream_launcher_data_model.h index 3d4b16c..53db518f 100644 --- a/ash/components/phonehub/app_stream_launcher_data_model.h +++ b/ash/components/phonehub/app_stream_launcher_data_model.h
@@ -19,7 +19,8 @@ public: ~Observer() override = default; - virtual void OnShouldShowMiniLauncherChanged() = 0; + virtual void OnShouldShowMiniLauncherChanged(); + virtual void OnAppListChanged(); }; AppStreamLauncherDataModel();
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index a61b9a7d..0cf092f 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -1183,12 +1183,6 @@ "ImeTrayHideVoiceButton", base::FEATURE_ENABLED_BY_DEFAULT); -// Enables improved keyboard shortcuts for activating desks at specified indices -// and toggling whether a window is assigned to all desks. -BASE_FEATURE(kImprovedDesksKeyboardShortcuts, - "ImprovedDesksKeyboardShortcuts", - base::FEATURE_ENABLED_BY_DEFAULT); - // Controls whether to show new improved UI for cryptohome errors that happened // during login. UI contains links to help center and might provide actions // that can be taken to resolve the problem. @@ -1472,6 +1466,11 @@ "OobeMaterialNext", base::FEATURE_DISABLED_BY_DEFAULT); +// If enabled, the new recommend apps screen is shown. +BASE_FEATURE(kOobeNewRecommendApps, + "OobeNewRecommendApps", + base::FEATURE_ENABLED_BY_DEFAULT); + // Removes "Shut down" button from OOBE, except first login screen and // successful enrollment step. BASE_FEATURE(kOobeRemoveShutdownButton, @@ -1878,12 +1877,6 @@ "StylusBatteryStatus", base::FEATURE_ENABLED_BY_DEFAULT); -// Enables or disables using the system input engine for physical typing in -// Chinese. -BASE_FEATURE(kSystemChinesePhysicalTyping, - "SystemChinesePhysicalTyping", - base::FEATURE_ENABLED_BY_DEFAULT); - // Enables or disables the System Extensions platform. BASE_FEATURE(kSystemExtensions, "SystemExtensions", @@ -1909,12 +1902,6 @@ // Enables the ability to play sounds for system services. BASE_FEATURE(kSystemSounds, "SystemSounds", base::FEATURE_DISABLED_BY_DEFAULT); -// Enables or disables using the system input engine for physical typing in -// transliteration input methods. -BASE_FEATURE(kSystemTransliterationPhysicalTyping, - "SystemTransliterationPhysicalTyping", - base::FEATURE_ENABLED_BY_DEFAULT); - // Enables or disables the shadows of system tray bubbles. BASE_FEATURE(kSystemTrayShadow, "SystemTrayShadow", @@ -2620,10 +2607,6 @@ return base::FeatureList::IsEnabled(kImeTrayHideVoiceButton); } -bool IsImprovedDesksKeyboardShortcutsEnabled() { - return base::FeatureList::IsEnabled(kImprovedDesksKeyboardShortcuts); -} - bool IsInputInDiagnosticsAppEnabled() { return base::FeatureList::IsEnabled(kEnableInputInDiagnosticsApp); } @@ -2734,7 +2717,8 @@ } bool IsEcheLauncherEnabled() { - return base::FeatureList::IsEnabled(kEcheLauncher); + return base::FeatureList::IsEnabled(kEcheLauncher) && + base::FeatureList::IsEnabled(kEcheSWA); } bool IsNearbyKeepAliveFixEnabled() { @@ -2809,6 +2793,10 @@ return base::FeatureList::IsEnabled(kOobeQuickStart); } +bool IsOobeNewRecommendAppsEnabled() { + return base::FeatureList::IsEnabled(kOobeNewRecommendApps); +} + bool IsOobeRemoveShutdownButtonEnabled() { return base::FeatureList::IsEnabled(kOobeRemoveShutdownButton); }
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index 285d5b0..8442253d 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -344,8 +344,6 @@ BASE_DECLARE_FEATURE(kImeSystemEmojiPickerSearchExtension); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kImeStylusHandwriting); COMPONENT_EXPORT(ASH_CONSTANTS) -BASE_DECLARE_FEATURE(kImprovedDesksKeyboardShortcuts); -COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kImprovedLoginErrorHandling); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kInstantTethering); COMPONENT_EXPORT(ASH_CONSTANTS) @@ -537,8 +535,6 @@ BASE_DECLARE_FEATURE(kStartAssistantAudioDecoderOnDemand); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSyncSettingsCategorization); -COMPONENT_EXPORT(ASH_CONSTANTS) -BASE_DECLARE_FEATURE(kSystemChinesePhysicalTyping); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemExtensions); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemExtensionsManagedDeviceHealthServices); @@ -547,8 +543,6 @@ COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemLiveCaption); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemSounds); -COMPONENT_EXPORT(ASH_CONSTANTS) -BASE_DECLARE_FEATURE(kSystemTransliterationPhysicalTyping); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemTrayShadow); COMPONENT_EXPORT(ASH_CONSTANTS) BASE_DECLARE_FEATURE(kSystemProxyForSystemServices); @@ -711,7 +705,6 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHomeButtonWithTextEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHostnameSettingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHotspotEnabled(); -COMPONENT_EXPORT(ASH_CONSTANTS) bool IsImprovedDesksKeyboardShortcutsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInputInDiagnosticsAppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInputNoiseCancellationUiEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS)
diff --git a/ash/constants/ash_switches.cc b/ash/constants/ash_switches.cc index 509a972..dece237 100644 --- a/ash/constants/ash_switches.cc +++ b/ash/constants/ash_switches.cc
@@ -318,6 +318,10 @@ // file). const char kDefaultWallpaperSmall[] = "default-wallpaper-small"; +// Test Organization Unit (OU) user to use for demo mode. Only pass the part +// before "@cros-demo-mode.com". +const char kDemoModeEnrollingUsername[] = "demo-mode-enrolling-username"; + // App ID to use for highlights app in demo mode. const char kDemoModeHighlightsApp[] = "demo-mode-highlights-extension";
diff --git a/ash/constants/ash_switches.h b/ash/constants/ash_switches.h index 0398dd5f..17dfa2e 100644 --- a/ash/constants/ash_switches.h +++ b/ash/constants/ash_switches.h
@@ -100,6 +100,8 @@ COMPONENT_EXPORT(ASH_CONSTANTS) extern const char kDefaultWallpaperIsOem[]; COMPONENT_EXPORT(ASH_CONSTANTS) extern const char kDefaultWallpaperLarge[]; COMPONENT_EXPORT(ASH_CONSTANTS) extern const char kDefaultWallpaperSmall[]; +COMPONENT_EXPORT(ASH_CONSTANTS) +extern const char kDemoModeEnrollingUsername[]; COMPONENT_EXPORT(ASH_CONSTANTS) extern const char kDemoModeHighlightsApp[]; COMPONENT_EXPORT(ASH_CONSTANTS) extern const char kDemoModeScreensaverApp[]; COMPONENT_EXPORT(ASH_CONSTANTS)
diff --git a/ash/constants/notifier_catalogs.h b/ash/constants/notifier_catalogs.h index 75a1df2..d9aebe7 100644 --- a/ash/constants/notifier_catalogs.h +++ b/ash/constants/notifier_catalogs.h
@@ -231,7 +231,8 @@ kDeprecateAssistantStylus = 36, kEcheTrayCopyPasteNotImplemented = 37, kEcheTrayTabletModeNotSupported = 38, - kMaxValue = kEcheTrayTabletModeNotSupported, + kNotificationCenterTrayNoNotifications = 39, + kMaxValue = kNotificationCenterTrayNoNotifications, }; } // namespace ash
diff --git a/ash/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc b/ash/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc index 6a89637..caf8577 100644 --- a/ash/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc +++ b/ash/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc
@@ -1385,10 +1385,7 @@ if (!is_initialized) { is_initialized = true; - // The improved desks keyboard shortcuts should only be enabled if the - // improved keyboard shortcuts flag is also enabled. - if (::features::IsImprovedKeyboardShortcutsEnabled() && - ash::features::IsImprovedDesksKeyboardShortcutsEnabled()) { + if (::features::IsImprovedKeyboardShortcutsEnabled()) { const ash::KeyboardShortcutItem indexed_activation_shortcut = { // |categories| {ShortcutCategory::kTabAndWindow},
diff --git a/ash/system/accessibility/accessibility_detailed_view.cc b/ash/system/accessibility/accessibility_detailed_view.cc index 95740ce..af9fde7a 100644 --- a/ash/system/accessibility/accessibility_detailed_view.cc +++ b/ash/system/accessibility/accessibility_detailed_view.cc
@@ -660,7 +660,8 @@ // Create a non-clickable non-focusable toggle button on the right. auto toggle = std::make_unique<TrayToggleButton>( views::Button::PressedCallback(), - /*accessible_name_id=*/absl::nullopt); + /*accessible_name_id=*/absl::nullopt, + /*use_empty_border=*/features::IsQsRevampEnabled()); toggle->SetIsOn(checked); toggle->SetCanProcessEventsWithinSubtree(false); toggle->SetFocusBehavior(views::View::FocusBehavior::NEVER);
diff --git a/ash/system/bluetooth/bluetooth_detailed_view_controller.cc b/ash/system/bluetooth/bluetooth_detailed_view_controller.cc index 43fda66c..a9d5adf41 100644 --- a/ash/system/bluetooth/bluetooth_detailed_view_controller.cc +++ b/ash/system/bluetooth/bluetooth_detailed_view_controller.cc
@@ -288,7 +288,8 @@ paired_device_properties->device_properties = BluetoothDeviceProperties::New(); paired_device_properties->device_properties->id = "Video Camera"; - paired_device_properties->device_properties->public_name = u"Video Camera"; + paired_device_properties->device_properties->public_name = + u"Video Camera with a very very very very very very very long name"; paired_device_properties->device_properties->device_type = DeviceType::kVideoCamera; paired_device_properties->device_properties->connection_state =
diff --git a/ash/system/bluetooth/bluetooth_detailed_view_impl.cc b/ash/system/bluetooth/bluetooth_detailed_view_impl.cc index f6e5162..76a0e76 100644 --- a/ash/system/bluetooth/bluetooth_detailed_view_impl.cc +++ b/ash/system/bluetooth/bluetooth_detailed_view_impl.cc
@@ -41,13 +41,10 @@ namespace ash { namespace { -constexpr auto kToggleRowTriViewInsets = gfx::Insets::TLBR(8, 4, 8, 4); +constexpr auto kToggleRowTriViewInsets = gfx::Insets::VH(8, 24); constexpr auto kMainContainerMargins = gfx::Insets::TLBR(2, 0, 0, 0); constexpr auto kPairNewDeviceIconMargins = gfx::Insets::TLBR(0, 2, 0, 0); - -// TODO(b/252872600): Set left inset to 24 once HoverHighlightView and/or -// TriView support 24 pixel insets. -constexpr auto kSubHeaderInsets = gfx::Insets::TLBR(10, 18, 10, 24); +constexpr auto kSubHeaderInsets = gfx::Insets::TLBR(10, 24, 10, 16); } // namespace @@ -189,7 +186,8 @@ auto toggle = std::make_unique<TrayToggleButton>( base::BindRepeating(&BluetoothDetailedViewImpl::OnToggleClicked, weak_factory_.GetWeakPtr()), - IDS_ASH_STATUS_TRAY_BLUETOOTH); + IDS_ASH_STATUS_TRAY_BLUETOOTH, + /*use_empty_border=*/true); toggle_button_ = toggle.get(); toggle_row_->AddRightView(toggle.release());
diff --git a/ash/system/ime/ime_detailed_view.cc b/ash/system/ime/ime_detailed_view.cc index 92b44ad1..ea67d528 100644 --- a/ash/system/ime/ime_detailed_view.cc +++ b/ash/system/ime/ime_detailed_view.cc
@@ -53,8 +53,10 @@ void IMEDetailedView::CreateExtraTitleRowButtons() { if (ime_controller_->managed_by_policy()) { - controlled_setting_icon_ = TrayPopupUtils::CreateMainImageView(); - if (features::IsQsRevampEnabled()) { + const bool is_qs_revamp = features::IsQsRevampEnabled(); + controlled_setting_icon_ = TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/is_qs_revamp); + if (is_qs_revamp) { // Match the size of the settings button. This size matches IconButton // kSmall, but IconButton doesn't expose that value, so we inline it here. controlled_setting_icon_->SetPreferredSize(gfx::Size(32, 32));
diff --git a/ash/system/ime_menu/ime_list_view.cc b/ash/system/ime_menu/ime_list_view.cc index 5a3cd9ee..a5edba2 100644 --- a/ash/system/ime_menu/ime_list_view.cc +++ b/ash/system/ime_menu/ime_list_view.cc
@@ -66,7 +66,9 @@ selected_(selected) { views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON); - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + const bool is_qs_revamp = features::IsQsRevampEnabled(); + TriView* tri_view = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/is_qs_revamp); AddChildView(tri_view); SetLayoutManager(std::make_unique<views::FillLayout>()); @@ -105,7 +107,8 @@ if (selected) { // The checked button indicates the IME is selected. - views::ImageView* checked_image = TrayPopupUtils::CreateMainImageView(); + views::ImageView* checked_image = TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/is_qs_revamp); checked_image->SetImage(gfx::CreateVectorIcon( kHollowCheckCircleIcon, kMenuIconSize, button_color)); tri_view->AddView(TriView::Container::END, checked_image); @@ -164,18 +167,21 @@ views::ToggleButton* toggle() const { return toggle_; } void Init(views::Button::PressedCallback callback) { + const bool is_qs_revamp = features::IsQsRevampEnabled(); // QsRevamp does not use sticky headers. - if (!features::IsQsRevampEnabled()) { + if (!is_qs_revamp) { TrayPopupUtils::ConfigureAsStickyHeader(this); } SetLayoutManager(std::make_unique<views::FillLayout>()); - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + TriView* tri_view = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/is_qs_revamp); AddChildView(tri_view); auto* color_provider = AshColorProvider::Get(); // The on-screen keyboard image button. - views::ImageView* keyboard_image = TrayPopupUtils::CreateMainImageView(); + views::ImageView* keyboard_image = + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/is_qs_revamp); keyboard_image->SetImage(gfx::CreateVectorIcon( kImeMenuOnScreenKeyboardIcon, kMenuIconSize, color_provider->GetContentLayerColor( @@ -194,8 +200,8 @@ // The on-screen keyboard toggle button. toggle_ = new TrayToggleButton( - std::move(callback), - IDS_ASH_STATUS_TRAY_ACCESSIBILITY_VIRTUAL_KEYBOARD); + std::move(callback), IDS_ASH_STATUS_TRAY_ACCESSIBILITY_VIRTUAL_KEYBOARD, + /*use_empty_border=*/is_qs_revamp); toggle_->SetIsOn(keyboard::IsKeyboardEnabled()); tri_view->AddView(TriView::Container::END, toggle_); } @@ -231,6 +237,12 @@ property_map_.clear(); CreateScrollableList(); + // Setup the container for the IME list views. + container_ = + features::IsQsRevampEnabled() + ? scroll_content()->AddChildView(std::make_unique<RoundedContainer>()) + : scroll_content(); + if (single_ime_behavior == ImeListView::SHOW_SINGLE_IME || list.size() > 1) AppendImeListAndProperties(current_ime_id, list, property_items); @@ -253,6 +265,7 @@ Reset(); keyboard_status_row_ = nullptr; current_ime_view_ = nullptr; + container_ = nullptr; } void ImeListView::ScrollItemToVisible(views::View* item_view) { @@ -272,17 +285,12 @@ const std::vector<ImeInfo>& list, const std::vector<ImeMenuItem>& property_list) { DCHECK(ime_map_.empty()); - - views::View* container = scroll_content(); - if (features::IsQsRevampEnabled()) { - container = - scroll_content()->AddChildView(std::make_unique<RoundedContainer>()); - } + DCHECK(container_); for (size_t i = 0; i < list.size(); i++) { const bool selected = current_ime_id == list[i].id; views::View* ime_view = - container->AddChildView(std::make_unique<ImeListItemView>( + container_->AddChildView(std::make_unique<ImeListItemView>( this, list[i].short_name, list[i].name, selected, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorProminent))); @@ -295,7 +303,7 @@ // Add the properties, if any, of the currently-selected IME. if (selected && !property_list.empty()) { // Adds a separator on the top of property items. - container->AddChildView(TrayPopupUtils::CreateListItemSeparator(true)); + container_->AddChildView(TrayPopupUtils::CreateListItemSeparator(true)); const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary); @@ -303,7 +311,7 @@ // Adds the property items. for (const auto& property : property_list) { ImeListItemView* property_view = - container->AddChildView(std::make_unique<ImeListItemView>( + container_->AddChildView(std::make_unique<ImeListItemView>( this, std::u16string(), property.label, property.checked, icon_color)); @@ -313,7 +321,7 @@ // Adds a separator on the bottom of property items if there are still // other IMEs under the current one. if (i < list.size() - 1) { - container->AddChildView(TrayPopupUtils::CreateListItemSeparator(true)); + container_->AddChildView(TrayPopupUtils::CreateListItemSeparator(true)); } } } @@ -324,7 +332,7 @@ keyboard_status_row_ = new KeyboardStatusRow; keyboard_status_row_->Init(base::BindRepeating( &ImeListView::KeyboardStatusTogglePressed, base::Unretained(this))); - scroll_content()->AddChildViewAt(keyboard_status_row_, 0); + container_->AddChildViewAt(keyboard_status_row_, 0); } void ImeListView::KeyboardStatusTogglePressed() {
diff --git a/ash/system/ime_menu/ime_list_view.h b/ash/system/ime_menu/ime_list_view.h index 8a3b440..5ede95e 100644 --- a/ash/system/ime_menu/ime_list_view.h +++ b/ash/system/ime_menu/ime_list_view.h
@@ -112,6 +112,10 @@ // The item view of the current selected IME. views::View* current_ime_view_ = nullptr; + + // The container for the IME list. Either a ScrollView (pre-QsRevamp) or a + // RoundedContainer (post-QsRevamp). + views::View* container_ = nullptr; }; class ASH_EXPORT ImeListViewTestApi {
diff --git a/ash/system/locale/locale_detailed_view.cc b/ash/system/locale/locale_detailed_view.cc index 4c78fc8..1e48de5 100644 --- a/ash/system/locale/locale_detailed_view.cc +++ b/ash/system/locale/locale_detailed_view.cc
@@ -4,6 +4,7 @@ #include "ash/system/locale/locale_detailed_view.h" +#include "ash/constants/ash_features.h" #include "ash/public/cpp/system_tray_client.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" @@ -49,7 +50,8 @@ checked_(checked) { views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON); - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + TriView* tri_view = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/false); AddChildView(tri_view); SetLayoutManager(std::make_unique<views::FillLayout>()); @@ -76,7 +78,8 @@ tri_view->AddView(TriView::Container::CENTER, display_name_view); if (checked_) { - views::ImageView* checked_image = TrayPopupUtils::CreateMainImageView(); + views::ImageView* checked_image = TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/false); checked_image->SetImage(gfx::CreateVectorIcon( kCheckCircleIcon, kMenuIconSize, color_provider->GetContentLayerColor(
diff --git a/ash/system/message_center/ash_notification_input_container.cc b/ash/system/message_center/ash_notification_input_container.cc index 92125f7..d805061 100644 --- a/ash/system/message_center/ash_notification_input_container.cc +++ b/ash/system/message_center/ash_notification_input_container.cc
@@ -9,6 +9,7 @@ #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" #include "ash/system/message_center/message_center_constants.h" +#include "ui/chromeos/styles/cros_tokens_color_mappings.h" #include "ui/color/color_id.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/rrect_f.h" @@ -101,13 +102,23 @@ void AshNotificationInputContainer::UpdateButtonImage() { if (!GetWidget()) return; - - button()->SetImage( + UpdateButtonState(); + button()->SetImageModel( views::Button::STATE_NORMAL, - gfx::CreateVectorIcon(kSendIcon, kInputReplyButtonSize, - ash::AshColorProvider::Get()->GetControlsLayerColor( - ash::AshColorProvider::ControlsLayerType:: - kControlBackgroundColorActive))); + ui::ImageModel::FromVectorIcon(kSendIcon, cros_tokens::kColorProminent, + kInputReplyButtonSize)); + button()->SetImageModel( + views::Button::STATE_DISABLED, + ui::ImageModel::FromVectorIcon(kSendIcon, cros_tokens::kColorDisabled, + kInputReplyButtonSize)); +} + +void AshNotificationInputContainer::UpdateButtonState() { + button()->SetEnabled(!IsInputEmpty()); +} + +bool AshNotificationInputContainer::IsInputEmpty() { + return textfield()->GetText().empty(); } void AshNotificationInputContainer::OnThemeChanged() {
diff --git a/ash/system/message_center/ash_notification_input_container.h b/ash/system/message_center/ash_notification_input_container.h index fc83bd3..db6ae43f 100644 --- a/ash/system/message_center/ash_notification_input_container.h +++ b/ash/system/message_center/ash_notification_input_container.h
@@ -24,6 +24,7 @@ ~AshNotificationInputContainer() override; private: + FRIEND_TEST_ALL_PREFIXES(AshNotificationViewTest, ButtonStateUpdated); // message_center::NotificationInputContainer: views::BoxLayout* InstallLayoutManager() override; views::InkDropContainerView* InstallInkDrop() override; @@ -33,6 +34,8 @@ gfx::Insets GetSendButtonPadding() const override; void SetSendButtonHighlightPath() override; void UpdateButtonImage() override; + void UpdateButtonState(); + bool IsInputEmpty(); // views::View: void OnThemeChanged() override;
diff --git a/ash/system/message_center/ash_notification_view_pixeltest.cc b/ash/system/message_center/ash_notification_view_pixeltest.cc index cdac2d4..bbb2a174 100644 --- a/ash/system/message_center/ash_notification_view_pixeltest.cc +++ b/ash/system/message_center/ash_notification_view_pixeltest.cc
@@ -2,14 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/shell.h" #include "ash/system/notification_center/notification_center_test_api.h" #include "ash/test/ash_test_base.h" #include "ash/test/ash_test_util.h" #include "ash/test/pixel/ash_pixel_differ.h" #include "ash/test/pixel/ash_pixel_test_init_params.h" -#include "base/time/time.h" #include "ui/base/models/image_model.h" +#include "ui/views/view.h" namespace ash { @@ -22,11 +21,11 @@ "Very Very Very Very Very Very Very Very Very Very Very Very Very Very " "Very Very Very Very Long Multiline Title"; -constexpr char kShortTitleScreenshot[] = "ash_notification_short_title.rev_0"; +constexpr char kShortTitleScreenshot[] = "ash_notification_short_title.rev_1"; constexpr char kMediumTitleScreenshot[] = - "ash_notification_multiline_medium_title.rev_0"; + "ash_notification_multiline_medium_title.rev_1"; constexpr char kLongTitleScreenshot[] = - "ash_notification_multiline_long_title.rev_0"; + "ash_notification_multiline_long_title.rev_1"; } // namespace @@ -37,14 +36,6 @@ std::pair<const char* /*notification title string*/, const char* /*screenshot name*/>> { public: - AshNotificationViewTitlePixelTest() - : AshTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} - AshNotificationViewTitlePixelTest(const AshNotificationViewTitlePixelTest&) = - delete; - AshNotificationViewTitlePixelTest& operator=( - const AshNotificationViewTitlePixelTest&) = delete; - ~AshNotificationViewTitlePixelTest() override = default; - // AshTestBase: absl::optional<pixel_test::InitParams> CreatePixelTestInitParams() const override { @@ -56,8 +47,7 @@ AshTestBase::SetUp(); // The `NotificationCenterTray` does not exist until the `QsRevamp` feature - // is enabled. We're only using the `NotificationCenterTestApi` in this file - // to create notifications, do not use for any other purpose. + // is enabled. test_api_ = std::make_unique<NotificationCenterTestApi>( /*notification_center_tray=*/nullptr); } @@ -89,18 +79,17 @@ ui::ImageModel::FromImageSkia(CreateSolidColorTestImage( gfx::Size(/*width=*/45, /*height=*/45), SK_ColorGREEN))); - // Allow `MessagePopupCollection` animations to complete. - task_environment()->FastForwardBy(base::Seconds(1)); + test_api()->ToggleBubble(); - // Make sure the popup exists and is visible. - views::View* notification_popup = test_api()->GetPopupViewForId(id); - ASSERT_TRUE(notification_popup); - EXPECT_TRUE(notification_popup->GetVisible()); + // Make sure the notification view exists and is visible. + views::View* notification_view = test_api()->GetNotificationViewForId(id); + ASSERT_TRUE(notification_view); + EXPECT_TRUE(notification_view->GetVisible()); // Compare pixels. const std::string screenshot = GetParam().second; EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( - screenshot, notification_popup)); + screenshot, notification_view)); } } // namespace ash
diff --git a/ash/system/message_center/ash_notification_view_unittest.cc b/ash/system/message_center/ash_notification_view_unittest.cc index c09fd1d8..d25e4602 100644 --- a/ash/system/message_center/ash_notification_view_unittest.cc +++ b/ash/system/message_center/ash_notification_view_unittest.cc
@@ -11,6 +11,7 @@ #include "ash/strings/grit/ash_strings.h" #include "ash/style/icon_button.h" #include "ash/system/message_center/ash_notification_expand_button.h" +#include "ash/system/message_center/ash_notification_input_container.h" #include "ash/system/message_center/message_center_style.h" #include "ash/system/message_center/metrics_utils.h" #include "ash/system/message_center/unified_message_center_bubble.h" @@ -39,6 +40,7 @@ #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/label.h" +#include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/flex_layout_view.h" #include "ui/views/test/button_test_api.h" @@ -1110,4 +1112,28 @@ notification_view()->ToggleExpand(); } +TEST_F(AshNotificationViewTest, ButtonStateUpdated) { + auto notification = CreateTestNotification(); + GetPrimaryUnifiedSystemTray()->ShowBubble(); + + notification_view()->UpdateWithNotification(*notification); + + auto* notification_view = + GetNotificationViewFromMessageCenter(notification->id()); + ash::AshNotificationInputContainer* inline_reply = + static_cast<AshNotificationInputContainer*>( + GetInlineReply(notification_view)); + + EXPECT_TRUE(inline_reply->textfield()->GetText().empty()); + + inline_reply->UpdateButtonImage(); + + EXPECT_FALSE(inline_reply->button()->GetEnabled()); + + inline_reply->textfield()->SetText(u"test"); + inline_reply->UpdateButtonImage(); + + EXPECT_TRUE(inline_reply->button()->GetEnabled()); +} + } // namespace ash
diff --git a/ash/system/network/network_list_header_view.cc b/ash/system/network/network_list_header_view.cc index 0151a35..d12fa61 100644 --- a/ash/system/network/network_list_header_view.cc +++ b/ash/system/network/network_list_header_view.cc
@@ -31,8 +31,9 @@ TrayPopupUtils::ConfigureAsStickyHeader(this); SetLayoutManager(std::make_unique<views::FillLayout>()); container_ = TrayPopupUtils::CreateSubHeaderRowView(/*start_visible=*/true); - container_->AddView(TriView::Container::START, - TrayPopupUtils::CreateMainImageView()); + container_->AddView( + TriView::Container::START, + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false)); AddChildView(container_); AddTitleView(label_id); }
diff --git a/ash/system/network/network_list_network_item_view.cc b/ash/system/network/network_list_network_item_view.cc index 3e80a91c..4e560332 100644 --- a/ash/system/network/network_list_network_item_view.cc +++ b/ash/system/network/network_list_network_item_view.cc
@@ -405,7 +405,7 @@ void NetworkListNetworkItemView::AddPolicyView() { std::unique_ptr<views::ImageView> controlled_icon( - TrayPopupUtils::CreateMainImageView()); + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false)); const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary); controlled_icon->SetImage(
diff --git a/ash/system/network/network_list_view.cc b/ash/system/network/network_list_view.cc index 6f4e722..38135796 100644 --- a/ash/system/network/network_list_view.cc +++ b/ash/system/network/network_list_view.cc
@@ -685,7 +685,8 @@ if (source != OncSource::kDevicePolicy && source != OncSource::kUserPolicy) return nullptr; - views::ImageView* controlled_icon = TrayPopupUtils::CreateMainImageView(); + views::ImageView* controlled_icon = + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false); controlled_icon->SetImage( gfx::CreateVectorIcon(kSystemMenuBusinessIcon, GetIconColor())); return controlled_icon; @@ -814,11 +815,13 @@ TriView* NetworkListView::CreateConnectionWarning() { // Set up layout and apply sticky row property. - TriView* connection_warning = TrayPopupUtils::CreateDefaultRowView(); + TriView* connection_warning = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/false); TrayPopupUtils::ConfigureAsStickyHeader(connection_warning); // Set 'info' icon on left side. - views::ImageView* image_view = TrayPopupUtils::CreateMainImageView(); + views::ImageView* image_view = + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false); image_view->SetImage( gfx::CreateVectorIcon(kSystemMenuInfoIcon, GetIconColor())); image_view->SetBackground(views::CreateSolidBackground(SK_ColorTRANSPARENT));
diff --git a/ash/system/network/network_list_view_controller_impl.cc b/ash/system/network/network_list_view_controller_impl.cc index 49da3cf..b77d065 100644 --- a/ash/system/network/network_list_view_controller_impl.cc +++ b/ash/system/network/network_list_view_controller_impl.cc
@@ -617,12 +617,12 @@ void NetworkListViewControllerImpl::ShowConnectionWarning() { // Set up layout and apply sticky row property. std::unique_ptr<TriView> connection_warning( - TrayPopupUtils::CreateDefaultRowView()); + TrayPopupUtils::CreateDefaultRowView(/*use_wide_layout=*/false)); TrayPopupUtils::ConfigureAsStickyHeader(connection_warning.get()); // Set 'info' icon on left side. - std::unique_ptr<views::ImageView> image_view = - base::WrapUnique(TrayPopupUtils::CreateMainImageView()); + std::unique_ptr<views::ImageView> image_view = base::WrapUnique( + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false)); image_view->SetImage(gfx::CreateVectorIcon( kSystemMenuInfoIcon, AshColorProvider::Get()->GetContentLayerColor(
diff --git a/ash/system/network/network_section_header_view.cc b/ash/system/network/network_section_header_view.cc index 47c8d84..aa453ce3 100644 --- a/ash/system/network/network_section_header_view.cc +++ b/ash/system/network/network_section_header_view.cc
@@ -169,8 +169,9 @@ TrayPopupUtils::ConfigureAsStickyHeader(this); SetLayoutManager(std::make_unique<views::FillLayout>()); container_ = TrayPopupUtils::CreateSubHeaderRowView(true); - container_->AddView(TriView::Container::START, - TrayPopupUtils::CreateMainImageView()); + container_->AddView( + TriView::Container::START, + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false)); AddChildView(container_); network_row_title_view_ = new NetworkRowTitleView(title_id_);
diff --git a/ash/system/network/vpn_list_view.cc b/ash/system/network/vpn_list_view.cc index b01b272..36b6d36dc 100644 --- a/ash/system/network/vpn_list_view.cc +++ b/ash/system/network/vpn_list_view.cc
@@ -126,8 +126,9 @@ TrayPopupUtils::ConfigureAsStickyHeader(this); SetLayoutManager(std::make_unique<views::FillLayout>()); TriView* tri_view = TrayPopupUtils::CreateSubHeaderRowView(true); - tri_view->AddView(TriView::Container::START, - TrayPopupUtils::CreateMainImageView()); + tri_view->AddView( + TriView::Container::START, + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false)); AddChildView(tri_view); // Add the VPN label. @@ -176,7 +177,7 @@ private: views::ImageView* GetPolicyIndicatorIcon() { views::ImageView* policy_indicator_icon = - TrayPopupUtils::CreateMainImageView(); + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false); policy_indicator_icon->SetImage(gfx::CreateVectorIcon( kSystemMenuBusinessIcon, AshColorProvider::Get()->GetContentLayerColor(
diff --git a/ash/system/notification_center/notification_center_test_api.cc b/ash/system/notification_center/notification_center_test_api.cc index 7200ad8..07d14d64 100644 --- a/ash/system/notification_center/notification_center_test_api.cc +++ b/ash/system/notification_center/notification_center_test_api.cc
@@ -8,9 +8,11 @@ #include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/system/message_center/ash_message_popup_collection.h" +#include "ash/system/message_center/unified_message_center_bubble.h" #include "ash/system/notification_center/notification_center_bubble.h" #include "ash/system/notification_center/notification_center_tray.h" #include "ash/system/notification_center/notification_center_view.h" +#include "ash/system/notification_center/notification_list_view.h" #include "ash/system/notification_center/stacked_notification_bar.h" #include "ash/system/unified/unified_system_tray.h" #include "base/strings/string_number_conversions.h" @@ -28,8 +30,19 @@ void NotificationCenterTestApi::ToggleBubble() { auto event_generator = std::make_unique<ui::test::EventGenerator>(Shell::GetPrimaryRootWindow()); - event_generator->MoveMouseTo( - notification_center_tray_->GetBoundsInScreen().CenterPoint()); + + gfx::Point click_location = + notification_center_tray_ + ? notification_center_tray_->GetBoundsInScreen().CenterPoint() + : Shell::Get() + ->GetPrimaryRootWindowController() + ->shelf() + ->status_area_widget() + ->unified_system_tray() + ->GetBoundsInScreen() + .CenterPoint(); + + event_generator->MoveMouseTo(click_location); event_generator->ClickLeftButton(); } @@ -55,6 +68,10 @@ /*by_user=*/true); } +size_t NotificationCenterTestApi::GetNotificationCount() const { + return message_center::MessageCenter::Get()->NotificationCount(); +} + bool NotificationCenterTestApi::IsBubbleShown() { return notification_center_tray_->is_active() && GetWidget()->IsVisible(); } @@ -67,6 +84,15 @@ return notification_center_tray_->GetVisible(); } +views::View* NotificationCenterTestApi::GetNotificationViewForId( + const std::string& id) { + // Ensure this api is only called when the notification list view exists, i.e. + // The notification center bubble is open. + DCHECK(GetNotificationListView()); + + return GetNotificationListView()->GetMessageViewForNotificationId(id); +} + views::View* NotificationCenterTestApi::GetPopupViewForId( const std::string& id) { // TODO(b/259459804): Move `MessagePopupCollection` to be owned by @@ -105,6 +131,25 @@ return base::NumberToString(notification_id_++); } +NotificationListView* NotificationCenterTestApi::GetNotificationListView() { + DCHECK(message_center::MessageCenter::Get()->IsMessageCenterVisible()); + + if (notification_center_tray_) { + return notification_center_tray_->bubble_->notification_center_view_ + ->notification_list_view(); + } + + auto* unified_system_tray = Shell::Get() + ->GetPrimaryRootWindowController() + ->shelf() + ->GetStatusAreaWidget() + ->unified_system_tray(); + + return unified_system_tray->message_center_bubble() + ->notification_center_view() + ->notification_list_view(); +} + std::unique_ptr<message_center::Notification> NotificationCenterTestApi::CreateNotification(const std::string& id, const std::string& title, @@ -118,4 +163,4 @@ new message_center::NotificationDelegate()); } -} // namespace ash \ No newline at end of file +} // namespace ash
diff --git a/ash/system/notification_center/notification_center_test_api.h b/ash/system/notification_center/notification_center_test_api.h index cb22191..b9573d6 100644 --- a/ash/system/notification_center/notification_center_test_api.h +++ b/ash/system/notification_center/notification_center_test_api.h
@@ -24,6 +24,7 @@ namespace ash { class NotificationCenterBubble; +class NotificationListView; class NotificationCenterTray; // Utility class to facilitate easier testing of the notification center. @@ -50,6 +51,9 @@ // Removes the notification associated with the provided id. void RemoveNotification(const std::string& id); + // Returns the number of notifications in the current notification list. + size_t GetNotificationCount() const; + // Returns true if `NotificationCenterBubble` is shown, false otherwise. bool IsBubbleShown(); @@ -61,6 +65,10 @@ // otherwise. bool IsTrayShown(); + // Returns the notification view associated with the provided notification id. + // Should be only used when the notifications bubble is open. + views::View* GetNotificationViewForId(const std::string& id); + // Returns the popup view associated with the provided notification id, // nullptr otherwise. views::View* GetPopupViewForId(const std::string& id); @@ -86,6 +94,8 @@ private: std::string GenerateNotificationId(); + NotificationListView* GetNotificationListView(); + std::unique_ptr<message_center::Notification> CreateNotification( const std::string& id, const std::string& title, @@ -98,4 +108,4 @@ } // namespace ash -#endif // ASH_SYSTEM_NOTIFICATION_CENTER_NOTIFICATION_CENTER_TEST_API_H_ \ No newline at end of file +#endif // ASH_SYSTEM_NOTIFICATION_CENTER_NOTIFICATION_CENTER_TEST_API_H_
diff --git a/ash/system/notification_center/notification_center_tray_unittest.cc b/ash/system/notification_center/notification_center_tray_unittest.cc index 29397be..6b60671 100644 --- a/ash/system/notification_center/notification_center_tray_unittest.cc +++ b/ash/system/notification_center/notification_center_tray_unittest.cc
@@ -5,15 +5,21 @@ #include "ash/system/notification_center/notification_center_tray.h" #include "ash/constants/ash_features.h" +#include "ash/public/cpp/system/toast_manager.h" +#include "ash/public/cpp/test/shell_test_api.h" #include "ash/system/notification_center/notification_center_test_api.h" #include "ash/system/status_area_widget.h" #include "ash/system/status_area_widget_test_helper.h" #include "ash/test/ash_test_base.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" +#include "ui/base/accelerators/accelerator.h" namespace ash { +constexpr char kNotificationCenterTrayNoNotificationsToastId[] = + "notification_center_tray_toast_ids.no_notifications"; + class NotificationCenterTrayTest : public AshTestBase { public: NotificationCenterTrayTest() = default; @@ -136,12 +142,38 @@ EXPECT_TRUE(test_api()->IsPopupShown(id)); } +// Keyboard accelerator shows/hides the bubble. +TEST_F(NotificationCenterTrayTest, AcceleratorTogglesBubble) { + test_api()->AddNotification(); + EXPECT_FALSE(test_api()->IsBubbleShown()); + // Pressing the accelerator should show the bubble. + ShellTestApi().PressAccelerator( + ui::Accelerator(ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)); + EXPECT_TRUE(test_api()->IsBubbleShown()); + // Pressing the acccelerator again should hide the bubble. + ShellTestApi().PressAccelerator( + ui::Accelerator(ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)); + EXPECT_FALSE(test_api()->IsBubbleShown()); +} + +// Keyboard accelerator shows a toast when there are no notifications. +TEST_F(NotificationCenterTrayTest, AcceleratorShowsToastWhenNoNotifications) { + ASSERT_EQ(test_api()->GetNotificationCount(), 0u); + EXPECT_FALSE(ToastManager::Get()->IsRunning( + kNotificationCenterTrayNoNotificationsToastId)); + // Pressing the accelerator should show the toast and not the bubble. + ShellTestApi().PressAccelerator( + ui::Accelerator(ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)); + EXPECT_TRUE(ToastManager::Get()->IsRunning( + kNotificationCenterTrayNoNotificationsToastId)); + EXPECT_FALSE(test_api()->IsBubbleShown()); +} + // TODO(b/252875025): // Add following test cases as we add relevant functionality: // - Focus Change dismissing bubble // - Popup notifications are dismissed when the bubble appears. // - Display removed while the bubble is shown. // - Tablet mode transition with the bubble open. -// - Open/Close bubble by keyboard shortcut. } // namespace ash
diff --git a/ash/system/phonehub/app_stream_launcher_view.cc b/ash/system/phonehub/app_stream_launcher_view.cc index 4481993f..d46dd11 100644 --- a/ash/system/phonehub/app_stream_launcher_view.cc +++ b/ash/system/phonehub/app_stream_launcher_view.cc
@@ -3,24 +3,21 @@ // found in the LICENSE file. #include "ash/system/phonehub/app_stream_launcher_view.h" -#include "ash/controls/rounded_scroll_bar.h" -#include "ash/resources/vector_icons/vector_icons.h" #include <cmath> #include <memory> +#include <string> -#include "ash/components/phonehub/multidevice_feature_access_manager.h" +#include "ash/components/phonehub/notification.h" #include "ash/components/phonehub/phone_hub_manager.h" #include "ash/components/phonehub/user_action_recorder.h" #include "ash/constants/ash_features.h" +#include "ash/controls/rounded_scroll_bar.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/phonehub/camera_roll_view.h" -#include "ash/system/phonehub/multidevice_feature_opt_in_view.h" -#include "ash/system/phonehub/phone_hub_recent_apps_view.h" +#include "ash/system/phonehub/app_stream_launcher_item.h" +#include "ash/system/phonehub/app_stream_launcher_view.h" #include "ash/system/phonehub/phone_hub_view_ids.h" -#include "ash/system/phonehub/phone_status_view.h" -#include "ash/system/phonehub/quick_actions_view.h" -#include "ash/system/phonehub/task_continuation_view.h" #include "ash/system/phonehub/ui_constants.h" #include "ash/system/tray/tray_constants.h" #include "ui/base/l10n/l10n_util.h" @@ -63,9 +60,9 @@ constexpr int kHorizontalInteriorMargin = 16; // Number of columns of apps in the grid -constexpr int kColumns = 5; +constexpr int kColumns = 4; -constexpr int kRowHeight = 60; +constexpr int kRowHeight = 80; // The padding between different sections within the apps page. Also used for // interior apps page container margin. @@ -99,9 +96,16 @@ .WithWeight(1)); phone_hub_manager->GetUserActionRecorder()->RecordUiOpened(); + + UpdateFromDataModel(); + if (phone_hub_manager->GetAppStreamLauncherDataModel()) + phone_hub_manager->GetAppStreamLauncherDataModel()->AddObserver(this); } -AppStreamLauncherView::~AppStreamLauncherView() = default; +AppStreamLauncherView::~AppStreamLauncherView() { + if (phone_hub_manager_->GetAppStreamLauncherDataModel()) + phone_hub_manager_->GetAppStreamLauncherDataModel()->RemoveObserver(this); +} // The behavior is inspired from ash/app_list/views/app_list_bubble_apps_page.cc std::unique_ptr<views::View> AppStreamLauncherView::CreateAppListView() { @@ -159,29 +163,42 @@ table_layout->AddRows(ceil((double)n_apps / kColumns), views::TableLayout::kFixedSize, kRowHeight); - for (int i = 0; i < n_apps; i++) { - std::unique_ptr<View> view = CreateViewForItemAtIndex(i); - view->SetPreferredSize(gfx::Size(50, 50)); - items_container_->AddChildView(std::move(view)); - } scroll_view->SetContents(std::move(scroll_contents)); return scroll_view; } -std::unique_ptr<views::View> AppStreamLauncherView::CreateViewForItemAtIndex( - size_t index) { - // TODO(nayebi): Replace this plceholder with the real implementation of the - // icon+text. - auto view = std::make_unique<views::LabelButton>( - base::BindRepeating(&AppStreamLauncherView::AppIconActivated, - base::Unretained(this)), - u"ICON"); - view->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_CENTER); - return view; +void AppStreamLauncherView::AppIconActivated( + phonehub::Notification::AppMetadata app, + const ui::Event& event) { + auto* interaction_handler_ = + phone_hub_manager_->GetRecentAppsInteractionHandler(); + if (!interaction_handler_) + return; + interaction_handler_->NotifyRecentAppClicked(app); } -void AppStreamLauncherView::AppIconActivated() {} +void AppStreamLauncherView::UpdateFromDataModel() { + if (!items_container_) + return; + items_container_->RemoveAllChildViews(); + if (!phone_hub_manager_->GetAppStreamLauncherDataModel()) + return; + const std::vector<phonehub::Notification::AppMetadata>* apps_list = + phone_hub_manager_->GetAppStreamLauncherDataModel() + ->GetAppsListSortedByName(); + for (auto& app : *apps_list) { + items_container_->AddChildView(CreateItemView(app)); + } +} + +std::unique_ptr<views::View> AppStreamLauncherView::CreateItemView( + const phonehub::Notification::AppMetadata& app) { + return std::make_unique<AppStreamLauncherItem>( + base::BindRepeating(&AppStreamLauncherView::AppIconActivated, + base::Unretained(this), app), + app); +} std::unique_ptr<views::View> AppStreamLauncherView::CreateHeaderView() { auto header = std::make_unique<views::View>(); @@ -260,4 +277,10 @@ return phone_hub_metrics::Screen::kMiniLauncher; } +void AppStreamLauncherView::OnAppListChanged() { + if (!features::IsEcheSWAEnabled() || !features::IsEcheLauncherEnabled()) + return; + UpdateFromDataModel(); +} + } // namespace ash
diff --git a/ash/system/phonehub/app_stream_launcher_view.h b/ash/system/phonehub/app_stream_launcher_view.h index c472285a..fd2f444 100644 --- a/ash/system/phonehub/app_stream_launcher_view.h +++ b/ash/system/phonehub/app_stream_launcher_view.h
@@ -5,8 +5,13 @@ #ifndef ASH_SYSTEM_PHONEHUB_APP_STREAM_LAUNCHER_VIEW_H_ #define ASH_SYSTEM_PHONEHUB_APP_STREAM_LAUNCHER_VIEW_H_ +#include <cstdint> #include <memory> #include "ash/ash_export.h" +#include "ash/components/phonehub/app_stream_launcher_data_model.h" +#include "ash/components/phonehub/notification.h" +#include "ash/components/phonehub/recent_app_click_observer.h" +#include "ash/components/phonehub/recent_apps_interaction_handler.h" #include "ash/system/phonehub/phone_hub_content_view.h" #include "ui/gfx/vector_icon_types.h" #include "ui/views/controls/button/button.h" @@ -23,7 +28,9 @@ // A view of the Phone Hub panel, displaying the apps that user can launch for // app streaming. -class ASH_EXPORT AppStreamLauncherView : public PhoneHubContentView { +class ASH_EXPORT AppStreamLauncherView + : public PhoneHubContentView, + public phonehub::AppStreamLauncherDataModel::Observer { public: explicit AppStreamLauncherView(phonehub::PhoneHubManager* phone_hub_manager); ~AppStreamLauncherView() override; @@ -36,18 +43,26 @@ // PhoneHubContentView: phone_hub_metrics::Screen GetScreenForMetrics() const override; + // phonehub::AppStreamLauncherDataModel::Observer: + void OnAppListChanged() override; + private: friend class AppStreamLauncherViewTest; FRIEND_TEST_ALL_PREFIXES(AppStreamLauncherViewTest, OpenView); std::unique_ptr<views::View> CreateAppListView(); + std::unique_ptr<views::View> CreateItemView( + const phonehub::Notification::AppMetadata& app); std::unique_ptr<views::View> CreateHeaderView(); std::unique_ptr<views::Button> CreateButton( views::Button::PressedCallback callback, const gfx::VectorIcon& icon, int message_id); - std::unique_ptr<views::View> CreateViewForItemAtIndex(size_t index); - void AppIconActivated(); + void AppIconActivated(phonehub::Notification::AppMetadata app, + const ui::Event& event); + + // Update the UI based on the information in the data model. + void UpdateFromDataModel(); // Handles the click on the "back" arrow in the header. void OnArrowBackActivated();
diff --git a/ash/system/phonehub/phone_connected_view.cc b/ash/system/phonehub/phone_connected_view.cc index c7f6a6c..e51788c2 100644 --- a/ash/system/phonehub/phone_connected_view.cc +++ b/ash/system/phonehub/phone_connected_view.cc
@@ -85,8 +85,8 @@ auto* recent_apps_handler = phone_hub_manager->GetRecentAppsInteractionHandler(); if (features::IsEcheSWAEnabled() && recent_apps_handler) { - setup_layered_view(AddChildView( - std::make_unique<PhoneHubRecentAppsView>(recent_apps_handler))); + setup_layered_view(AddChildView(std::make_unique<PhoneHubRecentAppsView>( + recent_apps_handler, phone_hub_manager))); } phone_hub_manager->GetUserActionRecorder()->RecordUiOpened();
diff --git a/ash/system/phonehub/phone_hub_notification_controller.cc b/ash/system/phonehub/phone_hub_notification_controller.cc index b8f22b5..56e4ad81 100644 --- a/ash/system/phonehub/phone_hub_notification_controller.cc +++ b/ash/system/phonehub/phone_hub_notification_controller.cc
@@ -224,6 +224,8 @@ // message_center::NotificationView: void OnNotificationInputSubmit(size_t index, const std::u16string& text) override { + if (text.empty()) + return; AshNotificationView::OnNotificationInputSubmit(index, text); DCHECK(reply_button_);
diff --git a/ash/system/phonehub/phone_hub_recent_apps_view.cc b/ash/system/phonehub/phone_hub_recent_apps_view.cc index 95779c63..f3bae8e 100644 --- a/ash/system/phonehub/phone_hub_recent_apps_view.cc +++ b/ash/system/phonehub/phone_hub_recent_apps_view.cc
@@ -9,6 +9,7 @@ #include <vector> #include "ash/components/phonehub/notification.h" +#include "ash/components/phonehub/phone_hub_manager.h" #include "ash/constants/ash_features.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/strings/grit/ash_strings.h" @@ -108,8 +109,10 @@ }; PhoneHubRecentAppsView::PhoneHubRecentAppsView( - phonehub::RecentAppsInteractionHandler* recent_apps_interaction_handler) - : recent_apps_interaction_handler_(recent_apps_interaction_handler) { + phonehub::RecentAppsInteractionHandler* recent_apps_interaction_handler, + phonehub::PhoneHubManager* phone_hub_manager) + : recent_apps_interaction_handler_(recent_apps_interaction_handler), + phone_hub_manager_(phone_hub_manager) { SetID(PhoneHubViewID::kPhoneHubRecentAppsView); auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); @@ -247,8 +250,13 @@ PreferredSizeChanged(); } -// TODO(b/259160267): Add function when full apps list view is ready. -void PhoneHubRecentAppsView::SwitchToFullAppsList() {} +void PhoneHubRecentAppsView::SwitchToFullAppsList() { + if (!features::IsEcheLauncherEnabled()) { + return; + } + phone_hub_manager_->GetAppStreamLauncherDataModel() + ->SetShouldShowMiniLauncher(true); +} std::unique_ptr<views::ImageButton> PhoneHubRecentAppsView::GenerateMoreAppsButton() {
diff --git a/ash/system/phonehub/phone_hub_recent_apps_view.h b/ash/system/phonehub/phone_hub_recent_apps_view.h index 9aed488..325b325 100644 --- a/ash/system/phonehub/phone_hub_recent_apps_view.h +++ b/ash/system/phonehub/phone_hub_recent_apps_view.h
@@ -7,6 +7,7 @@ #include <memory> #include "ash/ash_export.h" +#include "ash/components/phonehub/phone_hub_manager.h" #include "ash/components/phonehub/recent_apps_interaction_handler.h" #include "base/gtest_prod_util.h" #include "ui/views/controls/button/image_button.h" @@ -22,7 +23,8 @@ public phonehub::RecentAppsInteractionHandler::Observer { public: explicit PhoneHubRecentAppsView( - phonehub::RecentAppsInteractionHandler* recent_apps_interaction_handler); + phonehub::RecentAppsInteractionHandler* recent_apps_interaction_handler, + phonehub::PhoneHubManager* phone_hub_manager); ~PhoneHubRecentAppsView() override; PhoneHubRecentAppsView(PhoneHubRecentAppsView&) = delete; PhoneHubRecentAppsView operator=(PhoneHubRecentAppsView&) = delete; @@ -74,6 +76,7 @@ std::vector<views::View*> recent_app_button_list_; phonehub::RecentAppsInteractionHandler* recent_apps_interaction_handler_ = nullptr; + phonehub::PhoneHubManager* phone_hub_manager_ = nullptr; PlaceholderView* placeholder_view_ = nullptr; };
diff --git a/ash/system/phonehub/phone_hub_recent_apps_view_unittest.cc b/ash/system/phonehub/phone_hub_recent_apps_view_unittest.cc index 09e5768..4ef2ade 100644 --- a/ash/system/phonehub/phone_hub_recent_apps_view_unittest.cc +++ b/ash/system/phonehub/phone_hub_recent_apps_view_unittest.cc
@@ -4,6 +4,8 @@ #include "ash/system/phonehub/phone_hub_recent_apps_view.h" +#include "ash/components/phonehub/app_stream_launcher_data_model.h" +#include "ash/components/phonehub/fake_phone_hub_manager.h" #include "ash/components/phonehub/fake_recent_apps_interaction_handler.h" #include "ash/components/phonehub/notification.h" #include "ash/constants/ash_features.h" @@ -38,11 +40,12 @@ AshTestBase::SetUp(); feature_list_.InitWithFeatures( - /*enabled_features=*/{chromeos::features::kEcheLauncher}, + /*enabled_features=*/{chromeos::features::kEcheLauncher, + chromeos::features::kEcheSWA}, /*disabled_features=*/{}); phone_hub_recent_apps_view_ = std::make_unique<PhoneHubRecentAppsView>( - &fake_recent_apps_interaction_handler_); + &fake_recent_apps_interaction_handler_, &fake_phone_hub_manager_); } void TearDown() override { @@ -73,10 +76,16 @@ fake_recent_apps_interaction_handler_.OnFeatureStateChanged(feature_state); } + bool AppStreamLauncherShowState() { + return fake_phone_hub_manager_.fake_app_stream_launcher_data_model() + ->GetShouldShowMiniLauncher(); + } + private: std::unique_ptr<PhoneHubRecentAppsView> phone_hub_recent_apps_view_; phonehub::FakeRecentAppsInteractionHandler fake_recent_apps_interaction_handler_; + phonehub::FakePhoneHubManager fake_phone_hub_manager_; base::test::ScopedFeatureList feature_list_; }; @@ -169,6 +178,7 @@ size_t expected_number_of_button_be_clicked = 5; EXPECT_EQ(expected_number_of_button_be_clicked, PackageNameToClickCount(kPackageName)); + EXPECT_TRUE(AppStreamLauncherShowState()); } } // namespace ash
diff --git a/ash/system/phonehub/phone_hub_tray.cc b/ash/system/phonehub/phone_hub_tray.cc index 22867d98..6dc9dc1 100644 --- a/ash/system/phonehub/phone_hub_tray.cc +++ b/ash/system/phonehub/phone_hub_tray.cc
@@ -373,7 +373,7 @@ } void PhoneHubTray::UpdateHeaderVisibility() { - if (!features::IsEcheSWAEnabled()) + if (!features::IsEcheLauncherEnabled()) return; if (!phone_status_view_) return;
diff --git a/ash/system/phonehub/phone_hub_ui_controller.cc b/ash/system/phonehub/phone_hub_ui_controller.cc index 2bbcb41..901dc218 100644 --- a/ash/system/phonehub/phone_hub_ui_controller.cc +++ b/ash/system/phonehub/phone_hub_ui_controller.cc
@@ -151,7 +151,7 @@ if (phone_hub_manager_) { phone_hub_manager_->GetFeatureStatusProvider()->AddObserver(this); phone_hub_manager_->GetOnboardingUiTracker()->AddObserver(this); - if (features::IsEcheSWAEnabled()) + if (features::IsEcheLauncherEnabled()) phone_hub_manager_->GetAppStreamLauncherDataModel()->AddObserver(this); phone_hub_manager_->GetPhoneModel()->AddObserver(this); } @@ -303,7 +303,7 @@ } void PhoneHubUiController::OnShouldShowMiniLauncherChanged() { - if (!features::IsEcheSWAEnabled()) + if (!features::IsEcheLauncherEnabled()) return; UpdateUiState(GetUiStateFromPhoneHubManager()); } @@ -334,7 +334,7 @@ PhoneHubUiController::GetUiStateFromPhoneHubManager() { PhoneHubUiController::UiState ui_state = GetUiStateFromPhoneHubManagerInternal(); - if (features::IsEcheSWAEnabled() && + if (features::IsEcheLauncherEnabled() && (ui_state != PhoneHubUiController::UiState::kMiniLauncher) && phone_hub_manager_ && phone_hub_manager_->GetAppStreamLauncherDataModel()) {
diff --git a/ash/system/time/calendar_event_list_item_view.cc b/ash/system/time/calendar_event_list_item_view.cc index 980bd45a..dbb6c5f 100644 --- a/ash/system/time/calendar_event_list_item_view.cc +++ b/ash/system/time/calendar_event_list_item_view.cc
@@ -198,7 +198,8 @@ // Creates a `TriView` which carries the `color_dot`, `summary_` and // `time_range_`. - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + TriView* tri_view = + TrayPopupUtils::CreateDefaultRowView(/*use_wide_layout=*/false); tri_view->SetMinSize( TriView::Container::START, gfx::Size(kColorDotViewSize,
diff --git a/ash/system/time/calendar_view.cc b/ash/system/time/calendar_view.cc index 1532940..868f5f5 100644 --- a/ash/system/time/calendar_view.cc +++ b/ash/system/time/calendar_view.cc
@@ -410,7 +410,8 @@ header_ = header_container->AddChildView(std::move(header)); temp_header_ = header_container->AddChildView(std::move(temp_header)); - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + TriView* tri_view = + TrayPopupUtils::CreateDefaultRowView(/*use_wide_layout=*/false); tri_view->SetBorder(views::CreateEmptyBorder( gfx::Insets::TLBR(kLabelVerticalPadding, kContentHorizontalPadding, 0, kContentHorizontalPadding - kChevronPadding)));
diff --git a/ash/system/tray/hover_highlight_view.cc b/ash/system/tray/hover_highlight_view.cc index 869323f..1cca363b8 100644 --- a/ash/system/tray/hover_highlight_view.cc +++ b/ash/system/tray/hover_highlight_view.cc
@@ -6,6 +6,7 @@ #include <string> +#include "ash/constants/ash_features.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_id.h" @@ -42,7 +43,8 @@ DCHECK(is_populated_); DCHECK(!right_view_); - views::ImageView* right_icon = TrayPopupUtils::CreateMainImageView(); + views::ImageView* right_icon = TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/features::IsQsRevampEnabled()); right_icon->SetImage(image); AddRightView(right_icon); } @@ -93,7 +95,8 @@ const std::u16string& text) { DCHECK(!is_populated_); - std::unique_ptr<views::ImageView> icon(TrayPopupUtils::CreateMainImageView()); + std::unique_ptr<views::ImageView> icon(TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/features::IsQsRevampEnabled())); icon->SetImage(image); icon->SetEnabled(GetEnabled()); @@ -104,7 +107,8 @@ const std::u16string& text) { DCHECK(!is_populated_); - std::unique_ptr<views::ImageView> icon(TrayPopupUtils::CreateMainImageView()); + std::unique_ptr<views::ImageView> icon(TrayPopupUtils::CreateMainImageView( + /*use_wide_layout=*/features::IsQsRevampEnabled())); icon->SetImage(image); icon->SetEnabled(GetEnabled()); @@ -118,7 +122,8 @@ is_populated_ = true; SetLayoutManager(std::make_unique<views::FillLayout>()); - tri_view_ = TrayPopupUtils::CreateDefaultRowView(); + tri_view_ = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/features::IsQsRevampEnabled()); AddChildView(tri_view_); left_view_ = view.get(); @@ -148,7 +153,8 @@ is_populated_ = true; SetLayoutManager(std::make_unique<views::FillLayout>()); - tri_view_ = TrayPopupUtils::CreateDefaultRowView(); + tri_view_ = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/features::IsQsRevampEnabled()); AddChildView(tri_view_); text_label_ = TrayPopupUtils::CreateUnfocusableLabel();
diff --git a/ash/system/tray/tray_constants.h b/ash/system/tray/tray_constants.h index f78e9c5..49a3445 100644 --- a/ash/system/tray/tray_constants.h +++ b/ash/system/tray/tray_constants.h
@@ -44,12 +44,21 @@ // in the system menu. constexpr int kTrayPopupLabelHorizontalPadding = 4; +// The padding used on the left and right of labels with QsRevamp. +constexpr int kQsPopupLabelHorizontalPadding = 16; + +// The padding used on the top and bottom of labels. +constexpr int kTrayPopupLabelVerticalPadding = 8; + // The minimum/default height of the rows in the system tray menu. constexpr int kTrayPopupItemMinHeight = 48; // The width used for the first region of the row (which holds an image). constexpr int kTrayPopupItemMinStartWidth = 48; +// The width used for the first region of the row (an image) with QsRevamp. +constexpr int kQsPopupItemMinStartWidth = 20; + // The size of the icons appearing in the material design system menu. constexpr int kMenuIconSize = 20; @@ -57,6 +66,9 @@ constexpr int kTrayPopupItemMinEndWidth = kMenuIconSize + 2 * kTrayPopupButtonEndMargin; +// The width used for the end region of a row with QsRevamp. +constexpr int kQsPopupItemMinEndWidth = 20; + // Padding used on right side of labels to keep minimum distance to the next // item. This applies to all labels in the system menu. constexpr int kTrayPopupLabelRightPadding = 8; @@ -84,8 +96,16 @@ constexpr int kMenuButtonSize = 48; // The vertical padding for the system menu separator. constexpr int kMenuSeparatorVerticalPadding = 4; -// The horizontal padding for the system menu separator. + +// Additional margin on the left edge of the tray menu. constexpr int kMenuExtraMarginFromLeftEdge = 4; + +// Additional margin on the left edge of the quick settings menu with QsRevamp. +constexpr int kQsExtraMarginFromLeftEdge = 24; + +// Default margin on right edge of the quick settings menu with QsRevamp. +constexpr int kQsExtraMarginsFromRightEdge = 18; + // The visual padding to the left of icons in the system menu. constexpr int kMenuEdgeEffectivePadding = kMenuExtraMarginFromLeftEdge + (kMenuButtonSize - kMenuIconSize) / 2;
diff --git a/ash/system/tray/tray_detailed_view.cc b/ash/system/tray/tray_detailed_view.cc index 120efd40..40180a4 100644 --- a/ash/system/tray/tray_detailed_view.cc +++ b/ash/system/tray/tray_detailed_view.cc
@@ -502,7 +502,8 @@ TrayPopupUtils::FontStyle::kSubHeader); header->AddView(TriView::Container::CENTER, sub_header_label_); - sub_header_image_view_ = TrayPopupUtils::CreateMainImageView(); + sub_header_image_view_ = + TrayPopupUtils::CreateMainImageView(/*use_wide_layout=*/false); sub_header_icon_ = &icon; sub_header_image_view_->SetImage(gfx::CreateVectorIcon( icon, color_provider->GetContentLayerColor(
diff --git a/ash/system/tray/tray_info_label.cc b/ash/system/tray/tray_info_label.cc index c42a4498..403ee02 100644 --- a/ash/system/tray/tray_info_label.cc +++ b/ash/system/tray/tray_info_label.cc
@@ -15,7 +15,8 @@ : label_(TrayPopupUtils::CreateDefaultLabel()) { SetLayoutManager(std::make_unique<views::FillLayout>()); - TriView* tri_view = TrayPopupUtils::CreateDefaultRowView(); + TriView* tri_view = TrayPopupUtils::CreateDefaultRowView( + /*use_wide_layout=*/false); tri_view->SetInsets(gfx::Insets::TLBR( 0, kMenuExtraMarginFromLeftEdge + kTrayPopupItemMinStartWidth, 0, kTrayPopupPaddingHorizontal));
diff --git a/ash/system/tray/tray_popup_utils.cc b/ash/system/tray/tray_popup_utils.cc index 2ed06881..5dedd6ca 100644 --- a/ash/system/tray/tray_popup_utils.cc +++ b/ash/system/tray/tray_popup_utils.cc
@@ -47,11 +47,14 @@ // Creates a layout manager that positions Views vertically. The Views will be // stretched horizontally and centered vertically. -std::unique_ptr<views::LayoutManager> CreateDefaultCenterLayoutManager() { - // TODO(bruthig): Use constants instead of magic numbers. +std::unique_ptr<views::LayoutManager> CreateDefaultCenterLayoutManager( + bool use_wide_layout) { + const auto insets = + gfx::Insets::VH(kTrayPopupLabelVerticalPadding, + use_wide_layout ? kQsPopupLabelHorizontalPadding + : kTrayPopupLabelHorizontalPadding); auto box_layout = std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kVertical, - gfx::Insets::VH(8, kTrayPopupLabelHorizontalPadding)); + views::BoxLayout::Orientation::kVertical, insets); box_layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); box_layout->set_cross_axis_alignment( @@ -72,13 +75,14 @@ } std::unique_ptr<views::LayoutManager> CreateDefaultLayoutManager( - TriView::Container container) { + TriView::Container container, + bool use_wide_layout) { switch (container) { case TriView::Container::START: case TriView::Container::END: return CreateDefaultEndsLayoutManager(); case TriView::Container::CENTER: - return CreateDefaultCenterLayoutManager(); + return CreateDefaultCenterLayoutManager(use_wide_layout); } // Required by some compilers. NOTREACHED(); @@ -88,17 +92,20 @@ // Configures the default size and flex value for the specified |container| // of the given |tri_view|. Used by CreateDefaultRowView(). void ConfigureDefaultSizeAndFlex(TriView* tri_view, - TriView::Container container) { + TriView::Container container, + bool use_wide_layout) { int min_width = 0; switch (container) { case TriView::Container::START: - min_width = kTrayPopupItemMinStartWidth; + min_width = use_wide_layout ? kQsPopupItemMinStartWidth + : kTrayPopupItemMinStartWidth; break; case TriView::Container::CENTER: tri_view->SetFlexForContainer(TriView::Container::CENTER, 1.f); break; case TriView::Container::END: - min_width = kTrayPopupItemMinEndWidth; + min_width = + use_wide_layout ? kQsPopupItemMinEndWidth : kTrayPopupItemMinEndWidth; break; } @@ -143,24 +150,24 @@ } // namespace -TriView* TrayPopupUtils::CreateDefaultRowView() { - TriView* tri_view = CreateMultiTargetRowView(); +TriView* TrayPopupUtils::CreateDefaultRowView(bool use_wide_layout) { + TriView* tri_view = CreateMultiTargetRowView(use_wide_layout); tri_view->SetContainerLayout( TriView::Container::START, - CreateDefaultLayoutManager(TriView::Container::START)); + CreateDefaultLayoutManager(TriView::Container::START, use_wide_layout)); tri_view->SetContainerLayout( TriView::Container::CENTER, - CreateDefaultLayoutManager(TriView::Container::CENTER)); + CreateDefaultLayoutManager(TriView::Container::CENTER, use_wide_layout)); tri_view->SetContainerLayout( TriView::Container::END, - CreateDefaultLayoutManager(TriView::Container::END)); + CreateDefaultLayoutManager(TriView::Container::END, use_wide_layout)); return tri_view; } TriView* TrayPopupUtils::CreateSubHeaderRowView(bool start_visible) { - TriView* tri_view = CreateDefaultRowView(); + TriView* tri_view = CreateDefaultRowView(/*use_wide_layout=*/false); if (!start_visible) { tri_view->SetInsets(gfx::Insets::TLBR( 0, kTrayPopupPaddingHorizontal - kTrayPopupLabelHorizontalPadding, 0, @@ -170,14 +177,21 @@ return tri_view; } -TriView* TrayPopupUtils::CreateMultiTargetRowView() { +TriView* TrayPopupUtils::CreateMultiTargetRowView(bool use_wide_layout) { TriView* tri_view = new TriView(0 /* padding_between_items */); - tri_view->SetInsets(gfx::Insets::TLBR(0, kMenuExtraMarginFromLeftEdge, 0, 0)); + tri_view->SetInsets( + gfx::Insets::TLBR(0, + use_wide_layout ? kQsExtraMarginFromLeftEdge + : kMenuExtraMarginFromLeftEdge, + 0, use_wide_layout ? kQsExtraMarginsFromRightEdge : 0)); - ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::START); - ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::CENTER); - ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::END); + ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::START, + use_wide_layout); + ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::CENTER, + use_wide_layout); + ConfigureDefaultSizeAndFlex(tri_view, TriView::Container::END, + use_wide_layout); tri_view->SetContainerLayout(TriView::Container::START, std::make_unique<views::FillLayout>()); @@ -203,10 +217,14 @@ return label; } -views::ImageView* TrayPopupUtils::CreateMainImageView() { +views::ImageView* TrayPopupUtils::CreateMainImageView(bool use_wide_layout) { auto* image = new views::ImageView; - image->SetPreferredSize( - gfx::Size(kTrayPopupItemMinStartWidth, kTrayPopupItemMinHeight)); + if (use_wide_layout) { + image->SetPreferredSize(gfx::Size(kMenuIconSize, kMenuIconSize)); + } else { + image->SetPreferredSize( + gfx::Size(kTrayPopupItemMinStartWidth, kTrayPopupItemMinHeight)); + } return image; } @@ -225,11 +243,6 @@ view->layer()->SetFillsBoundsOpaquely(false); } -void TrayPopupUtils::ConfigureContainer(TriView::Container container, - views::View* container_view) { - container_view->SetLayoutManager(CreateDefaultLayoutManager(container)); -} - views::LabelButton* TrayPopupUtils::CreateTrayPopupButton( views::Button::PressedCallback callback, const std::u16string& text) {
diff --git a/ash/system/tray/tray_popup_utils.h b/ash/system/tray/tray_popup_utils.h index 2f4fa95..4554ec83 100644 --- a/ash/system/tray/tray_popup_utils.h +++ b/ash/system/tray/tray_popup_utils.h
@@ -63,7 +63,9 @@ // the CENTER container if space is required and available. // // The CENTER container has a flexible width. - static TriView* CreateDefaultRowView(); + // + // `use_wide_layout` uses a wider layout, typically for QsRevamp. + static TriView* CreateDefaultRowView(bool use_wide_layout); // Creates a container view to be used by system menu sub-section header rows. // The caller takes over ownership of the created view. @@ -99,7 +101,9 @@ // // Clients can use ConfigureContainer() to configure their own container views // before adding them to the returned TriView. - static TriView* CreateMultiTargetRowView(); + // + // `use_wide_layout` uses a wider layout, typically for QsRevamp. + static TriView* CreateMultiTargetRowView(bool use_wide_layout); // Returns a label that has been configured for system menu layout. This // should be used by all rows that require a label, i.e. both default and @@ -117,7 +121,9 @@ // default and detailed rows should use this. // // TODO(bruthig): Update all system menu rows to use this. - static views::ImageView* CreateMainImageView(); + // + // `use_wide_layout` uses a wider layout, typically for QsRevamp. + static views::ImageView* CreateMainImageView(bool use_wide_layout); // Creates a default focus painter used for most things in tray popups. static std::unique_ptr<views::Painter> CreateFocusPainter(); @@ -125,12 +131,6 @@ // Sets up |view| to be a sticky header in a tray detail scroll view. static void ConfigureAsStickyHeader(views::View* view); - // Configures |container_view| just like CreateDefaultRowView() would - // configure |container| on its returned TriView. To be used when mutliple - // targetable areas are required within a single row. - static void ConfigureContainer(TriView::Container container, - views::View* container_view); - // Creates a button for use in the system menu. For MD, this is a prominent // text // button. For non-MD, this does the same thing as the above. Caller assumes
diff --git a/ash/system/tray/tray_toggle_button.cc b/ash/system/tray/tray_toggle_button.cc index 68bff8cc3..e550e6c 100644 --- a/ash/system/tray/tray_toggle_button.cc +++ b/ash/system/tray/tray_toggle_button.cc
@@ -19,14 +19,17 @@ namespace ash { TrayToggleButton::TrayToggleButton(PressedCallback callback, - absl::optional<int> accessible_name_id) + absl::optional<int> accessible_name_id, + bool use_empty_border) : ToggleButton(std::move(callback)) { - const gfx::Size toggle_size(GetPreferredSize()); - const int vertical_padding = (kMenuButtonSize - toggle_size.height()) / 2; - const int horizontal_padding = - (kTrayToggleButtonWidth - toggle_size.width()) / 2; - SetBorder(views::CreateEmptyBorder( - gfx::Insets::VH(vertical_padding, horizontal_padding))); + if (!use_empty_border) { + const gfx::Size toggle_size(GetPreferredSize()); + const int vertical_padding = (kMenuButtonSize - toggle_size.height()) / 2; + const int horizontal_padding = + (kTrayToggleButtonWidth - toggle_size.width()) / 2; + SetBorder(views::CreateEmptyBorder( + gfx::Insets::VH(vertical_padding, horizontal_padding))); + } if (accessible_name_id.has_value()) SetAccessibleName(l10n_util::GetStringUTF16(accessible_name_id.value())); views::FocusRing::Get(this)->SetColorId(ui::kColorAshFocusRing);
diff --git a/ash/system/tray/tray_toggle_button.h b/ash/system/tray/tray_toggle_button.h index d82b476..7dc7e267 100644 --- a/ash/system/tray/tray_toggle_button.h +++ b/ash/system/tray/tray_toggle_button.h
@@ -24,9 +24,13 @@ // Creates a button that invokes `callback` when pressed. Sets the accessible // name to the string with resource id `accessible_name_id`, unless that - // parameter is nullopt. + // parameter is nullopt. If `use_empty_border` is false, adds an empty border + // to pad the toggle to 68x48 pixels (for legacy status area). If + // `use_empty_border` is true, the toggle button is just the size of the + // underlying button. TrayToggleButton(PressedCallback callback, - absl::optional<int> accessible_name_id); + absl::optional<int> accessible_name_id, + bool use_empty_border = false); TrayToggleButton(const TrayToggleButton&) = delete; TrayToggleButton& operator=(const TrayToggleButton&) = delete; ~TrayToggleButton() override = default;
diff --git a/ash/system/unified/deferred_update_dialog.cc b/ash/system/unified/deferred_update_dialog.cc index 8f7e464..8443797 100644 --- a/ash/system/unified/deferred_update_dialog.cc +++ b/ash/system/unified/deferred_update_dialog.cc
@@ -43,11 +43,13 @@ .AddOkButton( base::BindOnce(&DeferredUpdateDialog::OnApplyDeferredUpdate, base::Unretained(dialog_)), - l10n_util::GetStringUTF16(ok_text)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(ok_text))) .AddCancelButton( base::BindOnce(&DeferredUpdateDialog::OnContinueWithoutUpdate, base::Unretained(dialog_)), - l10n_util::GetStringUTF16(cancel_text)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(cancel_text))) .AddParagraph(ui::DialogModelLabel( l10n_util::GetStringUTF16(IDS_DEFERRED_UPDATE_DIALOG_TEXT))) .AddCheckbox(kAutoUpdateCheckboxId,
diff --git a/ash/webui/camera_app_ui/resources/js/device/mode/video.ts b/ash/webui/camera_app_ui/resources/js/device/mode/video.ts index eeb456f..7c7fe3b1 100644 --- a/ash/webui/camera_app_ui/resources/js/device/mode/video.ts +++ b/ash/webui/camera_app_ui/resources/js/device/mode/video.ts
@@ -342,6 +342,8 @@ if (!state.get(state.State.RECORDING_PAUSED)) { this.autoStopped = true; this.stop(); + } else { + this.toggleLowStorageWarning(true); } } };
diff --git a/ash/webui/diagnostics_ui/backend/input/input_data_provider.cc b/ash/webui/diagnostics_ui/backend/input/input_data_provider.cc index 2f0bfc2..60c91e38 100644 --- a/ash/webui/diagnostics_ui/backend/input/input_data_provider.cc +++ b/ash/webui/diagnostics_ui/backend/input/input_data_provider.cc
@@ -56,6 +56,10 @@ } // namespace +// Escape should be able to close the dialog as long as shortcuts are not +// blocked. This boolean is updated within |BlockShortcuts|. +bool InputDataProvider::should_close_dialog_on_escape_ = true; + InputDataProvider::InputDataProvider(aura::Window* window, KeyboardInputLog* keyboard_input_log_ptr) : keyboard_input_log_ptr_(keyboard_input_log_ptr), @@ -298,6 +302,10 @@ DCHECK(event_rewriter_delegate_); event_rewriter_delegate_->SuppressModifierKeyRewrites(should_block); + + // While we are blocking shortcuts, esc should not close the diagnostcs + // dialog. + should_close_dialog_on_escape_ = !should_block; } void InputDataProvider::ForwardKeyboardInput(uint32_t id) {
diff --git a/ash/webui/diagnostics_ui/backend/input/input_data_provider.h b/ash/webui/diagnostics_ui/backend/input/input_data_provider.h index bd7ddde..2d115fd 100644 --- a/ash/webui/diagnostics_ui/backend/input/input_data_provider.h +++ b/ash/webui/diagnostics_ui/backend/input/input_data_provider.h
@@ -63,6 +63,10 @@ InputDataProvider& operator=(const InputDataProvider&) = delete; ~InputDataProvider() override; + static bool ShouldCloseDialogOnEscape() { + return should_close_dialog_on_escape_; + } + void BindInterface( mojo::PendingReceiver<mojom::InputDataProvider> pending_receiver); @@ -161,6 +165,10 @@ base::raw_ptr<KeyboardInputLog> keyboard_input_log_ptr_ = nullptr; // Not Owned. + // Denotes whether DiagnosticsDialog should be closed when escape is pressed. + // Currently, this is only false when the keyboard tester is actively in use. + static bool should_close_dialog_on_escape_; + // Whether a tablet mode switch is present (which we use as a hint for the // top-right key glyph). bool has_tablet_mode_switch_ = false;
diff --git a/ash/webui/diagnostics_ui/backend/input/input_data_provider_unittest.cc b/ash/webui/diagnostics_ui/backend/input/input_data_provider_unittest.cc index 93903b6..db90d35 100644 --- a/ash/webui/diagnostics_ui/backend/input/input_data_provider_unittest.cc +++ b/ash/webui/diagnostics_ui/backend/input/input_data_provider_unittest.cc
@@ -542,7 +542,7 @@ public: // ui::EventRewriterChromeOS::Delegate: bool RewriteModifierKeys() override { - return suppress_modifier_key_rewrites_; + return !suppress_modifier_key_rewrites_; } void SuppressModifierKeyRewrites(bool should_supress) override { suppress_modifier_key_rewrites_ = should_supress; @@ -1706,7 +1706,8 @@ provider_->OnDeviceEvent(event0); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); // If widget is in focus, ObserveKeyEvents should block shortcuts, however // since the widget is not in focus, it does not block @@ -1714,7 +1715,8 @@ kDeviceId, fake_observer->receiver.BindNewPipeAndPassRemote()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); } TEST_F(InputDataProviderTest, ShortcutBlockingObeysFocusSwitching) { @@ -1732,24 +1734,28 @@ provider_->OnDeviceEvent(event0); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); // If widget is in focus, ObserveKeyEvents should block shortcuts provider_->ObserveKeyEvents( kDeviceId, fake_observer->receiver.BindNewPipeAndPassRemote()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(OpenAndCloseLauncher()); - EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(InputDataProvider::ShouldCloseDialogOnEscape()); // Hide widget and check that we can use shortcuts provider_->attached_widget_->Hide(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); // Show widget and check that shortcuts are blocked provider_->attached_widget_->Show(); EXPECT_FALSE(OpenAndCloseLauncher()); - EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(InputDataProvider::ShouldCloseDialogOnEscape()); } TEST_F(InputDataProviderTest, ShortcutBlockingObeysLastObserverDisconnect) { @@ -1771,33 +1777,38 @@ provider_->OnDeviceEvent(event0); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); // If widget is in focus, ObserveKeyEvents should block shortcuts provider_->ObserveKeyEvents( kDeviceId, fake_observer1->receiver.BindNewPipeAndPassRemote()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(OpenAndCloseLauncher()); - EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(InputDataProvider::ShouldCloseDialogOnEscape()); // When second observer is added, shortcuts should still be blocked provider_->ObserveKeyEvents( kDeviceId, fake_observer2->receiver.BindNewPipeAndPassRemote()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(OpenAndCloseLauncher()); - EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(InputDataProvider::ShouldCloseDialogOnEscape()); // When first observer is destroyed, shortcuts should still be blocked fake_observer1.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(OpenAndCloseLauncher()); - EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(InputDataProvider::ShouldCloseDialogOnEscape()); // After second observer is destroyed, shortcuts should be unblocked fake_observer2.reset(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(OpenAndCloseLauncher()); - EXPECT_TRUE(ModifierRewritesAreSuppressed()); + EXPECT_FALSE(ModifierRewritesAreSuppressed()); + EXPECT_TRUE(InputDataProvider::ShouldCloseDialogOnEscape()); } // Test overlapping lifetimes of separate observers of one device.
diff --git a/ash/webui/diagnostics_ui/diagnostics_ui.h b/ash/webui/diagnostics_ui/diagnostics_ui.h index f5a7f48..06e4bd6 100644 --- a/ash/webui/diagnostics_ui/diagnostics_ui.h +++ b/ash/webui/diagnostics_ui/diagnostics_ui.h
@@ -6,6 +6,7 @@ #define ASH_WEBUI_DIAGNOSTICS_UI_DIAGNOSTICS_UI_H_ #include "ash/webui/common/backend/plural_string_handler.h" +#include "ash/webui/diagnostics_ui/backend/input/input_data_provider.h" #include "ash/webui/diagnostics_ui/backend/session_log_handler.h" #include "ash/webui/diagnostics_ui/diagnostics_metrics.h" #include "ash/webui/diagnostics_ui/diagnostics_metrics_message_handler.h" @@ -44,6 +45,10 @@ DiagnosticsDialogUI(const DiagnosticsDialogUI&) = delete; DiagnosticsDialogUI& operator=(const DiagnosticsDialogUI&) = delete; + static bool ShouldCloseDialogOnEscape() { + return diagnostics::InputDataProvider::ShouldCloseDialogOnEscape(); + } + void BindInterface( mojo::PendingReceiver<diagnostics::mojom::NetworkHealthProvider> receiver);
diff --git a/ash/wm/tablet_mode/tablet_mode_multitask_menu.cc b/ash/wm/tablet_mode/tablet_mode_multitask_menu.cc index ca1e825..e359766 100644 --- a/ash/wm/tablet_mode/tablet_mode_multitask_menu.cc +++ b/ash/wm/tablet_mode/tablet_mode_multitask_menu.cc
@@ -4,6 +4,8 @@ #include "ash/wm/tablet_mode/tablet_mode_multitask_menu.h" +#include "ash/public/cpp/shell_window_ids.h" +#include "ash/public/cpp/window_properties.h" #include "ash/style/ash_color_id.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_multitask_menu_event_handler.h" @@ -35,6 +37,8 @@ constexpr base::TimeDelta kPositionAnimationDurationMs = base::Milliseconds(250); +constexpr base::TimeDelta kOpacityAnimationDurationMs = base::Milliseconds(150); + } // namespace // The contents view of the multitask menu. @@ -111,15 +115,12 @@ views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; params.activatable = views::Widget::InitParams::Activatable::kYes; - params.parent = window->parent(); + params.parent = + window->GetRootWindow()->GetChildById(kShellWindowId_FloatContainer); params.name = "TabletModeMultitaskMenuWidget"; widget_->Init(std::move(params)); widget_->SetVisibilityChangedAnimationsEnabled(false); - auto* multitask_menu_window = widget_->GetNativeWindow(); - // TODO(sophiewen): Consider adding transient child instead. - multitask_menu_window->parent()->StackChildAbove(multitask_menu_window, - window_); // Clip the widget's root view so that the menu appears to be sliding out from // the top, even if the window above it is stacked below it, which is the case @@ -180,6 +181,21 @@ .SetOpacity(view_layer, show ? 1.f : 0.f, gfx::Tween::LINEAR); } +void TabletModeMultitaskMenu::AnimateFadeOut() { + ui::Layer* view_layer = menu_view_->layer(); + auto* animator = view_layer->GetAnimator(); + if (animator->is_animating()) + return; + views::AnimationBuilder() + .OnEnded(base::BindOnce(&TabletModeMultitaskMenu::Reset, + weak_factory_.GetWeakPtr())) + .SetPreemptionStrategy( + ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET) + .Once() + .SetDuration(kOpacityAnimationDurationMs) + .SetOpacity(view_layer, 0.0f, gfx::Tween::LINEAR); +} + void TabletModeMultitaskMenu::BeginDrag(float initial_y) { // Try to match the bottom of the menu with the drag location. // TODO(sophiewen): The drag location may not always be at the bottom of the @@ -219,7 +235,7 @@ window_ = nullptr; // Destroys `this`. - event_handler_->ResetMultitaskMenu(); + Reset(); } void TabletModeMultitaskMenu::OnWidgetActivationChanged(views::Widget* widget, @@ -227,7 +243,7 @@ // `widget` gets deactivated when the window state changes. DCHECK(widget_observation_.IsObservingSource(widget)); if (!active) - event_handler_->ResetMultitaskMenu(); + Reset(); } void TabletModeMultitaskMenu::OnDisplayMetricsChanged(
diff --git a/ash/wm/tablet_mode/tablet_mode_multitask_menu.h b/ash/wm/tablet_mode/tablet_mode_multitask_menu.h index e37b83d..38f99eb5 100644 --- a/ash/wm/tablet_mode/tablet_mode_multitask_menu.h +++ b/ash/wm/tablet_mode/tablet_mode_multitask_menu.h
@@ -40,9 +40,14 @@ views::Widget* widget() { return widget_.get(); } - // Slides the menu down if `show` is true, otherwise slides up. + // Performs a slide down animation on the menu if `show` is true, otherwise + // slide up animation. void Animate(bool show); + // Performs a fade out animation and closes the menu. Called when tap outside + // the menu dismisses it. + void AnimateFadeOut(); + // Actions called by the event handler, where `initial_y` and `current_y` are // in `window_`'s coordinates. void BeginDrag(float initial_y);
diff --git a/ash/wm/tablet_mode/tablet_mode_multitask_menu_event_handler.cc b/ash/wm/tablet_mode/tablet_mode_multitask_menu_event_handler.cc index 107c20c..104e9de 100644 --- a/ash/wm/tablet_mode/tablet_mode_multitask_menu_event_handler.cc +++ b/ash/wm/tablet_mode/tablet_mode_multitask_menu_event_handler.cc
@@ -147,6 +147,16 @@ default: break; } + + // Tap outside will dismiss the menu with a fade out animation. + // TODO(b/260113268): Use increased tap target and `HitTestRect` instead. + if (!event->handled() && multitask_menu_ && + !gfx::RectF(multitask_menu_->widget()->GetWindowBoundsInScreen()) + .Contains(screen_location)) { + multitask_menu_->AnimateFadeOut(); + event->SetHandled(); + return; + } } } // namespace ash
diff --git a/base/base64.cc b/base/base64.cc index 6aea482..aa80a4aa 100644 --- a/base/base64.cc +++ b/base/base64.cc
@@ -19,19 +19,17 @@ } void Base64EncodeAppend(span<const uint8_t> input, std::string* output) { - // Ensure `modp_b64_encode_len` will not overflow. Note this length and - // `modp_b64_encode`'s output includes a trailing NUL byte. + // Ensure `modp_b64_encode_data_len` will not overflow. CHECK_LE(input.size(), MODP_B64_MAX_INPUT_LEN); - size_t encode_len = modp_b64_encode_len(input.size()); + size_t encode_data_len = modp_b64_encode_data_len(input.size()); size_t prefix_len = output->size(); - output->resize(base::CheckAdd(encode_len, prefix_len).ValueOrDie()); + output->resize(base::CheckAdd(encode_data_len, prefix_len).ValueOrDie()); - const size_t output_size = modp_b64_encode( + const size_t output_size = modp_b64_encode_data( output->data() + prefix_len, reinterpret_cast<const char*>(input.data()), input.size()); - // `output_size` does not include the trailing NUL byte, so this removes it. - output->resize(prefix_len + output_size); + CHECK_EQ(output->size(), prefix_len + output_size); } void Base64Encode(StringPiece input, std::string* output) {
diff --git a/base/base64_unittest.cc b/base/base64_unittest.cc index b593633..2e73bf1 100644 --- a/base/base64_unittest.cc +++ b/base/base64_unittest.cc
@@ -79,10 +79,10 @@ std::string output = "PREFIX"; EXPECT_CHECK_DEATH(Base64EncodeAppend(large_span, &output)); - // `modp_b64_encode_len` is a macro, so check `MODP_B64_MAX_INPUT_LEN` is + // `modp_b64_encode_data_len` is a macro, so check `MODP_B64_MAX_INPUT_LEN` is // correct be verifying the computation doesn't overflow. base::CheckedNumeric<size_t> max_len = MODP_B64_MAX_INPUT_LEN; - EXPECT_TRUE(modp_b64_encode_len(max_len).IsValid()); + EXPECT_TRUE(modp_b64_encode_data_len(max_len).IsValid()); } } // namespace base
diff --git a/base/base_paths_win.cc b/base/base_paths_win.cc index 22cea08..605ad115 100644 --- a/base/base_paths_win.cc +++ b/base/base_paths_win.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <windows.h> + #include <KnownFolders.h> #include <shlobj.h>
diff --git a/base/command_line.cc b/base/command_line.cc index 2b0bf13..d65d212 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -24,6 +24,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <shellapi.h> #include "base/strings/string_util_win.h"
diff --git a/base/file_version_info_win.cc b/base/file_version_info_win.cc index aa74187d..6813ec4f 100644 --- a/base/file_version_info_win.cc +++ b/base/file_version_info_win.cc
@@ -5,6 +5,7 @@ #include "base/file_version_info_win.h" #include <windows.h> + #include <stddef.h> #include <utility>
diff --git a/base/files/file_path_watcher_unittest.cc b/base/files/file_path_watcher_unittest.cc index 00e236be..832be8f 100644 --- a/base/files/file_path_watcher_unittest.cc +++ b/base/files/file_path_watcher_unittest.cc
@@ -31,6 +31,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <aclapi.h> #elif BUILDFLAG(IS_POSIX) #include <sys/stat.h>
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc index 469a882..952bdc6d 100644 --- a/base/logging_unittest.cc +++ b/base/logging_unittest.cc
@@ -38,6 +38,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <excpt.h> #endif // BUILDFLAG(IS_WIN)
diff --git a/base/path_service.cc b/base/path_service.cc index 7f0a907..e136bd1 100644 --- a/base/path_service.cc +++ b/base/path_service.cc
@@ -16,6 +16,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <shellapi.h> #include <shlobj.h> #endif
diff --git a/base/power_monitor/speed_limit_observer_win.cc b/base/power_monitor/speed_limit_observer_win.cc index 697dda4..2454140 100644 --- a/base/power_monitor/speed_limit_observer_win.cc +++ b/base/power_monitor/speed_limit_observer_win.cc
@@ -4,10 +4,10 @@ #include "base/power_monitor/speed_limit_observer_win.h" -// windows.h must be included before powerbase.h -#include <windows.h> // NOLINT(build/include_order) -#include <powerbase.h> // NOLINT(build/include_order) -#include <winternl.h> // NOLINT(build/include_order) +#include <windows.h> + +#include <powerbase.h> +#include <winternl.h> #include <algorithm> #include <memory>
diff --git a/base/process/kill_win.cc b/base/process/kill_win.cc index 63055a8..b572cfdf 100644 --- a/base/process/kill_win.cc +++ b/base/process/kill_win.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include <windows.h> + #include <io.h> #include <stdint.h>
diff --git a/base/process/process_handle_win.cc b/base/process/process_handle_win.cc index b9448e28..cf17eb4 100644 --- a/base/process/process_handle_win.cc +++ b/base/process/process_handle_win.cc
@@ -5,6 +5,7 @@ #include "base/process/process_handle.h" #include <windows.h> + #include <tlhelp32.h> #include <ostream>
diff --git a/base/process/process_iterator.h b/base/process/process_iterator.h index 5ffab38..422a69bf 100644 --- a/base/process/process_iterator.h +++ b/base/process/process_iterator.h
@@ -22,6 +22,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <tlhelp32.h> #elif BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_OPENBSD) #include <sys/sysctl.h>
diff --git a/base/rand_util_win.cc b/base/rand_util_win.cc index 099fe29..2d9a1633 100644 --- a/base/rand_util_win.cc +++ b/base/rand_util_win.cc
@@ -5,6 +5,7 @@ #include "base/rand_util.h" #include <windows.h> + #include <stddef.h> #include <stdint.h>
diff --git a/base/strings/sys_string_conversions_win.cc b/base/strings/sys_string_conversions_win.cc index 58dbe080e6..e84c79d 100644 --- a/base/strings/sys_string_conversions_win.cc +++ b/base/strings/sys_string_conversions_win.cc
@@ -5,6 +5,7 @@ #include "base/strings/sys_string_conversions.h" #include <windows.h> + #include <stdint.h> #include "base/strings/string_piece.h"
diff --git a/base/synchronization/waitable_event_win.cc b/base/synchronization/waitable_event_win.cc index 3165aee5..3141cf8 100644 --- a/base/synchronization/waitable_event_win.cc +++ b/base/synchronization/waitable_event_win.cc
@@ -5,6 +5,7 @@ #include "base/synchronization/waitable_event.h" #include <windows.h> + #include <stddef.h> #include <algorithm>
diff --git a/base/test/test_shortcut_win.cc b/base/test/test_shortcut_win.cc index 3333e59..49015ec 100644 --- a/base/test/test_shortcut_win.cc +++ b/base/test/test_shortcut_win.cc
@@ -5,6 +5,7 @@ #include "base/test/test_shortcut_win.h" #include <windows.h> + #include <objbase.h> #include <shlobj.h> #include <propkey.h>
diff --git a/base/threading/sequence_bound_internal.h b/base/threading/sequence_bound_internal.h index ed463b8..0177574f 100644 --- a/base/threading/sequence_bound_internal.h +++ b/base/threading/sequence_bound_internal.h
@@ -26,8 +26,6 @@ template <typename Functor, typename... Args> static inline auto BindOnce(Functor&& functor, Args&&... args) { - return base::BindOnce(std::forward<Functor>(functor), - std::forward<Args>(args)...); return ::base::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...); }
diff --git a/base/threading/thread_local_storage_unittest.cc b/base/threading/thread_local_storage_unittest.cc index a31071e6..812fc8d 100644 --- a/base/threading/thread_local_storage_unittest.cc +++ b/base/threading/thread_local_storage_unittest.cc
@@ -12,6 +12,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> + #include <process.h> // Ignore warnings about ptr->int conversions that we use when // storing ints into ThreadLocalStorage.
diff --git a/base/time/time_win.cc b/base/time/time_win.cc index fc5e79c..452e688 100644 --- a/base/time/time_win.cc +++ b/base/time/time_win.cc
@@ -35,6 +35,7 @@ #include <windows.foundation.h> #include <windows.h> + #include <mmsystem.h> #include <stdint.h>
diff --git a/build/android/incremental_install/java/org/chromium/incrementalinstall/ClassLoaderPatcher.java b/build/android/incremental_install/java/org/chromium/incrementalinstall/ClassLoaderPatcher.java index 4c85161..53e926e6 100644 --- a/build/android/incremental_install/java/org/chromium/incrementalinstall/ClassLoaderPatcher.java +++ b/build/android/incremental_install/java/org/chromium/incrementalinstall/ClassLoaderPatcher.java
@@ -153,34 +153,30 @@ @SuppressLint("SetWorldReadable") private void safeCopyAllFiles(File srcDir, File dstDir) throws IOException { + if (!mIsPrimaryProcess) { + // TODO: Work around this issue by using APK splits to install each dex / lib. + throw new RuntimeException("Incremental install does not work on Android M+ " + + "with isolated processes. Build system should have removed this. " + + "Please file a bug."); + } + // The library copying is not necessary on older devices, but we do it anyways to // simplify things (it's fast compared to dexing). // https://code.google.com/p/android/issues/detail?id=79480 + ensureAppFilesSubDirExists(); File lockFile = new File(mAppFilesSubDir, dstDir.getName() + ".lock"); - if (mIsPrimaryProcess) { - ensureAppFilesSubDirExists(); - LockFile lock = LockFile.acquireRuntimeLock(lockFile); - if (lock == null) { - LockFile.waitForRuntimeLock(lockFile, 10 * 1000); - } else { - try { - dstDir.mkdir(); - dstDir.setReadable(true, false); - dstDir.setExecutable(true, false); - copyChangedFiles(srcDir, dstDir); - } finally { - lock.release(); - } - } - } else { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - // TODO: Work around this issue by using APK splits to install each dex / lib. - throw new RuntimeException("Incremental install does not work on Android M+ " - + "with isolated processes. Build system should have removed this. " - + "Please file a bug."); - } - // Other processes: Waits for primary process to finish copying. + LockFile lock = LockFile.acquireRuntimeLock(lockFile); + if (lock == null) { LockFile.waitForRuntimeLock(lockFile, 10 * 1000); + } else { + try { + dstDir.mkdir(); + dstDir.setReadable(true, false); + dstDir.setExecutable(true, false); + copyChangedFiles(srcDir, dstDir); + } finally { + lock.release(); + } } } @@ -291,14 +287,9 @@ File emptyDir = new File(""); for (int i = 0; i < files.length; ++i) { File file = files[i]; - Object dexFile; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - // loadDexFile requires that ret contain all previously added elements. - dexFile = Reflect.invokeMethod(clazz, "loadDexFile", file, optimizedDirectory, - mClassLoader, ret); - } else { - dexFile = Reflect.invokeMethod(clazz, "loadDexFile", file, optimizedDirectory); - } + // loadDexFile requires that ret contain all previously added elements. + Object dexFile = Reflect.invokeMethod( + clazz, "loadDexFile", file, optimizedDirectory, mClassLoader, ret); Object dexElement; if (Build.VERSION.SDK_INT >= 26) { dexElement = Reflect.newInstance(entryClazz, dexFile, file);
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index 780d7315..8c39843 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -10.20221122.0.1 +10.20221122.1.1
diff --git a/chrome/VERSION b/chrome/VERSION index 551d0ce..635384c 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=110 MINOR=0 -BUILD=5435 +BUILD=5436 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index adfa845..100891d 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -1535,7 +1535,6 @@ "//base/test:test_support_java", "//cc:cc_java", "//chrome/android:chrome_java", - "//chrome/android/features/keyboard_accessory/public:public_java", "//chrome/android/features/start_surface:java_resources", "//chrome/android/features/start_surface:public_java", "//chrome/android/features/tab_ui:java", @@ -4086,7 +4085,6 @@ "java/src/org/chromium/chrome/browser/infobar/AutofillVirtualCardEnrollmentInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/FramebustBlockInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBarDelegate.java", "java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java", "java/src/org/chromium/chrome/browser/infobar/KnownInterceptionDisclosureInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/NearOomInfoBar.java", @@ -4094,10 +4092,8 @@ "java/src/org/chromium/chrome/browser/infobar/PermissionInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/ReaderModeInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/SafetyTipInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/SurveyInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/TranslateCompactInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/UpdatePasswordInfoBar.java", "java/src/org/chromium/chrome/browser/init/NativeStartupBridge.java", "java/src/org/chromium/chrome/browser/javascript/WebContextFetcher.java", "java/src/org/chromium/chrome/browser/lens/LensDebugBridge.java",
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 6fdaaa42..7181e13 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -684,8 +684,6 @@ "java/src/org/chromium/chrome/browser/infobar/CardDetail.java", "java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/FramebustBlockInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBarDelegate.java", "java/src/org/chromium/chrome/browser/infobar/IPHBubbleDelegateImpl.java", "java/src/org/chromium/chrome/browser/infobar/IPHInfoBarSupport.java", "java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java", @@ -697,13 +695,11 @@ "java/src/org/chromium/chrome/browser/infobar/PermissionInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/ReaderModeInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/SafetyTipInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/SubPanelListener.java", "java/src/org/chromium/chrome/browser/infobar/SurveyInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/SurveyInfoBarDelegate.java", "java/src/org/chromium/chrome/browser/infobar/TextViewEllipsizerSafe.java", "java/src/org/chromium/chrome/browser/infobar/TranslateCompactInfoBar.java", - "java/src/org/chromium/chrome/browser/infobar/UpdatePasswordInfoBar.java", "java/src/org/chromium/chrome/browser/init/ActivityLifecycleDispatcherImpl.java", "java/src/org/chromium/chrome/browser/init/AsyncInitTaskRunner.java", "java/src/org/chromium/chrome/browser/init/AsyncInitializationActivity.java",
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index 927bb4b..8d99f82 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -233,6 +233,7 @@ "junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceMetricsTest.java", "junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceNotificationTest.java", "junit/src/org/chromium/chrome/browser/search_engines/settings/SearchEngineAdapterTest.java", + "junit/src/org/chromium/chrome/browser/share/LensUtilsTest.java", "junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java", "junit/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandlerTest.java", "junit/src/org/chromium/chrome/browser/signin/SigninBridgeTest.java",
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index e1ada303..9c28e46c 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -46,7 +46,6 @@ "javatests/src/org/chromium/chrome/browser/TabsTest.java", "javatests/src/org/chromium/chrome/browser/UrlSchemeTest.java", "javatests/src/org/chromium/chrome/browser/VideoFullscreenOrientationLockChromeTest.java", - "javatests/src/org/chromium/chrome/browser/ViewTransitionPixelTest.java", "javatests/src/org/chromium/chrome/browser/VirtualKeyboardResizeTest.java", "javatests/src/org/chromium/chrome/browser/WarmupManagerTest.java", "javatests/src/org/chromium/chrome/browser/accessibility/FontSizePrefsTest.java", @@ -430,7 +429,6 @@ "javatests/src/org/chromium/chrome/browser/settings/MainSettingsFragmentTest.java", "javatests/src/org/chromium/chrome/browser/settings/SettingsActivityTest.java", "javatests/src/org/chromium/chrome/browser/shape_detection/ShapeDetectionTest.java", - "javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java", "javatests/src/org/chromium/chrome/browser/share/ShareButtonControllerTest.java", "javatests/src/org/chromium/chrome/browser/share/ShareDelegateImplIntegrationTest.java", "javatests/src/org/chromium/chrome/browser/share/ShareDelegateImplTest.java",
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingCoordinator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingCoordinator.java index bb361d64..69d5cdf 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingCoordinator.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingCoordinator.java
@@ -184,14 +184,4 @@ ManualFillingMediator getMediatorForTesting() { return mMediator; } - - @Override - public int getKeyboardExtensionHeight() { - return mMediator != null ? mMediator.getKeyboardExtensionHeight() : 0; - } - - @Override - public void forceShowForTesting() { - mMediator.showWhenKeyboardIsVisible(); - } }
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingMediator.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingMediator.java index e209d423..60987a93 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingMediator.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingMediator.java
@@ -565,16 +565,6 @@ } /** - * Returns the amount that the keyboard will be extended by the accessory bar. - */ - public int getKeyboardExtensionHeight() { - if (!canExtendKeyboard()) return 0; - - return mActivity.getResources().getDimensionPixelSize( - R.dimen.keyboard_accessory_suggestion_height); - } - - /** * Opens the keyboard which implicitly dismisses the sheet. Without open sheet, this is a NoOp. */ void swapSheetWithKeyboard() {
diff --git a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java index f3fc81b..8179f00f5 100644 --- a/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java +++ b/chrome/android/features/keyboard_accessory/public/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponent.java
@@ -227,17 +227,4 @@ * @param confirmedCallback A {@link Runnable} to trigger upon confirmation. */ void confirmOperation(String title, String message, Runnable confirmedCallback); - - /** - * Returns the amount that the keyboard will be extended by the filling component when shown. - * i.e. The height of any accessories to be shown on top of the keyboard. - */ - int getKeyboardExtensionHeight(); - - /** - * Will force the accessory to show when the keyboard is shown. - * TODO(crbug.com/1385400): Ideally this would live in a test utility like - * ManualFillingTestHelper. - */ - void forceShowForTesting(); }
diff --git a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceMediator.java b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceMediator.java index 744463b..5a4779f 100644 --- a/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceMediator.java +++ b/chrome/android/features/start_surface/java/src/org/chromium/chrome/features/start_surface/StartSurfaceMediator.java
@@ -830,9 +830,18 @@ // the TabSelectionEditor dialog. Therefore, we need to check both controllers as well. if (mSecondaryTasksSurfaceController != null && mSecondaryTasksSurfaceController.isDialogVisible()) { - return mSecondaryTasksSurfaceController.onBackPressed(isOnHomepage); + boolean ret = mSecondaryTasksSurfaceController.onBackPressed(isOnHomepage); + assert !BackPressManager.isEnabled() + || ret : String.format("Wrong back press state: %s, start surface: %s", + mSecondaryTasksSurfaceController.getClass().getName(), + mStartSurfaceState); + return ret; } else if (mController.isDialogVisible()) { - return mController.onBackPressed(isOnHomepage); + boolean ret = mController.onBackPressed(isOnHomepage); + assert !BackPressManager.isEnabled() + || ret : String.format("Wrong back press state: %s, start surface: %s", + mController.getClass().getName(), mStartSurfaceState); + return ret; } if (mStartSurfaceState == StartSurfaceState.SHOWN_TABSWITCHER) { @@ -844,7 +853,12 @@ ReturnToChromeUtil.recordBackNavigationToStart("FromTabSwitcher"); return true; } else { - return mSecondaryTasksSurfaceController.onBackPressed(isOnHomepage); + boolean ret = mSecondaryTasksSurfaceController.onBackPressed(isOnHomepage); + assert !BackPressManager.isEnabled() + || ret : String.format("Wrong back press state: %s, start surface: %s", + mSecondaryTasksSurfaceController.getClass().getName(), + mStartSurfaceState); + return ret; } } @@ -855,7 +869,11 @@ } } - return mController.onBackPressed(isOnHomepage); + boolean ret = mController.onBackPressed(isOnHomepage); + assert !BackPressManager.isEnabled() + || ret : String.format("Wrong back press state: %s, start surface: %s", + mController.getClass().getName(), mStartSurfaceState); + return ret; } void maybeDestroyFeedPlaceholder() { @@ -867,8 +885,7 @@ @Override public void handleBackPress() { - boolean ret = onBackPressedInternal(); - assert ret; + onBackPressedInternal(); notifyBackPressStateChanged(); } @@ -1082,7 +1099,7 @@ if (isVisible) { if (mSecondaryTasksSurfacePropertyModel == null) { - mSecondaryTasksSurfaceController = mSecondaryTasksSurfaceInitializer.initialize(); + setSecondaryTasksSurfaceController(mSecondaryTasksSurfaceInitializer.initialize()); } if (mSecondaryTasksSurfacePropertyModel != null) { mSecondaryTasksSurfacePropertyModel.set(IS_FAKE_SEARCH_BOX_VISIBLE, false);
diff --git a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java index 65fe022..f2c690a 100644 --- a/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java +++ b/chrome/android/features/start_surface/junit/src/org/chromium/chrome/features/start_surface/StartSurfaceMediatorUnitTest.java
@@ -1527,6 +1527,7 @@ "Should not intercept back press by default", mediator.shouldInterceptBackPress()); mControllerDialogVisibleSupplier.set(true); Assert.assertTrue(mediator.shouldInterceptBackPress()); + doReturn(true).when(mMainTabGridController).onBackPressed(false); mediator.onBackPressed(); verify(mMainTabGridController).onBackPressed(false); @@ -1536,6 +1537,7 @@ mControllerDialogVisibleSupplier.set(true); mSecondaryControllerDialogVisibleSupplier.set(true); Assert.assertTrue(mediator.shouldInterceptBackPress()); + doReturn(true).when(mSecondaryTasksSurfaceController).onBackPressed(false); mediator.onBackPressed(); verify(mMainTabGridController).onBackPressed(false); verify(mSecondaryTasksSurfaceController,
diff --git a/chrome/android/features/tab_ui/BUILD.gn b/chrome/android/features/tab_ui/BUILD.gn index 838c565..7f71f55 100644 --- a/chrome/android/features/tab_ui/BUILD.gn +++ b/chrome/android/features/tab_ui/BUILD.gn
@@ -263,7 +263,6 @@ "javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiViewBinderTest.java", "javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabListViewHolderTest.java", "javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorLayoutBinderTest.java", - "javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java", ] deps = [
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java index b65d1c0..12dee38 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java
@@ -43,7 +43,6 @@ import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CallbackHelper; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.tab.Tab; @@ -86,7 +85,7 @@ @ParameterAnnotations.UseRunnerDelegate(ChromeJUnit4RunnerDelegate.class) @Features.EnableFeatures({GRID_TAB_SWITCHER_FOR_TABLETS, TAB_STRIP_IMPROVEMENTS, TAB_GROUPS_FOR_TABLETS, TAB_SELECTION_EDITOR_V2}) -@Batch(Batch.UNIT_TESTS) +@Batch(Batch.PER_CLASS) public class TabSelectionEditorMenuTest extends BlankUiTestActivityTestCase { private static final int TAB_COUNT = 3; private static final Integer TAB_ID_0 = 0; @@ -314,7 +313,6 @@ @Test @MediumTest - @DisabledTest(message = "https://crbug.com/1348710") @Feature({"RenderTest"}) public void testSingleActionView_Click() throws Exception { List<FakeTabSelectionEditorAction> actions = new ArrayList<>();
diff --git a/chrome/android/features/tab_ui/tab_management_java_sources.gni b/chrome/android/features/tab_ui/tab_management_java_sources.gni index 7bc49010..14a13b3 100644 --- a/chrome/android/features/tab_ui/tab_management_java_sources.gni +++ b/chrome/android/features/tab_ui/tab_management_java_sources.gni
@@ -31,6 +31,7 @@ "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGridIphTest.java", "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiTest.java", "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabListContainerViewBinderTest.java", + "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorMenuTest.java", "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorTest.java", "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSelectionEditorTestingRobot.java", "//chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSuggestionMessageCardTest.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java index d05eba1..0ac5fae4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java
@@ -89,13 +89,4 @@ public @Px int calculateSoftKeyboardHeight(View rootView) { return calculateKeyboardHeight(rootView); } - - @Override - public int calculateTotalKeyboardHeight(View rootView) { - int accessoryHeight = 0; - if (mManualFillingComponentSupplier.hasValue()) { - accessoryHeight = mManualFillingComponentSupplier.get().getKeyboardExtensionHeight(); - } - return calculateKeyboardHeight(rootView) + accessoryHeight; - } -} +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java index 2635c21..8719da6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/LaunchIntentDispatcher.java
@@ -15,7 +15,6 @@ import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; -import android.os.SystemClock; import androidx.annotation.IntDef; import androidx.annotation.Nullable; @@ -438,7 +437,6 @@ if (Intent.ACTION_VIEW.equals(newIntent.getAction()) && !IntentHandler.wasIntentSenderChrome(newIntent)) { - long time = SystemClock.elapsedRealtime(); if (!chromeTabbedTaskExists()) { newIntent.putExtra(IntentHandler.EXTRA_STARTED_TABBED_CHROME_TASK, true); } @@ -448,8 +446,6 @@ // the flag to take effect only once. newIntent.setFlags(newIntent.getFlags() & ~Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); } - RecordHistogram.recordTimesHistogram("Startup.Android.ChromeTabbedTaskExistsTime", - SystemClock.elapsedRealtime() - time); } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { @@ -533,13 +529,6 @@ * Records metrics gleaned from the Intent. */ private void recordIntentMetrics() { - @IntentHandler.ExternalAppId - int source = IntentHandler.determineExternalIntentSource(mIntent); - if (mIntent.getPackage() == null && source != IntentHandler.ExternalAppId.CHROME) { - int flagsOfInterest = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT; - int maskedFlags = mIntent.getFlags() & flagsOfInterest; - RecordHistogram.recordSparseHistogram("Launch.IntentFlags", maskedFlags); - } MediaNotificationUma.recordClickSource(mIntent); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java b/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java index 68b799c8..c7580d9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/flags/ChromeCachedFlags.java
@@ -87,6 +87,7 @@ add(ChromeFeatureList.sCctResizableAlwaysShowNavBarButtons); add(ChromeFeatureList.sCctResizableForFirstParties); add(ChromeFeatureList.sCctResizableForThirdParties); + add(ChromeFeatureList.sCctResizableSideSheet); add(ChromeFeatureList.sCctRetainableStateInMemory); add(ChromeFeatureList.sCctToolbarCustomizations); add(ChromeFeatureList.sCloseTabSuggestions);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/tab_activity_glue/ActivityTabWebContentsDelegateAndroid.java b/chrome/android/java/src/org/chromium/chrome/browser/app/tab_activity_glue/ActivityTabWebContentsDelegateAndroid.java index 498d540..8d6dcd6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/tab_activity_glue/ActivityTabWebContentsDelegateAndroid.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/tab_activity_glue/ActivityTabWebContentsDelegateAndroid.java
@@ -379,14 +379,6 @@ } @Override - public int getVirtualKeyboardHeight() { - if (mActivity == null) return 0; - - View rootView = mActivity.getWindow().getDecorView().getRootView(); - return mTab.getWindowAndroid().getKeyboardDelegate().calculateTotalKeyboardHeight(rootView); - } - - @Override public void enterFullscreenModeForTab(boolean prefersNavigationBar, boolean prefersStatusBar) { if (mFullscreenManager != null) { mFullscreenManager.onEnterFullscreen(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBar.java deleted file mode 100644 index 9874a6606b..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBar.java +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2014 The Chromium Authors -// 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.infobar; - -import android.text.SpannableString; -import android.text.Spanned; - -import org.chromium.chrome.R; -import org.chromium.components.infobars.ConfirmInfoBar; -import org.chromium.components.infobars.InfoBarControlLayout; -import org.chromium.components.infobars.InfoBarLayout; -import org.chromium.ui.text.NoUnderlineClickableSpan; - -/** - * An infobar to notify that the generated password was saved. - */ -public class GeneratedPasswordSavedInfoBar extends ConfirmInfoBar { - private final int mInlineLinkRangeStart; - private final int mInlineLinkRangeEnd; - private final String mDetailsMessage; - - /** - * Creates and shows the infobar to notify that the generated password was saved. - * @param iconDrawableId Drawable ID corresponding to the icon that the infobar will show. - * @param messageText Message to display in the infobar. - * @param detailsMessageText Message containing additional details to be displayed in the - * infobar. - * @param inlineLinkRangeStart The start of the range of the messageText that should be a link. - * @param inlineLinkRangeEnd The end of the range of the messageText that should be a link. - * @param buttonLabel String to display on the button. - */ - public GeneratedPasswordSavedInfoBar(int iconDrawableId, String messageText, - String detailsMessageText, int inlineLinkRangeStart, int inlineLinkRangeEnd, - String buttonLabel) { - super(iconDrawableId, R.color.infobar_icon_drawable_color, null, messageText, null, - buttonLabel, null); - mDetailsMessage = detailsMessageText; - mInlineLinkRangeStart = inlineLinkRangeStart; - mInlineLinkRangeEnd = inlineLinkRangeEnd; - } - - /** - * Used to specify button layout and custom content. Makes infobar display a single button and - * an inline link in the message. - * @param layout Handles user interface for the infobar. - */ - @Override - public void createContent(InfoBarLayout layout) { - super.createContent(layout); - InfoBarControlLayout detailsMessageLayout = layout.addControlLayout(); - SpannableString detailsMessageWithLink = new SpannableString(mDetailsMessage); - detailsMessageWithLink.setSpan( - new NoUnderlineClickableSpan(layout.getContext(), (view) -> onLinkClicked()), - mInlineLinkRangeStart, mInlineLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE); - detailsMessageLayout.addDescription(detailsMessageWithLink); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBarDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBarDelegate.java deleted file mode 100644 index cf8a0e2..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/GeneratedPasswordSavedInfoBarDelegate.java +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors -// 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.infobar; - -import org.chromium.base.annotations.CalledByNative; -import org.chromium.components.infobars.InfoBar; - -/** - * Provides JNI methods for the infobar to notify that the generated password was saved. - */ -public class GeneratedPasswordSavedInfoBarDelegate { - /** - * Creates and shows the infobar to notify that the generated password was saved. - * @param iconId Enum ID corresponding to the icon that the infobar will show. - * @param messageText Message to display in the infobar. - * @param detailsMessageText Message containing additional details to be displayed in the - * infobar. - * @param inlineLinkRangeStart The start of the range of the messageText that should be a link. - * @param inlineLinkRangeEnd The end of the range of the messageText that should be a link. - * @param buttonLabel String to display on the button. - */ - @CalledByNative - private static InfoBar show(int iconId, String messageText, String detailsMessageText, - int inlineLinkRangeStart, int inlineLinkRangeEnd, String buttonLabel) { - return new GeneratedPasswordSavedInfoBar(iconId, messageText, detailsMessageText, - inlineLinkRangeStart, inlineLinkRangeEnd, buttonLabel); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java deleted file mode 100644 index a7f51d1..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2018 The Chromium Authors -// 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.infobar; - -import android.text.TextUtils; - -import org.chromium.base.annotations.CalledByNative; -import org.chromium.chrome.R; -import org.chromium.components.infobars.ConfirmInfoBar; -import org.chromium.components.infobars.InfoBar; -import org.chromium.components.infobars.InfoBarControlLayout; -import org.chromium.components.infobars.InfoBarLayout; -import org.chromium.components.signin.base.AccountInfo; - -/** - * The Save Password infobar asks the user whether they want to save the password for the site. - */ -public class SavePasswordInfoBar extends ConfirmInfoBar { - private final String mDetailsMessage; - private final AccountInfo mAccountInfo; - - @CalledByNative - private static InfoBar show(int iconId, String message, String detailsMessage, - String primaryButtonText, String secondaryButtonText, AccountInfo accountInfo) { - // If accountInfo is empty, no footer will be shown. - return new SavePasswordInfoBar(iconId, message, detailsMessage, primaryButtonText, - secondaryButtonText, accountInfo); - } - - private SavePasswordInfoBar(int iconDrawbleId, String message, String detailsMessage, - String primaryButtonText, String secondaryButtonText, AccountInfo accountInfo) { - super(iconDrawbleId, R.color.infobar_icon_drawable_color, null, message, null, - primaryButtonText, secondaryButtonText); - mDetailsMessage = detailsMessage; - mAccountInfo = accountInfo; - } - - @Override - public void createContent(InfoBarLayout layout) { - super.createContent(layout); - if (!TextUtils.isEmpty(mDetailsMessage)) { - InfoBarControlLayout detailsMessageLayout = layout.addControlLayout(); - detailsMessageLayout.addDescription(mDetailsMessage); - } - - if (mAccountInfo != null && !TextUtils.isEmpty(mAccountInfo.getEmail()) - && mAccountInfo.getAccountImage() != null) { - layout.addFooterView(PasswordInfoBarUtils.createAccountIndicationFooter( - layout.getContext(), mAccountInfo.getAccountImage(), mAccountInfo.getEmail())); - } - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/UpdatePasswordInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/UpdatePasswordInfoBar.java deleted file mode 100644 index 2ed82550..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/UpdatePasswordInfoBar.java +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2016 The Chromium Authors -// 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.infobar; - -import android.text.TextUtils; -import android.widget.Spinner; - -import org.chromium.base.annotations.CalledByNative; -import org.chromium.chrome.R; -import org.chromium.components.infobars.ConfirmInfoBar; -import org.chromium.components.infobars.InfoBar; -import org.chromium.components.infobars.InfoBarControlLayout; -import org.chromium.components.infobars.InfoBarControlLayout.InfoBarArrayAdapter; -import org.chromium.components.infobars.InfoBarLayout; -import org.chromium.components.signin.base.AccountInfo; - -/** - * The Update Password infobar offers the user the ability to update a password for the site. - */ -public class UpdatePasswordInfoBar extends ConfirmInfoBar { - private final String[] mUsernames; - private final int mUsernameIndex; - private final String mDetailsMessage; - private final AccountInfo mAccountInfo; - private Spinner mUsernamesSpinner; - - @CalledByNative - private static InfoBar show(int iconId, String[] usernames, int selectedUsername, - String message, String detailsMessage, String primaryButtonText, - AccountInfo accountInfo) { - // If accountInfo is empty, no footer will be shown. - return new UpdatePasswordInfoBar(iconId, usernames, selectedUsername, message, - detailsMessage, primaryButtonText, accountInfo); - } - - private UpdatePasswordInfoBar(int iconDrawableId, String[] usernames, int selectedUsername, - String message, String detailsMessage, String primaryButtonText, - AccountInfo accountInfo) { - super(iconDrawableId, R.color.infobar_icon_drawable_color, null, message, null, - primaryButtonText, null); - mDetailsMessage = detailsMessage; - mUsernames = usernames; - mUsernameIndex = selectedUsername; - mAccountInfo = accountInfo; - } - - @Override - public void createContent(InfoBarLayout layout) { - super.createContent(layout); - - InfoBarControlLayout usernamesLayout = layout.addControlLayout(); - if (mUsernames.length > 1) { - InfoBarArrayAdapter<String> usernamesAdapter = - new InfoBarArrayAdapter<String>(getContext(), mUsernames); - mUsernamesSpinner = usernamesLayout.addSpinner( - R.id.password_infobar_accounts_spinner, usernamesAdapter); - mUsernamesSpinner.setSelection(mUsernameIndex); - } else { - usernamesLayout.addDescription(mUsernames[0]); - } - - if (!TextUtils.isEmpty(mDetailsMessage)) { - InfoBarControlLayout detailsMessageLayout = layout.addControlLayout(); - detailsMessageLayout.addDescription(mDetailsMessage); - } - - if (mAccountInfo != null && !TextUtils.isEmpty(mAccountInfo.getEmail()) - && mAccountInfo.getAccountImage() != null) { - layout.addFooterView(PasswordInfoBarUtils.createAccountIndicationFooter( - layout.getContext(), mAccountInfo.getAccountImage(), mAccountInfo.getEmail())); - } - } - - @CalledByNative - private int getSelectedUsername() { - return mUsernames.length == 1 ? 0 : mUsernamesSpinner.getSelectedItemPosition(); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java index 5666365..231869b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SyncPromoView.java
@@ -60,6 +60,7 @@ } @Override + @SuppressWarnings("WrongViewCast") // False positive. protected void onFinishInflate() { super.onFinishInflate();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroidImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroidImpl.java index 0d7122b..e3f204b2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroidImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroidImpl.java
@@ -390,11 +390,6 @@ return mDelegate.controlsResizeView(); } - @Override - public int getVirtualKeyboardHeight() { - return mDelegate.getVirtualKeyboardHeight(); - } - @VisibleForTesting void showFramebustBlockInfobarForTesting(String url) { TabWebContentsDelegateAndroidImplJni.get().showFramebustBlockInfoBar(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java index 036f6f94..228823c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/ChromeTabCreator.java
@@ -111,6 +111,20 @@ * @param loadUrlParams parameters of the url load. * @param type Information about how the tab was launched. * @param parent the parent tab, if present. + * @param position the requested position (index in the tab model) + * @return The new tab. + */ + @Override + public Tab createNewTab( + LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent, int position) { + return createNewTab(loadUrlParams, type, parent, position, null); + } + + /** + * Creates a new tab and posts to UI. + * @param loadUrlParams parameters of the url load. + * @param type Information about how the tab was launched. + * @param parent the parent tab, if present. * @param intent the source of the url if it isn't null. * @return The new tab. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java index bc6e7c6..461b8c3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java
@@ -817,7 +817,7 @@ Log.w(TAG, "Failed to restore TabState; creating Tab with last known URL."); Tab fallbackTab = mTabCreatorManager.getTabCreator(isIncognito) .createNewTab(new LoadUrlParams(tabToRestore.url), - TabLaunchType.FROM_RESTORE, null); + TabLaunchType.FROM_RESTORE, null, restoredIndex); if (fallbackTab == null) { RecordHistogram.recordEnumeratedHistogram("Tabs.TabRestoreMethod", @@ -832,8 +832,8 @@ RecordHistogram.recordEnumeratedHistogram("Tabs.TabRestoreMethod", TabRestoreMethod.CREATE_NEW_TAB, TabRestoreMethod.NUM_ENTRIES); - tabId = fallbackTab.getId(); - model.moveTab(tabId, restoredIndex); + // restoredIndex might not be the one used in createNewTab so update accordingly. + restoredIndex = model.indexOf(fallbackTab); } // If the tab is being restored from a merge and its index is 0, then the model being
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/TabDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/TabDelegate.java index 653d948..a38543d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/TabDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/TabDelegate.java
@@ -137,6 +137,13 @@ } @Override + public Tab createNewTab( + LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent, int position) { + // Ignore position as it isn't supported for async creation. + return createNewTab(loadUrlParams, type, parent); + } + + @Override public void createNewTab( AsyncTabCreationParams asyncParams, @TabLaunchType int type, int parentId) { assert asyncParams != null;
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index ca13030..f641e36 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -19,6 +19,7 @@ import( "//chrome/browser/commerce/subscriptions/test/android/test_java_sources.gni") import("//chrome/browser/share/android/test_java_sources.gni") +import("//chrome/browser/tab_group/javatests/tab_groups_test_java_sources.gni") import("//chrome/common/features.gni") import("//components/feed/features.gni") import("//components/offline_pages/buildflags/features.gni") @@ -39,6 +40,7 @@ chrome_junit_test_java_sources += feed_junit_test_java_sources chrome_test_java_sources += feed_test_java_sources chrome_test_java_sources += start_surface_test_java_sources +chrome_test_java_sources += tab_groups_test_java_sources chrome_junit_test_java_sources += start_surface_junit_java_sources chrome_junit_test_java_sources += tab_management_junit_java_sources chrome_junit_test_java_sources += price_tracking_junit_test_java_sources
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/MainActivityWithURLTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/MainActivityWithURLTest.java index 83cc90399..991b6bfa 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/MainActivityWithURLTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/MainActivityWithURLTest.java
@@ -16,6 +16,7 @@ import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -23,6 +24,7 @@ import org.chromium.chrome.test.util.ChromeTabUtils; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.net.test.EmbeddedTestServer; +import org.chromium.ui.test.util.UiRestriction; /** * Tests starting the activity with URLs. @@ -62,6 +64,7 @@ @Test @SmallTest @Feature({"Navigation"}) + @Restriction(UiRestriction.RESTRICTION_TYPE_TABLET) // https://crbug.com/1392547 public void testLaunchActivity() { // Launch chrome mActivityTestRule.startMainActivityFromLauncher();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ViewTransitionPixelTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ViewTransitionPixelTest.java deleted file mode 100644 index 2e2ef91..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ViewTransitionPixelTest.java +++ /dev/null
@@ -1,491 +0,0 @@ -// Copyright 2022 The Chromium Authors -// 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; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.support.test.InstrumentationRegistry; -import android.text.TextUtils; -import android.util.Base64; - -import androidx.test.filters.MediumTest; - -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.test.util.Batch; -import org.chromium.base.test.util.CallbackHelper; -import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.Criteria; -import org.chromium.base.test.util.CriteriaHelper; -import org.chromium.base.test.util.CriteriaNotSatisfiedException; -import org.chromium.chrome.browser.flags.ChromeSwitches; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.content_public.browser.WebContents; -import org.chromium.content_public.browser.test.util.Coordinates; -import org.chromium.content_public.browser.test.util.DOMUtils; -import org.chromium.content_public.browser.test.util.JavaScriptUtils; -import org.chromium.content_public.browser.test.util.TestThreadUtils; -import org.chromium.net.test.EmbeddedTestServer; -import org.chromium.ui.mojom.VirtualKeyboardMode; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Tests view-transitions API in relation to Android Chrome UI. - * - * These test that view transitions result in correctly sized and positioned transitions in the - * presence/absence of UI such as virtual-keyboard and moveable URL bar. - * - * See https://github.com/WICG/shared-element-transitions/blob/main/explainer.md - * TODO(bokan): Link to relevant spec when ready. - */ -@RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, - "enable-features=ViewTransition", "hide-scrollbars"}) -@Batch(Batch.PER_CLASS) -public class ViewTransitionPixelTest { - @Rule - public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); - - private static final String TEXTFIELD_DOM_ID = "inputElement"; - private static final int TEST_TIMEOUT = 10000; - - // How many pixels can differ in the pixel test before comparison is considered non-equivalent. - // Experimentally determined to allow some difference due to compositing and raster but not to - // allow false positives. - private static final int PIXEL_DIFF_FUZZINESS = 4000; - - // When performing the pixel test, this is the threshold within which pixel color channels are - // considered equivalent. Experimentally determined to allow minor raster differences when - // compositing decisions change. - private static final int PIXEL_COLOR_CHANNEL_DIFF_FUZZINESS = 10; - - private static final String CAPTURE_NEW = "new"; - private static final String CAPTURE_OLD = "old"; - - private EmbeddedTestServer mTestServer; - - private int mInitialPageHeight; - private double mInitialVVHeight; - - @VirtualKeyboardMode.EnumType - private int mVirtualKeyboardMode = VirtualKeyboardMode.RESIZES_VISUAL; - - @Before - public void setUp() { - mTestServer = EmbeddedTestServer.createAndStartServer(InstrumentationRegistry.getContext()); - } - - @After - public void tearDown() { - if (mTestServer != null) { - mTestServer.stopAndDestroyServer(); - } - } - - private void startTest(@VirtualKeyboardMode.EnumType int vkMode, String captureWhich) - throws Throwable { - mVirtualKeyboardMode = vkMode; - String url = "/chrome/test/data/android/view_transition.html"; - - if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_VISUAL) { - url += "?resizes-visual"; - } else if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_CONTENT) { - url += "?resizes-content"; - } else { - Assert.fail("Unexpected virtual keyboard mode"); - } - - // Set the animation direction to either capture the new or the old state. - url += "&" + captureWhich; - - mActivityTestRule.startMainActivityWithURL(mTestServer.getURL(url)); - mActivityTestRule.waitForActivityNativeInitializationComplete(); - - mInitialPageHeight = getPageInnerHeight(); - mInitialVVHeight = getVisualViewportHeight(); - - // startMainActivityWithURL will wait for the renderer to produce a - // frame but not for it to be presented. Since we can take screenshots - // right after this, ensure we've presented. - waitForFramePresented(); - } - - private void assertWaitForKeyboardStatus(final boolean show) { - CriteriaHelper.pollUiThread(() -> { - boolean isKeyboardShowing = mActivityTestRule.getKeyboardDelegate().isKeyboardShowing( - mActivityTestRule.getActivity(), mActivityTestRule.getActivity().getTabsView()); - Criteria.checkThat(isKeyboardShowing, Matchers.is(show)); - }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); - } - - private void assertWaitForPageHeight(double expectedPageHeight) { - CriteriaHelper.pollInstrumentationThread(() -> { - try { - int curHeight = getPageInnerHeight(); - // Allow 1px delta to account for device scale factor rounding. - Criteria.checkThat( - (double) curHeight, Matchers.closeTo(expectedPageHeight, /*error=*/1.0)); - } catch (Throwable e) { - throw new CriteriaNotSatisfiedException(e); - } - }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); - } - - private void assertWaitForVisualViewportHeight(double expectedHeight) { - CriteriaHelper.pollInstrumentationThread(() -> { - try { - double curHeight = getVisualViewportHeight(); - // Allow 1px delta to account for device scale factor rounding. - Criteria.checkThat(curHeight, Matchers.closeTo(expectedHeight, /*error=*/1.0)); - } catch (Throwable e) { - throw new CriteriaNotSatisfiedException(e); - } - }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); - } - - private WebContents getWebContents() { - return mActivityTestRule.getActivity().getActivityTab().getWebContents(); - } - - private int getPageInnerHeight() throws Throwable { - return Integer.parseInt(JavaScriptUtils.executeJavaScriptAndWaitForResult( - getWebContents(), "window.innerHeight")); - } - - private double getVisualViewportHeight() throws Throwable { - return Float.parseFloat(JavaScriptUtils.executeJavaScriptAndWaitForResult( - getWebContents(), "window.visualViewport.height")); - } - - private void showAndWaitForKeyboard() throws Throwable { - DOMUtils.clickNode(getWebContents(), TEXTFIELD_DOM_ID); - TestThreadUtils.runOnUiThreadBlocking(() - -> mActivityTestRule.getActivity() - .getManualFillingComponent() - .forceShowForTesting()); - - assertWaitForKeyboardStatus(true); - - double keyboardHeight = getKeyboardHeightDp(); - - // Use less than or equal since the keyboard may actually include accessories like the - // Autofill bar. - if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_VISUAL) { - assertWaitForVisualViewportHeight(mInitialVVHeight - keyboardHeight); - } else if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_CONTENT) { - assertWaitForPageHeight(mInitialPageHeight - keyboardHeight); - } else { - Assert.fail("Unimplemented keyboard mode"); - } - } - - private void hideKeyboard() throws Throwable { - TestThreadUtils.runOnUiThreadBlocking( - () -> mActivityTestRule.getActivity().getManualFillingComponent().hide()); - JavaScriptUtils.executeJavaScriptAndWaitForResult( - getWebContents(), "document.activeElement.blur()"); - } - - private void waitForKeyboardHidden() { - assertWaitForKeyboardStatus(false); - if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_VISUAL) { - assertWaitForVisualViewportHeight(mInitialVVHeight); - } else if (mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_CONTENT) { - assertWaitForPageHeight(mInitialPageHeight); - } else { - Assert.fail("Unimplemented keyboard mode"); - } - } - - private double getKeyboardHeightDp() { - final double dpi = Coordinates.createFor(getWebContents()).getDeviceScaleFactor(); - double keyboardHeightPx = - mActivityTestRule.getKeyboardDelegate().calculateTotalKeyboardHeight( - mActivityTestRule.getActivity().getWindow().getDecorView().getRootView()); - return keyboardHeightPx / dpi; - } - - private String bitmapToDataUrl(Bitmap bmp) { - // Scale down the image so that we can fit the resulting data: URL into Android's 4000 - // character log line limit. 300px of width is an arbitrary choice that experimentally - // results in data: URLs about 1000 chars in length. - double scale = 300.0 / bmp.getWidth(); - Bitmap scaledDownBmp = Bitmap.createScaledBitmap( - bmp, (int) (bmp.getWidth() * scale), (int) (bmp.getHeight() * scale), true); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - scaledDownBmp.compress(Bitmap.CompressFormat.PNG, 50, os); - String url = - "data:image/png;base64," + Base64.encodeToString(os.toByteArray(), Base64.NO_WRAP); - - if (url.length() > 4000) { - return "<IMAGE TOO LARGE TO FIT IN LOG>"; - } - - return url; - } - - private Bitmap takeScreenshot() throws Throwable { - Context context = InstrumentationRegistry.getContext(); - - final CallbackHelper ch = new CallbackHelper(); - final AtomicReference<String> screenshotOutputPath = new AtomicReference<>(); - TestThreadUtils.runOnUiThreadBlocking(() -> { - getWebContents().getRenderWidgetHostView().writeContentBitmapToDiskAsync( - /*width=*/0, /*height=*/0, context.getCacheDir().getAbsolutePath(), path -> { - screenshotOutputPath.set(path); - ch.notifyCalled(); - }); - }); - - ch.waitForNext(TEST_TIMEOUT, TimeUnit.SECONDS); - - if (TextUtils.isEmpty(screenshotOutputPath.get())) { - throw new Exception("Failed to take screenshot"); - } - - File outputFile = new File(screenshotOutputPath.get()); - outputFile.deleteOnExit(); - Bitmap screenshot = BitmapFactory.decodeFile(outputFile.getAbsolutePath()); - outputFile.delete(); - return screenshot; - } - - // This will start the transition and wait until snapshots for the old page have been - // taken. This will return only once the domUpdate callback has run (but not resolved). The - // transition animation doesn't start until the test calls startTransitionAnimation. - private void createTransitionAndWaitUntilDomUpdateDispatched() throws Throwable { - JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), "createTransition()"); - JavaScriptUtils.runJavascriptWithAsyncResult(getWebContents(), - "readyToStartPromise.then(() => domAutomationController.send(true));"); - } - - // After calling createTransitionAndWaitUntilDomUpdateDispatched to create a transition, this - // will continue the transition and start the animation. - private void startTransitionAnimation() throws Throwable { - JavaScriptUtils.executeJavaScriptAndWaitForResult( - getWebContents(), "startTransitionAnimation();"); - } - - // Force generating a new compositor frame from the renderer and wait until - // its presented on screen. - private void waitForFramePresented() throws Throwable { - final CallbackHelper ch = new CallbackHelper(); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - getWebContents().getMainFrame().insertVisualStateCallback(result -> ch.notifyCalled()); - }); - - ch.waitForNext(TEST_TIMEOUT, TimeUnit.SECONDS); - - // insertVisualStateCallback replies when a CompositorFrame is submitted. However, we want - // to wait until the Viz process has received the new CompositorFrame so that the new frame - // is available to a CopySurfaceRequest. Waiting for a second frame to be submitted - // guarantees this since it cannot be sent until the first frame was ACKed by Viz. - TestThreadUtils.runOnUiThreadBlocking(() -> { - getWebContents().getMainFrame().insertVisualStateCallback(result -> ch.notifyCalled()); - }); - - ch.waitForNext(TEST_TIMEOUT, TimeUnit.SECONDS); - } - - private boolean doPixelsApproximatelyMatch(int expected, int actual, int threshold) { - return Math.abs(Color.red(expected) - Color.red(actual)) < threshold - && Math.abs(Color.green(expected) - Color.green(actual)) < threshold - && Math.abs(Color.blue(expected) - Color.blue(actual)) < threshold; - } - - // Compares the expected to the actual screenshot bitmaps and returns true if they're - // equivalent. Some fuzziness is allowed to account for blending and compositing artifacts. If - // failed, the test is failed with a message containing paths to a data: URL for each of the - // bitmaps. These can be easily viewed using `adb shell cat filename` and copied into a browser - // for viewing. - private boolean doPixelTestScreenshotsMatch(Bitmap expected, Bitmap actual) throws Throwable { - Assert.assertEquals(expected.getWidth(), actual.getWidth()); - Assert.assertEquals(expected.getHeight(), actual.getHeight()); - - int failingPixels = 0; - for (int y = 0; y < expected.getHeight(); ++y) { - for (int x = 0; x < expected.getWidth(); ++x) { - int expectedColor = expected.getPixel(x, y); - int actualColor = actual.getPixel(x, y); - - if (!doPixelsApproximatelyMatch( - expectedColor, actualColor, PIXEL_COLOR_CHANNEL_DIFF_FUZZINESS)) { - ++failingPixels; - } - } - } - - if (failingPixels > PIXEL_DIFF_FUZZINESS) { - String url_expected = bitmapToDataUrl(expected); - String url_actual = bitmapToDataUrl(actual); - Assert.fail("Does not match reference screenshot, " + failingPixels - + " pixels differed.\n" - + " Expected screenshot (" + url_expected + ")\n" - + " Actual screenshot(" + url_actual + ")"); - return false; - } - - return true; - } - - /** - * Test view transitions when going from a state with a virtual keyboard shown to the virtual - * keyboard hidden. - * - * This tests the default mode where the virtual-keyboard resizes only the visual viewport and - * the author hasn't opted into a content-resizing virtual keyboard. - */ - @Test - @MediumTest - public void testVirtualKeyboardResizesVisualOld() throws Throwable { - startTest(VirtualKeyboardMode.RESIZES_VISUAL, CAPTURE_OLD); - - // Since the keyboard affects only the visual viewport, the initial page is how we expect - // the transition snapshot to look when the keyboard is hidden. - Bitmap expected = takeScreenshot(); - - showAndWaitForKeyboard(); - - createTransitionAndWaitUntilDomUpdateDispatched(); - - // Note: rendering is blocked here so we can't wait for the keyboard to hide since the size - // depends on the renderer. - hideKeyboard(); - - // Start the animation. The "animation" simply displays the old transition for the full - // duration of the test. - startTransitionAnimation(); - - waitForKeyboardHidden(); - - // Wait for a frame to be presented to ensure the animation has started and the updated - // viewport size is rendered. - waitForFramePresented(); - - Bitmap actual = takeScreenshot(); - - Assert.assertTrue(doPixelTestScreenshotsMatch(expected, actual)); - } - - /** - * Test view transitions when going from a state with a virtual keyboard shown to the virtual - * keyboard hidden. - * - * This tests the mode where the author opts in to the keyboard resizing page content. - */ - @Test - @MediumTest - public void testVirtualKeyboardResizesContentOld() throws Throwable { - startTest(VirtualKeyboardMode.RESIZES_CONTENT, CAPTURE_OLD); - - // Since the keyboard affects content it'll push the bottom-fixed element up. Push it up - // manually to take the expected screenshot. - { - showAndWaitForKeyboard(); - - double keyboardHeight = getKeyboardHeightDp(); - - hideKeyboard(); - waitForKeyboardHidden(); - - JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), - "document.getElementById('bottomfixed').style.transform =" - + "'translateY(-" + keyboardHeight + "px)';"); - - waitForFramePresented(); - } - - Bitmap expected = takeScreenshot(); - - { - JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), - "document.getElementById('bottomfixed').style.transform = '';"); - } - - showAndWaitForKeyboard(); - - createTransitionAndWaitUntilDomUpdateDispatched(); - - // Note: rendering is blocked here so we can't wait for the keyboard to hide since the size - // depends on the renderer. - hideKeyboard(); - - // Start the animation. The "animation" simply displays the old transition for the full - // duration of the test. - startTransitionAnimation(); - - waitForKeyboardHidden(); - - // Wait for a frame to be presented to ensure the animation has started and the updated - // viewport size is rendered. - waitForFramePresented(); - - Bitmap actual = takeScreenshot(); - - Assert.assertTrue(doPixelTestScreenshotsMatch(expected, actual)); - } - - /** - * Test view transitions when going from a state with a virtual keyboard shown to the virtual - * keyboard hidden. - * - * This tests the mode where the author opts in to the keyboard resizing page content. - */ - @Test - @MediumTest - public void testVirtualKeyboardResizesContentNew() throws Throwable { - startTest(VirtualKeyboardMode.RESIZES_CONTENT, CAPTURE_NEW); - - Bitmap expected; - - // Since this test checks new state, the keyboard will be down so all that must be done - // for the reference screenshot is to update the DOM to the final state. - { - JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), "updateDOM()"); - waitForFramePresented(); - - expected = takeScreenshot(); - - JavaScriptUtils.executeJavaScriptAndWaitForResult(getWebContents(), "undoUpdateDOM()"); - } - - showAndWaitForKeyboard(); - - createTransitionAndWaitUntilDomUpdateDispatched(); - - // Note: rendering is blocked here so we can't wait for the keyboard to hide since the size - // depends on the renderer. - hideKeyboard(); - - // Start the animation. The "animation" simply displays the new transition for the full - // duration of the test. - startTransitionAnimation(); - - waitForKeyboardHidden(); - - // Wait for a frame to be presented to ensure the animation has started and the updated - // viewport size is rendered. - waitForFramePresented(); - - Bitmap actual = takeScreenshot(); - - Assert.assertTrue(doPixelTestScreenshotsMatch(expected, actual)); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java deleted file mode 100644 index b01d0c07..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/share/LensUtilsTest.java +++ /dev/null
@@ -1,232 +0,0 @@ -// Copyright 2019 The Chromium Authors -// 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; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; - -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; - -import androidx.test.filters.SmallTest; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.chrome.browser.IntentHandler; -import org.chromium.chrome.browser.flags.ChromeFeatureList; -import org.chromium.chrome.browser.flags.ChromeSwitches; -import org.chromium.chrome.test.ChromeBrowserTestRule; -import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.content_public.browser.test.util.TestThreadUtils; - -/** - * Tests of {@link LensUtils}. - * TODO(https://crbug.com/1054738): Reimplement LensUtilsTest as robolectric tests - */ -@RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE) -public class LensUtilsTest { - @Rule - public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule(); - - private static final String TEST_MIN_AGSA_VERSION = "11.34"; - private static final String TEST_MIN_AGSA_VERSION_BELOW_DIRECT_INTENT_MIN = "11.33.9"; - - @Mock - Context mContext; - @Mock - PackageManager mPackageManager; - @Mock - PackageInfo mPackageInfo; - - @Before - public void setUp() throws NameNotFoundException { - MockitoAnnotations.initMocks(this); - doReturn(mContext).when(mContext).getApplicationContext(); - doReturn(mPackageManager).when(mContext).getPackageManager(); - doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(IntentHandler.PACKAGE_GSA, 0); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabled()} method when disable incognito param is - * unset and user is incognito. - */ - @Test - @SmallTest - public void isGoogleLensFeatureEnabled_incognitoParamUnsetIncognitoUser() { - Assert.assertFalse("Feature incorrectly enabled when incognito param is not set", - isGoogleLensFeatureEnabledOnUiThread(true)); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabled()} method when incognito users are enabled - * and user is incognito. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/false"}) - @Test - @SmallTest - public void - isGoogleLensFeatureEnabled_incognitoEnabledIncognitoUser() { - Assert.assertTrue("Feature incorrectly disabled when incognito param is not set", - isGoogleLensFeatureEnabledOnUiThread(true)); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabled()} method when incognito users are disabled - * and user is incognito. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true"}) - @Test - @SmallTest - public void - isGoogleLensFeatureEnabled_incognitoDisabledIncognitoUser() { - Assert.assertFalse("Feature incorrectly not disabled when incognito param was set", - isGoogleLensFeatureEnabledOnUiThread(true)); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabled()} method when incognito users are disabled - * and user is not incognito. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true"}) - @Test - @SmallTest - public void - isGoogleLensFeatureEnabled_incognitoDisabledStandardUser() { - Assert.assertTrue("Feature incorrectly disabled when user was not incognito", - isGoogleLensFeatureEnabledOnUiThread(false)); - } - - /** - * Test {@link LensUtils#shouldLogUkmByFeature(featureName)} method for enable UKM logging for - * Lens chip integration. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" - + "logUkm/true"}) - @Test - @SmallTest - public void - shouldLogUkm_translateChipUkmLoggingEnabled() { - assertTrue( - shouldLogUkmOnUiThread(ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS)); - } - - /** - * Test {@link LensUtils#shouldLogUkmByFeature(featureName)} method for enable UKM logging for - * Lens chip integration. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" - + "logUkm/false"}) - @Test - @SmallTest - public void - shouldLogUkm_translateChipUkmLoggingDisabled() { - assertFalse( - shouldLogUkmOnUiThread(ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS)); - } - - /** - * Test {@link LensUtils#shouldLogUkmByFeature(featureName)} method for enable UKM logging for - * Lens chip integration. - */ - @CommandLineFlags. - Add({"enable-features=" + ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" - + "logUkm/true"}) - @Test - @SmallTest - public void - shouldLogUkm_shoppingChipUkmLoggingEnabled() { - assertTrue(shouldLogUkmOnUiThread(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP)); - } - - /** - * Test {@link LensUtils#shouldLogUkmByFeature(featureName)} method for enable UKM logging for - * Lens chip integration. - */ - @CommandLineFlags. - Add({"enable-features=" + ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:disableOnIncognito/true/" - + "logUkm/false"}) - @Test - @SmallTest - public void - shouldLogUkm_shoppingChipUkmLoggingDisabled() { - assertFalse(shouldLogUkmOnUiThread(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP)); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabledOnTablet()} method when search with Google - * Lens is enabled. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled"}) - @Test - @SmallTest - public void - isGoogleLensFeatureEnabled_tabletDisabled() { - Assert.assertFalse("Feature incorrectly enabled when Lens on tablet was disabled", - isGoogleLensFeatureEnabledOnTabletOnUiThread()); - } - - /** - * Test {@link LensUtils#isGoogleLensFeatureEnabledOnTablet()} method when search with Google - * Lens is enabled. - */ - @CommandLineFlags.Add({"enable-features=" - + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS + "<FakeStudyName", - "force-fieldtrials=FakeStudyName/Enabled", - "force-fieldtrial-params=FakeStudyName.Enabled:enableContextMenuSearchOnTablet/true"}) - @Test - @SmallTest - public void - isGoogleLensFeatureEnabled_tabletEnabled() { - Assert.assertTrue("Feature incorrectly disabled when Lens on tablet was enabled", - isGoogleLensFeatureEnabledOnTabletOnUiThread()); - } - - private boolean isGoogleLensFeatureEnabledOnUiThread(boolean isIncognito) { - return TestThreadUtils.runOnUiThreadBlockingNoException( - () -> LensUtils.isGoogleLensFeatureEnabled(isIncognito)); - } - - private boolean shouldLogUkmOnUiThread(String featureName) { - return TestThreadUtils.runOnUiThreadBlockingNoException( - () -> LensUtils.shouldLogUkmByFeature(featureName)); - } - - private boolean isGoogleLensFeatureEnabledOnTabletOnUiThread() { - return TestThreadUtils.runOnUiThreadBlockingNoException( - () -> LensUtils.isGoogleLensFeatureEnabledOnTablet()); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreUnitTest.java index c54804a..f63dbae 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreUnitTest.java
@@ -82,6 +82,10 @@ private TabModel mNormalTabModel; @Mock private TabModel mIncognitoTabModel; + @Mock + private TabModelFilterProvider mTabModelFilterProvider; + private TabModelFilter mNormalTabModelFilter; + private TabModelFilter mIncognitoTabModelFilter; @Mock private TabCreatorManager mTabCreatorManager; @@ -109,6 +113,12 @@ .thenReturn(TabPersistentStore.SAVED_STATE_FILE_PREFIX + "state_files_yay"); when(mPersistencePolicy.isMergeInProgress()).thenReturn(false); when(mPersistencePolicy.performInitialization(any(TaskRunner.class))).thenReturn(false); + + when(mTabModelSelector.getTabModelFilterProvider()).thenReturn(mTabModelFilterProvider); + mNormalTabModelFilter = new EmptyTabModelFilter(mNormalTabModel); + mIncognitoTabModelFilter = new EmptyTabModelFilter(mIncognitoTabModel); + when(mTabModelFilterProvider.getTabModelFilter(false)).thenReturn(mNormalTabModelFilter); + when(mTabModelFilterProvider.getTabModelFilter(true)).thenReturn(mIncognitoTabModelFilter); } @After @@ -220,7 +230,7 @@ verify(mNormalTabCreator) .createNewTab(argThat(new LoadUrlParamsUrlMatcher(UrlConstants.NTP_URL)), - eq(TabLaunchType.FROM_RESTORE), (Tab) isNull()); + eq(TabLaunchType.FROM_RESTORE), (Tab) isNull(), eq(0)); } @Test @@ -245,14 +255,14 @@ mPersistentStore.restoreTab(emptyNtpDetails, null, null, false); verify(mNormalTabCreator) .createNewTab(argThat(new LoadUrlParamsUrlMatcher(UrlConstants.NTP_URL)), - eq(TabLaunchType.FROM_RESTORE), (Tab) isNull()); + eq(TabLaunchType.FROM_RESTORE), (Tab) isNull(), eq(0)); TabRestoreDetails emptyIncognitoNtpDetails = new TabRestoreDetails(1, 0, true, UrlConstants.NTP_URL, true); mPersistentStore.restoreTab(emptyIncognitoNtpDetails, null, null, false); verify(mIncognitoTabCreator) .createNewTab(argThat(new LoadUrlParamsUrlMatcher(UrlConstants.NTP_URL)), - eq(TabLaunchType.FROM_RESTORE), (Tab) isNull()); + eq(TabLaunchType.FROM_RESTORE), (Tab) isNull(), eq(0)); } @Test @@ -296,7 +306,7 @@ verify(mIncognitoTabCreator) .createNewTab(argThat(new LoadUrlParamsUrlMatcher(UrlConstants.NTP_URL)), - eq(TabLaunchType.FROM_RESTORE), (Tab) isNull()); + eq(TabLaunchType.FROM_RESTORE), (Tab) isNull(), eq(0)); } @Test
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java index c213be2..8772692 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java
@@ -32,6 +32,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -72,6 +73,9 @@ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ChromeBackupAgentTest.BackupManagerShadow.class}) public class ChromeBackupAgentTest { + @Rule + public TemporaryFolder mTempDir = new TemporaryFolder(); + /** * Shadow to allow counting of dataChanged calls. */ @@ -173,17 +177,16 @@ // Mock the backup data. BackupDataOutput backupData = mock(BackupDataOutput.class); - // Create a state file. - File stateFile1 = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w")); - // Set up some preferences to back up. SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); setUpTestPrefs(prefs); - // Run the test function. - mAgent.onBackup(null, backupData, newState); + File stateFile = mTempDir.newFile(); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + stateFile, ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Run the test function. + mAgent.onBackup(null, backupData, newState); + } // Check that the right things were written to the backup verify(backupData).writeEntityHeader("native.pref1", 1); @@ -212,36 +215,34 @@ verify(backupData, times(0)) .writeEntityHeader(eq("AndroidDefault." + PREFERENCE_KEY_NOT_BACKED_UP), anyInt()); - newState.close(); - // Check that the state was saved correctly - ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile1)); - ArrayList<String> names = (ArrayList<String>) newStateStream.readObject(); - assertThat(names.size(), equalTo(6)); - assertThat(names, hasItem("native.pref1")); - assertThat( - names, hasItem("AndroidDefault." + ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE)); - assertThat(names, - hasItem("AndroidDefault." + ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED)); - assertThat(names, - hasItem("AndroidDefault." - + ChromePreferenceKeys.FIRST_RUN_LIGHTWEIGHT_FLOW_COMPLETE)); - assertThat(names, - hasItem("AndroidDefault." - + ChromePreferenceKeys.PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER)); - assertThat(names, hasItem("AndroidDefault." + ChromeBackupAgentImpl.SIGNED_IN_ACCOUNT_KEY)); - ArrayList<byte[]> values = (ArrayList<byte[]>) newStateStream.readObject(); - assertThat(values.size(), equalTo(6)); - assertThat(values, hasItem(unameBytes)); - assertThat(values, hasItem(new byte[] {0})); - assertThat(values, hasItem(new byte[] {1})); + try (ObjectInputStream newStateStream = + new ObjectInputStream(new FileInputStream(stateFile))) { + ArrayList<String> names = (ArrayList<String>) newStateStream.readObject(); + assertThat(names.size(), equalTo(6)); + assertThat(names, hasItem("native.pref1")); + assertThat(names, + hasItem("AndroidDefault." + ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE)); + assertThat(names, + hasItem("AndroidDefault." + + ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED)); + assertThat(names, + hasItem("AndroidDefault." + + ChromePreferenceKeys.FIRST_RUN_LIGHTWEIGHT_FLOW_COMPLETE)); + assertThat(names, + hasItem("AndroidDefault." + + ChromePreferenceKeys.PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER)); + assertThat(names, + hasItem("AndroidDefault." + ChromeBackupAgentImpl.SIGNED_IN_ACCOUNT_KEY)); + ArrayList<byte[]> values = (ArrayList<byte[]>) newStateStream.readObject(); + assertThat(values.size(), equalTo(6)); + assertThat(values, hasItem(unameBytes)); + assertThat(values, hasItem(new byte[] {0})); + assertThat(values, hasItem(new byte[] {1})); - // Make sure that there are no extra objects. - assertThat(newStateStream.available(), equalTo(0)); - - // Tidy up. - newStateStream.close(); - stateFile1.delete(); + // Make sure that there are no extra objects. + assertThat(newStateStream.available(), equalTo(0)); + } } /** @@ -254,54 +255,46 @@ // Mock the backup data. BackupDataOutput backupData = mock(BackupDataOutput.class); - // Create a state file. - File stateFile1 = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w")); - // Set up some preferences to back up. SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); setUpTestPrefs(prefs); - // Do a first backup. - mAgent.onBackup(null, backupData, newState); + File stateFile1 = mTempDir.newFile(); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + stateFile1, ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a first backup. + mAgent.onBackup(null, backupData, newState); + } // Minimal check on first backup, this isn't the test here. verify(backupData, times(6)).writeEntityHeader(anyString(), anyInt()); verify(backupData, times(6)).writeEntityData(any(byte[].class), anyInt()); - newState.close(); + File stateFile2 = mTempDir.newFile(); + try (ParcelFileDescriptor oldState = + ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.MODE_READ_ONLY); - ParcelFileDescriptor oldState = - ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("r")); - File stateFile2 = File.createTempFile("Test", ""); - newState = ParcelFileDescriptor.open(stateFile2, ParcelFileDescriptor.parseMode("w")); - - // Try a second backup without changing any data - mAgent.onBackup(oldState, backupData, newState); - + ParcelFileDescriptor newState = ParcelFileDescriptor.open( + stateFile2, ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Try a second backup without changing any data + mAgent.onBackup(oldState, backupData, newState); + } // Check that the second backup didn't write anything. verifyNoMoreInteractions(backupData); - oldState.close(); - newState.close(); - // The two state files should contain identical data. - ObjectInputStream oldStateStream = new ObjectInputStream(new FileInputStream(stateFile1)); - ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject(); - ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject(); - ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile2)); - ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject(); - ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject(); - assertThat(newNames, equalTo(oldNames)); - assertTrue(Arrays.deepEquals(newValues.toArray(), oldValues.toArray())); - assertThat(newStateStream.available(), equalTo(0)); - - // Tidy up. - oldStateStream.close(); - newStateStream.close(); - stateFile1.delete(); - stateFile2.delete(); + try (ObjectInputStream oldStateStream = + new ObjectInputStream(new FileInputStream(stateFile1)); + ObjectInputStream newStateStream = + new ObjectInputStream(new FileInputStream(stateFile2))) { + ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject(); + ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject(); + ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject(); + ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject(); + assertThat(newNames, equalTo(oldNames)); + assertTrue(Arrays.deepEquals(newValues.toArray(), oldValues.toArray())); + assertThat(newStateStream.available(), equalTo(0)); + } } /** @@ -314,61 +307,53 @@ // Mock the backup data. BackupDataOutput backupData = mock(BackupDataOutput.class); - // Create a state file. - File stateFile1 = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w")); - // Set up some preferences to back up. SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); setUpTestPrefs(prefs); - // Do a first backup. - mAgent.onBackup(null, backupData, newState); - + // Create a state file. + File stateFile1 = mTempDir.newFile(); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + stateFile1, ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a first backup. + mAgent.onBackup(null, backupData, newState); + } // Minimal check on first backup, this isn't the test here. verify(backupData, times(6)).writeEntityHeader(anyString(), anyInt()); verify(backupData, times(6)).writeEntityData(any(byte[].class), anyInt()); - newState.close(); - - ParcelFileDescriptor oldState = - ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("r")); - File stateFile2 = File.createTempFile("Test", ""); - newState = ParcelFileDescriptor.open(stateFile2, ParcelFileDescriptor.parseMode("w")); - // Change some data. SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(ChromePreferenceKeys.PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER, true); editor.apply(); - - // Do a second backup. reset(backupData); - mAgent.onBackup(oldState, backupData, newState); + + File stateFile2 = mTempDir.newFile(); + try (ParcelFileDescriptor oldState = + ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.MODE_WRITE_ONLY); + ParcelFileDescriptor newState = ParcelFileDescriptor.open( + stateFile2, ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a second backup. + mAgent.onBackup(oldState, backupData, newState); + } // Check that the second backup wrote something. verify(backupData, times(6)).writeEntityHeader(anyString(), anyInt()); verify(backupData, times(6)).writeEntityData(any(byte[].class), anyInt()); - oldState.close(); - newState.close(); - // the two state files should contain different data (although the names are unchanged). - ObjectInputStream oldStateStream = new ObjectInputStream(new FileInputStream(stateFile1)); - ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject(); - ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject(); - ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile2)); - ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject(); - ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject(); - assertThat(newNames, equalTo(oldNames)); - assertFalse(Arrays.deepEquals(newValues.toArray(), oldValues.toArray())); - assertThat(newStateStream.available(), equalTo(0)); - - // Tidy up. - oldStateStream.close(); - newStateStream.close(); - stateFile1.delete(); - stateFile2.delete(); + try (ObjectInputStream oldStateStream = + new ObjectInputStream(new FileInputStream(stateFile1)); + ObjectInputStream newStateStream = + new ObjectInputStream(new FileInputStream(stateFile2))) { + ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject(); + ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject(); + ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject(); + ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject(); + assertThat(newNames, equalTo(oldNames)); + assertFalse(Arrays.deepEquals(newValues.toArray(), oldValues.toArray())); + assertThat(newStateStream.available(), equalTo(0)); + } } /** @@ -400,11 +385,10 @@ // Check that a successful backup resets the failure count doReturn(true).when(mAgent).initializeBrowser(); // A successful backup needs a real state file, or lots more mocking. - File stateFile = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w")); - - mAgent.onBackup(null, backupData, newState); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + mTempDir.newFile(), ParcelFileDescriptor.MODE_WRITE_ONLY)) { + mAgent.onBackup(null, backupData, newState); + } assertThat(prefs.getInt(ChromeBackupAgentImpl.BACKUP_FAILURE_COUNT, 0), equalTo(0)); } @@ -468,16 +452,14 @@ */ @Test public void testOnRestore_normal() throws IOException { - // Create a state file. - File stateFile = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w")); - BackupDataInput backupData = createMockBackupData(); mAccountManagerTestRule.addAccount(mAccountInfo.getEmail()); - // Do a restore. - mAgent.onRestore(backupData, 0, newState); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + mTempDir.newFile(), ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a restore. + mAgent.onRestore(backupData, 0, newState); + } SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); assertTrue(prefs.getBoolean(ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE, false)); assertFalse(prefs.contains("junk")); @@ -501,15 +483,12 @@ */ @Test public void testOnRestore_badUser() throws IOException { - // Create a state file. - File stateFile = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w")); - BackupDataInput backupData = createMockBackupData(); - - // Do a restore. - mAgent.onRestore(backupData, 0, newState); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + mTempDir.newFile(), ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a restore. + mAgent.onRestore(backupData, 0, newState); + } SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); assertFalse(prefs.contains(ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE)); verify(mChromeBackupAgentJniMock, never()) @@ -530,16 +509,14 @@ */ @Test public void testOnRestore_browserStartupFails() throws IOException { - // Create a state file. - File stateFile = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w")); - BackupDataInput backupData = createMockBackupData(); doReturn(false).when(mAgent).initializeBrowser(); - // Do a restore. - mAgent.onRestore(backupData, 0, newState); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + mTempDir.newFile(), ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a restore. + mAgent.onRestore(backupData, 0, newState); + } SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); assertFalse(prefs.contains(ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE)); @@ -555,16 +532,14 @@ */ @Test public void testOnRestore_afterFirstRun() throws IOException { - // Create a state file. - File stateFile = File.createTempFile("Test", ""); - ParcelFileDescriptor newState = - ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w")); - BackupDataInput backupData = createMockBackupData(); FirstRunStatus.setFirstRunFlowComplete(true); - // Do a restore. - mAgent.onRestore(backupData, 0, newState); + try (ParcelFileDescriptor newState = ParcelFileDescriptor.open( + mTempDir.newFile(), ParcelFileDescriptor.MODE_WRITE_ONLY)) { + // Do a restore. + mAgent.onRestore(backupData, 0, newState); + } SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); assertTrue(prefs.contains(ChromePreferenceKeys.FIRST_RUN_FLOW_COMPLETE));
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/share/LensUtilsTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/share/LensUtilsTest.java new file mode 100644 index 0000000..1d63bb67 --- /dev/null +++ b/chrome/android/junit/src/org/chromium/chrome/browser/share/LensUtilsTest.java
@@ -0,0 +1,130 @@ +// Copyright 2019 The Chromium Authors +// 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; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.content.pm.PackageInfo; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowPackageManager; + +import org.chromium.base.FeatureList; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.IntentHandler; +import org.chromium.chrome.browser.flags.ChromeFeatureList; + +import java.util.Map; + +/** + * Tests of {@link LensUtils}. + */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE) +public class LensUtilsTest { + @Before + public void setUp() { + ShadowPackageManager pm = + Shadows.shadowOf(RuntimeEnvironment.getApplication().getPackageManager()); + PackageInfo packageInfo = new PackageInfo(); + packageInfo.packageName = IntentHandler.PACKAGE_GSA; + pm.installPackage(packageInfo); + } + + private static void configureFeature(String featureName, String... params) { + FeatureList.TestValues testValues = new FeatureList.TestValues(); + testValues.setFeatureFlagsOverride(Map.of(featureName, true)); + for (String param : params) { + String[] keyValue = param.split("="); + testValues.addFieldTrialParamOverride(featureName, keyValue[0], keyValue[1]); + } + FeatureList.setTestValues(testValues); + } + + @Test + public void isGoogleLensFeatureEnabled_incognitoParamUnsetIncognitoUser() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS); + Assert.assertFalse("Feature incorrectly enabled when incognito param is not set", + LensUtils.isGoogleLensFeatureEnabled(true)); + } + + @Test + public void isGoogleLensFeatureEnabled_incognitoEnabledIncognitoUser() { + configureFeature( + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS, "disableOnIncognito=false"); + Assert.assertTrue("Feature incorrectly disabled when incognito param is not set", + LensUtils.isGoogleLensFeatureEnabled(true)); + } + + @Test + public void isGoogleLensFeatureEnabled_incognitoDisabledIncognitoUser() { + configureFeature( + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS, "disableOnIncognito=true"); + Assert.assertFalse("Feature incorrectly not disabled when incognito param was set", + LensUtils.isGoogleLensFeatureEnabled(true)); + } + + @Test + public void isGoogleLensFeatureEnabled_incognitoDisabledStandardUser() { + configureFeature( + ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS, "disableOnIncognito=true"); + Assert.assertTrue("Feature incorrectly disabled when user was not incognito", + LensUtils.isGoogleLensFeatureEnabled(false)); + } + + @Test + public void shouldLogUkm_translateChipUkmLoggingEnabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS, + "disableOnIncognito=true", "logUkm=true"); + assertTrue(LensUtils.shouldLogUkmByFeature( + ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS)); + } + + @Test + public void shouldLogUkm_translateChipUkmLoggingDisabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS, + "disableOnIncognito=true", "logUkm=false"); + assertFalse(LensUtils.shouldLogUkmByFeature( + ChromeFeatureList.CONTEXT_MENU_TRANSLATE_WITH_GOOGLE_LENS)); + } + + @Test + public void shouldLogUkm_shoppingChipUkmLoggingEnabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP, "disableOnIncognito=true", + "logUkm=true"); + assertTrue( + LensUtils.shouldLogUkmByFeature(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP)); + } + + @Test + public void shouldLogUkm_shoppingChipUkmLoggingDisabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP, "disableOnIncognito=true", + "logUkm=false"); + assertFalse( + LensUtils.shouldLogUkmByFeature(ChromeFeatureList.CONTEXT_MENU_GOOGLE_LENS_CHIP)); + } + + @Test + public void isGoogleLensFeatureEnabled_tabletDisabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS); + Assert.assertFalse("Feature incorrectly enabled when Lens on tablet was disabled", + LensUtils.isGoogleLensFeatureEnabledOnTablet()); + } + + @Test + public void isGoogleLensFeatureEnabled_tabletEnabled() { + configureFeature(ChromeFeatureList.CONTEXT_MENU_SEARCH_WITH_GOOGLE_LENS, + "enableContextMenuSearchOnTablet=true"); + Assert.assertTrue("Feature incorrectly disabled when Lens on tablet was enabled", + LensUtils.isGoogleLensFeatureEnabledOnTablet()); + } +} \ No newline at end of file
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/TabModelImplUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/TabModelImplUnitTest.java index 2b7d757..086cfe9 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/TabModelImplUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/TabModelImplUnitTest.java
@@ -68,6 +68,11 @@ @Mock private TabModelSelector mTabModelSelector; + @Mock + private TabModelFilterProvider mTabModelFilterProvider; + @Mock + private TabModelFilter mTabModelFilter; + private int mNextTabId; @Before @@ -82,6 +87,12 @@ when(mTabModelDelegate.isReparentingInProgress()).thenReturn(false); + when(mTabModelSelector.getTabModelFilterProvider()).thenReturn(mTabModelFilterProvider); + when(mTabModelFilterProvider.getTabModelFilter(false)).thenReturn(mTabModelFilter); + when(mTabModelFilterProvider.getTabModelFilter(true)).thenReturn(mTabModelFilter); + when(mTabModelFilter.getValidPosition(any(), anyInt())) + .thenAnswer(i -> i.getArguments()[1]); + mNextTabId = 0; }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/UndoTabModelUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/UndoTabModelUnitTest.java index b8494ab..c5efe59b 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/UndoTabModelUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tabmodel/UndoTabModelUnitTest.java
@@ -76,6 +76,11 @@ @Mock private TabModelSelector mTabModelSelector; + @Mock + private TabModelFilterProvider mTabModelFilterProvider; + @Mock + private TabModelFilter mTabModelFilter; + private int mNextTabId; @Before @@ -90,6 +95,12 @@ when(mTabModelDelegate.isReparentingInProgress()).thenReturn(false); + when(mTabModelSelector.getTabModelFilterProvider()).thenReturn(mTabModelFilterProvider); + when(mTabModelFilterProvider.getTabModelFilter(false)).thenReturn(mTabModelFilter); + when(mTabModelFilterProvider.getTabModelFilter(true)).thenReturn(mTabModelFilter); + when(mTabModelFilter.getValidPosition(any(), anyInt())) + .thenAnswer(i -> i.getArguments()[1]); + mNextTabId = 0; }
diff --git a/chrome/app/extensions_strings.grdp b/chrome/app/extensions_strings.grdp index f0202ba..236743c 100644 --- a/chrome/app/extensions_strings.grdp +++ b/chrome/app/extensions_strings.grdp
@@ -123,6 +123,9 @@ <message name="IDS_EXTENSIONS_HOST_PERMISSIONS_DESCRIPTION" desc="The explanatory text for adjusting which websites an extension is allowed to run on."> This extension can read and change your data on sites. You can control which sites the extension can access. </message> + <message name="IDS_EXTENSIONS_PERMISSIONS_LEARN_MORE_A11Y_LABEL" desc="Accessibility label for a 'Learn more' link that links to an external help article about Extension permissions."> + Learn more about extension permissions + </message> <!-- TODO(devlin): Unify this with IDS_SETTINGS_EDIT. --> <message name="IDS_EXTENSIONS_HOST_PERMISSIONS_EDIT" desc="The label of the button used to edit an extension's access to a given website."> Edit
diff --git a/chrome/app/extensions_strings_grdp/IDS_EXTENSIONS_PERMISSIONS_LEARN_MORE_A11Y_LABEL.png.sha1 b/chrome/app/extensions_strings_grdp/IDS_EXTENSIONS_PERMISSIONS_LEARN_MORE_A11Y_LABEL.png.sha1 new file mode 100644 index 0000000..aae44c6e --- /dev/null +++ b/chrome/app/extensions_strings_grdp/IDS_EXTENSIONS_PERMISSIONS_LEARN_MORE_A11Y_LABEL.png.sha1
@@ -0,0 +1 @@ +57439d465c4a14bf1c29a9a7a2e705594afa56a1 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings.grdp b/chrome/app/os_settings_strings.grdp index d51fe74..4972a47 100644 --- a/chrome/app/os_settings_strings.grdp +++ b/chrome/app/os_settings_strings.grdp
@@ -1257,6 +1257,24 @@ <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_DESCRIPTION" desc="In the Select-to-speak settings subpage, the label for option to highlight spoken words rather than spoken nodes."> Highlight each word as it is spoken </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_DESCRIPTION" desc="In the Select-to-speak settings subpage, the label for option to pick word highlight color."> + Highlight color + </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_BLUE" desc="In the Select-to-speak settings subpage, the label for a blue highlight color."> + Blue + </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_ORANGE" desc="In the Select-to-speak settings subpage, the label for a orange highlight color."> + Orange + </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_YELLOW" desc="In the Select-to-speak settings subpage, the label for a yellow highlight color."> + Yellow + </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_GREEN" desc="In the Select-to-speak settings subpage, the label for a green highlight color."> + Green + </message> + <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_PINK" desc="In the Select-to-speak settings subpage, the label for a pink highlight color."> + Pink + </message> <message name="IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_BACKGROUND_SHADING_DESCRIPTION" desc="In the Select-to-speak settings subpage, the label for option to fade the background outside of the focus ring to improve focus on what is being spoken."> Shade background content </message> @@ -1961,11 +1979,10 @@ <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_TITLE" desc="Title of the dialog for entering details to create a new Linux container."> Create a new container </message> - <!-- TODO(crbug/1300764): Remove translateable on error strings once they are finalized.--> - <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR" translateable="false" desc="Error for invalid input when creating a new Linux container."> - This container and VM name combination already exists. + <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR" desc="Error for invalid input when creating a new Linux container."> + This container already exists. </message> - <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR" translateable="false" desc="Error for invalid input when creating a new Linux container."> + <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR" desc="Error for invalid input when creating a new Linux container."> Container name cannot be empty. </message> <message name="IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_IMAGE_SERVER" desc="Heading for the input field for entering the image server URL when creating a new Linux container.">
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_BLUE.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_BLUE.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_BLUE.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_DESCRIPTION.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_GREEN.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_GREEN.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_GREEN.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_ORANGE.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_ORANGE.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_ORANGE.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_PINK.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_PINK.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_PINK.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_YELLOW.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_YELLOW.png.sha1 new file mode 100644 index 0000000..b01ade8 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_YELLOW.png.sha1
@@ -0,0 +1 @@ +495e7be7e8332a54039dceb91d8513bed2ca0082 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR.png.sha1 index ab4ed73..3a1a08d 100644 --- a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR.png.sha1 +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_CONTAINER_EXISTS_ERROR.png.sha1
@@ -1 +1 @@ -57138bfedc642a383f6e1487f792b3ccf9b6c2e9 \ No newline at end of file +5c2bf2193152a69154cfc0920fa7f6136dc36277 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR.png.sha1 index 5fb723e..07635d8 100644 --- a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR.png.sha1 +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_CROSTINI_EXTRA_CONTAINERS_CREATE_DIALOG_EMPTY_CONTAINER_NAME_ERROR.png.sha1
@@ -1 +1 @@ -9631fa16d097228100643c28267082308e52b821 \ No newline at end of file +7d277124c80bfa5579a60518800a8253e163e490 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 831ef6f7..7aee088 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -95,7 +95,6 @@ buildflag_header("buildflags") { header = "buildflags.h" flags = [ - "ENABLE_UPDATER=$enable_updater", "ENABLE_UPDATE_NOTIFICATIONS=$enable_update_notifications", "USE_MINIKIN_HYPHENATION=$use_minikin_hyphenation", "USE_THIN_LTO=$use_thin_lto", @@ -398,8 +397,6 @@ "dips/dips_database.h", "dips/dips_features.cc", "dips/dips_features.h", - "dips/dips_helper.cc", - "dips/dips_helper.h", "dips/dips_service.cc", "dips/dips_service.h", "dips/dips_service_factory.cc", @@ -3131,8 +3128,6 @@ "password_manager/android/credential_android.h", "password_manager/android/credential_leak_controller_android.cc", "password_manager/android/credential_leak_controller_android.h", - "password_manager/android/generated_password_saved_infobar_delegate_android.cc", - "password_manager/android/generated_password_saved_infobar_delegate_android.h", "password_manager/android/generated_password_saved_message_delegate.cc", "password_manager/android/generated_password_saved_message_delegate.h", "password_manager/android/password_accessory_controller.h", @@ -3153,8 +3148,6 @@ "password_manager/android/password_manager_error_message_helper_bridge.h", "password_manager/android/password_manager_error_message_helper_bridge_impl.cc", "password_manager/android/password_manager_error_message_helper_bridge_impl.h", - "password_manager/android/password_manager_infobar_delegate_android.cc", - "password_manager/android/password_manager_infobar_delegate_android.h", "password_manager/android/password_manager_launcher_android.cc", "password_manager/android/password_manager_launcher_android.h", "password_manager/android/password_scripts_fetcher_android.cc", @@ -3162,12 +3155,8 @@ "password_manager/android/password_store_bridge.h", "password_manager/android/password_ui_view_android.cc", "password_manager/android/password_ui_view_android.h", - "password_manager/android/save_password_infobar_delegate_android.cc", - "password_manager/android/save_password_infobar_delegate_android.h", "password_manager/android/save_update_password_message_delegate.cc", "password_manager/android/save_update_password_message_delegate.h", - "password_manager/android/update_password_infobar_delegate_android.cc", - "password_manager/android/update_password_infobar_delegate_android.h", "payments/android/service_worker_payment_app_bridge.cc", "permissions/notification_blocked_dialog_controller_android.cc", "permissions/notification_blocked_dialog_controller_android.h",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index b0b905e..915481de 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3305,6 +3305,21 @@ std::size(kFastCheckoutConsentlessExecution), nullptr}}; #endif // BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(IS_CHROMEOS_ASH) +const FeatureEntry::FeatureParam kGalleryAppPdfEditNotificationEditAndSign[] = { + {"text", "Edit and Sign"}}; +const FeatureEntry::FeatureParam + kGalleryAppPdfEditNotificationOpenWithGalleryApp[] = { + {"text", "Open with Gallery app"}}; +const FeatureEntry::FeatureVariation + kGalleryAppPdfEditNotificationVariations[] = { + {"Edit and Sign", kGalleryAppPdfEditNotificationEditAndSign, + std::size(kGalleryAppPdfEditNotificationEditAndSign), nullptr}, + {"Open with Gallery app", + kGalleryAppPdfEditNotificationOpenWithGalleryApp, + std::size(kGalleryAppPdfEditNotificationOpenWithGalleryApp), nullptr}}; +#endif + // RECORDING USER METRICS FOR FLAGS: // ----------------------------------------------------------------------------- // The first line of the entry is the internal name. @@ -3798,10 +3813,6 @@ kOsCrOS, FEATURE_VALUE_TYPE(features::kNewShortcutMapping), }, - {"improved-desks-keyboard-shortcuts", - flag_descriptions::kImprovedDesksKeyboardShortcutsName, - flag_descriptions::kImprovedDesksKeyboardShortcutsDescription, kOsCrOS, - FEATURE_VALUE_TYPE(ash::features::kImprovedDesksKeyboardShortcuts)}, {"improved-keyboard-shortcuts", flag_descriptions::kImprovedKeyboardShortcutsName, flag_descriptions::kImprovedKeyboardShortcutsDescription, kOsCrOS, @@ -4854,20 +4865,10 @@ flag_descriptions::kCrosOnDeviceGrammarCheckName, flag_descriptions::kCrosOnDeviceGrammarCheckDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kOnDeviceGrammarCheck)}, - {"enable-cros-system-chinese-physical-typing", - flag_descriptions::kSystemChinesePhysicalTypingName, - flag_descriptions::kSystemChinesePhysicalTypingDescription, kOsCrOS, - FEATURE_VALUE_TYPE(chromeos::features::kSystemChinesePhysicalTyping)}, {"enable-cros-system-japanese-physical-typing", flag_descriptions::kSystemJapanesePhysicalTypingName, flag_descriptions::kSystemJapanesePhysicalTypingDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kSystemJapanesePhysicalTyping)}, - {"enable-cros-system-transliteration-physical-typing", - flag_descriptions::kSystemTransliterationPhysicalTypingName, - flag_descriptions::kSystemTransliterationPhysicalTypingDescription, - kOsCrOS, - FEATURE_VALUE_TYPE( - chromeos::features::kSystemTransliterationPhysicalTyping)}, {"enable-cros-touch-text-editing-redesign", flag_descriptions::kTouchTextEditingRedesignName, flag_descriptions::kTouchTextEditingRedesignDescription, kOsCrOS, @@ -6337,6 +6338,9 @@ chrome::android::kCCTResizableForThirdParties, kCCTResizableThirdPartiesDefaultPolicyVariations, "CCTResizableThirdPartiesDefaultPolicy")}, + {"cct-resizable-side-sheet", flag_descriptions::kCCTResizableSideSheetName, + flag_descriptions::kCCTResizableSideSheetDescription, kOsAndroid, + FEATURE_VALUE_TYPE(chrome::android::kCCTResizableSideSheet)}, {"cct-retaining-state-in-memory", flag_descriptions::kCCTRetainingStateInMemoryName, flag_descriptions::kCCTRetainingStateInMemoryDescription, kOsAndroid, @@ -8526,6 +8530,13 @@ flag_descriptions::kTabAudioMutingDescription, kOsDesktop, FEATURE_VALUE_TYPE(media::kEnableTabMuting)}, +#if BUILDFLAG(IS_CHROMEOS_ASH) + {"enable-app-discovery-for-oobe", + flag_descriptions::kAppDiscoveryForOobeName, + flag_descriptions::kAppDiscoveryForOobeDescription, kOsCrOS, + FEATURE_VALUE_TYPE(features::kAppDiscoveryForOobe)}, +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + {"force-major-version-to-minor", flag_descriptions::kForceMajorVersionInMinorPositionInUserAgentName, flag_descriptions::kForceMajorVersionInMinorPositionInUserAgentDescription, @@ -9486,6 +9497,16 @@ FEATURE_VALUE_TYPE(features::kPowerBookmarksSidePanel)}, #endif +#if BUILDFLAG(IS_CHROMEOS_ASH) + {"gallery-app-pdf-edit-notification", + flag_descriptions::kGalleryAppPdfEditNotificationName, + flag_descriptions::kGalleryAppPdfEditNotificationDescription, kOsCrOS, + FEATURE_WITH_PARAMS_VALUE_TYPE( + ash::features::kGalleryAppPdfEditNotification, + kGalleryAppPdfEditNotificationVariations, + "GalleryAppPdfEditNotification")}, +#endif + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/accessibility/accessibility_ui.cc b/chrome/browser/accessibility/accessibility_ui.cc index 3e85919..4f0fcb6 100644 --- a/chrome/browser/accessibility/accessibility_ui.cc +++ b/chrome/browser/accessibility/accessibility_ui.cc
@@ -125,7 +125,7 @@ target_data.Set(kPidField, static_cast<int>(base::GetProcId(handle))); target_data.Set(kFaviconUrlField, favicon_url.spec()); target_data.Set(kAccessibilityModeField, - static_cast<int>(accessibility_mode.mode())); + static_cast<int>(accessibility_mode.flags())); target_data.Set(kTypeField, kPage); return target_data; }
diff --git a/chrome/browser/android/omnibox/autocomplete_controller_android.cc b/chrome/browser/android/omnibox/autocomplete_controller_android.cc index fc4cb646..2f67350 100644 --- a/chrome/browser/android/omnibox/autocomplete_controller_android.cc +++ b/chrome/browser/android/omnibox/autocomplete_controller_android.cc
@@ -489,8 +489,6 @@ const AutocompleteResult& autocomplete_result) { JNIEnv* env = AttachCurrentThread(); - autocomplete_controller_->SetTailSuggestContentPrefixes(); - // Get the inline-autocomplete text. std::u16string inline_autocompletion; if (auto* default_match = autocomplete_result.default_match())
diff --git a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc index 6cc17666..64e20cca4 100644 --- a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc +++ b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.cc
@@ -45,14 +45,14 @@ bool ShouldAutoDisplayUi( const std::vector<IntentPickerAppInfo>& apps_for_picker, - content::NavigationHandle* navigation_handle) { - content::WebContents* web_contents = navigation_handle->GetWebContents(); + NavigationInfo navigation_info) { + content::WebContents* web_contents = navigation_info.web_contents; if (web_contents->GetVisibility() == content::Visibility::HIDDEN) { return false; } - const GURL& url = navigation_handle->GetURL(); + const GURL& url = navigation_info.url; // Disable Auto-display in the new Intent Picker UI unless it is specifically // re-enabled. @@ -65,7 +65,7 @@ if (InAppBrowser(web_contents)) return false; - if (!ShouldOverrideUrlLoading(GetStartingGURL(navigation_handle), url)) + if (!ShouldOverrideUrlLoading(navigation_info.starting_url, url)) return false; Profile* profile = @@ -99,10 +99,10 @@ } PickerShowState GetPickerShowState( - content::NavigationHandle* navigation_handle, + NavigationInfo navigation_info, const std::vector<IntentPickerAppInfo>& apps_for_picker) { - return ShouldAutoDisplayUi(apps_for_picker, navigation_handle) && - IsNavigateFromLink(navigation_handle) + return ShouldAutoDisplayUi(apps_for_picker, navigation_info) && + navigation_info.is_navigate_from_link ? PickerShowState::kPopOut : PickerShowState::kOmnibox; } @@ -120,18 +120,18 @@ } // namespace -void MaybeShowIntentPickerBubble(content::NavigationHandle* navigation_handle, +void MaybeShowIntentPickerBubble(NavigationInfo navigation_info, std::vector<IntentPickerAppInfo> apps) { - if (apps.empty() || GetPickerShowState(navigation_handle, apps) == - PickerShowState::kOmnibox) { + if (apps.empty() || + GetPickerShowState(navigation_info, apps) == PickerShowState::kOmnibox) { return; } IntentHandlingMetrics::RecordIntentPickerIconEvent( IntentHandlingMetrics::IntentPickerIconEvent::kAutoPopOut); - content::WebContents* web_contents = navigation_handle->GetWebContents(); - const GURL& url = navigation_handle->GetURL(); + content::WebContents* web_contents = navigation_info.web_contents; + const GURL& url = navigation_info.url; IntentPickerTabHelper::LoadAppIcons( web_contents, std::move(apps),
diff --git a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h index 61b8ed0..eed1e6a 100644 --- a/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h +++ b/chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h
@@ -12,13 +12,19 @@ #include "url/gurl.h" namespace content { -class NavigationHandle; class WebContents; } // namespace content namespace apps { -void MaybeShowIntentPickerBubble(content::NavigationHandle* navigation_handle, +struct NavigationInfo { + content::WebContents* web_contents; + GURL url; + GURL starting_url; + bool is_navigate_from_link; +}; + +void MaybeShowIntentPickerBubble(NavigationInfo navigation_info, std::vector<IntentPickerAppInfo> apps); // These enums are used to define the intent picker show state, whether the
diff --git a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc index 17ab1ed..566f70b 100644 --- a/chrome/browser/apps/intent_helper/intent_picker_helpers.cc +++ b/chrome/browser/apps/intent_helper/intent_picker_helpers.cc
@@ -7,8 +7,10 @@ #include <string> #include <utility> +#include "base/functional/bind.h" #include "base/memory/weak_ptr.h" #include "base/notreached.h" +#include "base/task/task_traits.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" @@ -32,6 +34,7 @@ #include "chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h" #include "chrome/browser/apps/intent_helper/metrics/intent_handling_metrics.h" #elif BUILDFLAG(IS_MAC) +#include "base/task/thread_pool.h" #include "chrome/browser/apps/intent_helper/mac_intent_picker_helpers.h" #endif // BUILDFLAG(IS_CHROMEOS) @@ -39,9 +42,10 @@ namespace { -std::vector<IntentPickerAppInfo> FindAppsForUrl( +void AppendAppsForUrlSync( content::WebContents* web_contents, const GURL& url, + base::OnceCallback<void(std::vector<IntentPickerAppInfo>)> callback, std::vector<IntentPickerAppInfo> apps) { #if BUILDFLAG(IS_MAC) // On the Mac, if there is a Universal Link, it goes first. @@ -64,7 +68,38 @@ ui::ImageModel(), update.AppId(), update.Name()); }); } - return apps; + + std::move(callback).Run(std::move(apps)); +} + +void FindAppsForUrl( + content::WebContents* web_contents, + const GURL& url, + base::OnceCallback<void(std::vector<IntentPickerAppInfo>)> callback) { + auto append_apps = + [](base::WeakPtr<content::WebContents> web_contents, + IntentPickerTabHelper* helper, int commit_count, const GURL& url, + base::OnceCallback<void(std::vector<IntentPickerAppInfo>)> callback, + std::vector<IntentPickerAppInfo> apps) { + if (!web_contents) + return; + if (helper->commit_count() != commit_count) + return; + + AppendAppsForUrlSync(web_contents.get(), url, std::move(callback), + std::move(apps)); + }; + + // TODO(crbug.com/1236141): Move the Mac intent code to be here, called async. + + IntentPickerTabHelper* helper = + IntentPickerTabHelper::FromWebContents(web_contents); + int commit_count = helper->commit_count(); + + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce(append_apps, web_contents->GetWeakPtr(), helper, + commit_count, url, std::move(callback), + std::vector<IntentPickerAppInfo>())); } void LaunchAppFromIntentPicker(content::WebContents* web_contents, @@ -138,43 +173,28 @@ base::BindOnce(&OnIntentPickerClosed, web_contents->GetWeakPtr(), url)); } -std::vector<IntentPickerAppInfo> GetAppsForIntentPicker( - content::WebContents* web_contents) { - std::vector<IntentPickerAppInfo> apps = {}; - if (!ShouldCheckAppsForUrl(web_contents)) - return apps; +void GetAppsForIntentPicker( + content::WebContents* web_contents, + base::OnceCallback<void(std::vector<IntentPickerAppInfo>)> callback) { + if (!ShouldCheckAppsForUrl(web_contents)) { + std::move(callback).Run({}); + return; + } Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - if (!AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) - return apps; + if (!AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) { + std::move(callback).Run({}); + return; + } - const GURL& url = web_contents->GetLastCommittedURL(); - apps = FindAppsForUrl(web_contents, url, std::move(apps)); - return apps; + FindAppsForUrl(web_contents, web_contents->GetLastCommittedURL(), + std::move(callback)); } -} // namespace - -// for chromeos, this should apply when navigation is not deferred for pwa only -// case also when navigation deferred and then resumed -void MaybeShowIntentPicker(content::NavigationHandle* navigation_handle) { - content::WebContents* web_contents = navigation_handle->GetWebContents(); - auto apps = GetAppsForIntentPicker(web_contents); - IntentPickerTabHelper::FromWebContents(web_contents)->ShowIconForApps(apps); -#if BUILDFLAG(IS_CHROMEOS) - MaybeShowIntentPickerBubble(navigation_handle, std::move(apps)); -#endif // BUILDFLAG(IS_CHROMEOS) -} - -void MaybeShowIntentPicker(content::WebContents* web_contents) { - IntentPickerTabHelper::FromWebContents(web_contents) - ->ShowIconForApps(GetAppsForIntentPicker(web_contents)); -} - -void ShowIntentPickerOrLaunchApp(content::WebContents* web_contents, - const GURL& url) { - std::vector<IntentPickerAppInfo> apps = FindAppsForUrl(web_contents, url, {}); +void ShowIntentPickerOrLaunchAppImpl(content::WebContents* web_contents, + const GURL& url, + std::vector<IntentPickerAppInfo> apps) { if (apps.empty()) return; @@ -210,6 +230,75 @@ base::BindOnce(&OnAppIconsLoaded, web_contents, url)); } +} // namespace + +void MaybeShowIntentPicker(content::NavigationHandle* navigation_handle) { + content::WebContents* web_contents = navigation_handle->GetWebContents(); + IntentPickerTabHelper* helper = + IntentPickerTabHelper::FromWebContents(web_contents); + int commit_count = helper->commit_count(); + + auto task = [](base::WeakPtr<content::WebContents> web_contents, +#if BUILDFLAG(IS_CHROMEOS) + NavigationInfo navigation_info, +#endif // BUILDFLAG(IS_CHROMEOS) + IntentPickerTabHelper* helper, int commit_count, + std::vector<IntentPickerAppInfo> apps) { + if (!web_contents) + return; + if (helper->commit_count() != commit_count) + return; + + helper->ShowIconForApps(apps); +#if BUILDFLAG(IS_CHROMEOS) + MaybeShowIntentPickerBubble(navigation_info, std::move(apps)); +#endif // BUILDFLAG(IS_CHROMEOS) + }; + +#if BUILDFLAG(IS_CHROMEOS) + NavigationInfo navigation_info = { + .web_contents = web_contents, + .url = navigation_handle->GetURL(), + .starting_url = GetStartingGURL(navigation_handle), + .is_navigate_from_link = IsNavigateFromLink(navigation_handle)}; +#endif // BUILDFLAG(IS_CHROMEOS) + + GetAppsForIntentPicker(web_contents, + base::BindOnce(task, web_contents->GetWeakPtr(), +#if BUILDFLAG(IS_CHROMEOS) + navigation_info, +#endif // BUILDFLAG(IS_CHROMEOS) + helper, commit_count)); +} + +void MaybeShowIntentPicker(content::WebContents* web_contents) { + IntentPickerTabHelper* helper = + IntentPickerTabHelper::FromWebContents(web_contents); + int commit_count = helper->commit_count(); + + auto task = [](base::WeakPtr<content::WebContents> web_contents, + IntentPickerTabHelper* helper, int commit_count, + std::vector<IntentPickerAppInfo> apps) { + if (!web_contents) + return; + if (helper->commit_count() != commit_count) + return; + + helper->ShowIconForApps(apps); + }; + + GetAppsForIntentPicker( + web_contents, + base::BindOnce(task, web_contents->GetWeakPtr(), helper, commit_count)); +} + +void ShowIntentPickerOrLaunchApp(content::WebContents* web_contents, + const GURL& url) { + FindAppsForUrl( + web_contents, url, + base::BindOnce(&ShowIntentPickerOrLaunchAppImpl, web_contents, url)); +} + bool IntentPickerPwaPersistenceEnabled() { #if BUILDFLAG(IS_CHROMEOS) return true;
diff --git a/chrome/browser/ash/BUILD.gn b/chrome/browser/ash/BUILD.gn index 4380dd3..ca3e8c940 100644 --- a/chrome/browser/ash/BUILD.gn +++ b/chrome/browser/ash/BUILD.gn
@@ -2378,6 +2378,10 @@ "policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.cc", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.cc", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.cc", + "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h", "policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h", "policy/reporting/metrics_reporting/cros_reporting_settings.cc", "policy/reporting/metrics_reporting/cros_reporting_settings.h",
diff --git a/chrome/browser/ash/bruschetta/bruschetta_mount_provider.cc b/chrome/browser/ash/bruschetta/bruschetta_mount_provider.cc index 6f7eff4..3a75d6e 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_mount_provider.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_mount_provider.cc
@@ -47,9 +47,13 @@ void BruschettaMountProvider::Prepare(PrepareCallback callback) { auto* service = BruschettaService::GetForProfile(profile_); auto launcher = service->GetLauncher(guest_id_.vm_name); - launcher->EnsureRunning(base::BindOnce(&BruschettaMountProvider::OnRunning, - weak_ptr_factory_.GetWeakPtr(), - std::move(callback))); + if (launcher) { + launcher->EnsureRunning(base::BindOnce(&BruschettaMountProvider::OnRunning, + weak_ptr_factory_.GetWeakPtr(), + std::move(callback))); + } else { + std::move(callback).Run(false, {}, {}, {}); + } } void BruschettaMountProvider::OnRunning(PrepareCallback callback,
diff --git a/chrome/browser/ash/bruschetta/bruschetta_service.cc b/chrome/browser/ash/bruschetta/bruschetta_service.cc index b971124b..b52521b 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_service.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_service.cc
@@ -8,39 +8,68 @@ #include "ash/constants/ash_features.h" #include "base/feature_list.h" +#include "base/functional/bind.h" #include "base/memory/weak_ptr.h" #include "bruschetta_terminal_provider.h" #include "chrome/browser/ash/bruschetta/bruschetta_features.h" #include "chrome/browser/ash/bruschetta/bruschetta_launcher.h" #include "chrome/browser/ash/bruschetta/bruschetta_mount_provider.h" +#include "chrome/browser/ash/bruschetta/bruschetta_pref_names.h" #include "chrome/browser/ash/bruschetta/bruschetta_service_factory.h" #include "chrome/browser/ash/bruschetta/bruschetta_util.h" +#include "chrome/browser/ash/guest_os/guest_id.h" +#include "chrome/browser/ash/guest_os/guest_os_pref_names.h" #include "chrome/browser/ash/guest_os/public/guest_os_service.h" #include "chrome/browser/ash/guest_os/public/types.h" +#include "components/prefs/pref_service.h" namespace bruschetta { +BruschettaService::VmRegistration::VmRegistration( + std::unique_ptr<BruschettaLauncher> launcher, + guest_os::GuestOsMountProviderRegistry::Id mount_id) + : launcher(std::move(launcher)), mount_id(mount_id) {} + +BruschettaService::VmRegistration::VmRegistration(VmRegistration&&) = default; +BruschettaService::VmRegistration& BruschettaService::VmRegistration::operator=( + BruschettaService::VmRegistration&&) = default; +BruschettaService::VmRegistration::~VmRegistration() = default; + BruschettaService::BruschettaService(Profile* profile) : profile_(profile) { // Don't set up anything if the bruschetta flag isn't enabled. if (!BruschettaFeatures::Get()->IsEnabled()) return; + pref_observer_.Init(profile_->GetPrefs()); + pref_observer_.Add( + prefs::kBruschettaVMConfiguration, + base::BindRepeating(&BruschettaService::OnPolicyChanged, + // Safety: `pref_observer_` owns this callback and is + // destroyed before `this`. + base::Unretained(this))); + bool registered_guests = false; // Register all bruschetta instances that have already been installed. - for (const auto& guest_id : + for (auto& guest_id : guest_os::GetContainers(profile, guest_os::VmType::BRUSCHETTA)) { - Register(guest_id); + RegisterWithTerminal(std::move(guest_id)); registered_guests = true; } // Migrate VMs installed during the alpha. These will have been set up by hand // using vmc so chrome doesn't know about this, but we know what the VM name // should be, so register it here is nothing has been registered from prefs - // and the migration flag is turned on. + // and the migration flag is turned on. Note that we do not call + // `RegisterInPrefs` because these VMs are currently outside of enterprise + // policy. if (!registered_guests && base::FeatureList::IsEnabled( chromeos::features::kBruschettaAlphaMigrate)) { - Register(GetBruschettaId()); + auto guest_id = GetBruschettaAlphaId(); + guest_os::AddContainerToPrefs(profile_, guest_id, {}); + RegisterWithTerminal(std::move(guest_id)); } + + OnPolicyChanged(); } BruschettaService::~BruschettaService() = default; @@ -49,31 +78,97 @@ return BruschettaServiceFactory::GetForProfile(profile); } -void BruschettaService::Register(const guest_os::GuestId& guest_id) { - launchers_.insert({guest_id.vm_name, std::make_unique<BruschettaLauncher>( - guest_id.vm_name, profile_)}); +void BruschettaService::OnPolicyChanged() { + for (auto& guest_id : + guest_os::GetContainers(profile_, guest_os::VmType::BRUSCHETTA)) { + const base::Value* config_id_value = GetContainerPrefValue( + profile_, guest_id, guest_os::prefs::kBruschettaConfigId); + if (!config_id_value) { + // Alpha VM, ignore policy + AllowLaunch(std::move(guest_id)); + continue; + } + + const std::string& config_id = config_id_value->GetString(); + absl::optional<const base::Value::Dict*> config = + GetRunnableConfig(profile_, config_id); + if (!config.has_value()) { + // config is either unset or explicitly blocked from running. + BlockLaunch(std::move(guest_id)); + continue; + } + + AllowLaunch(std::move(guest_id)); + } +} + +void BruschettaService::AllowLaunch(guest_os::GuestId guest_id) { + if (runnable_vms_.contains(guest_id.vm_name)) { + // Already runnable, do nothing. + return; + } + + std::string vm_name = guest_id.vm_name; + + auto launcher = + std::make_unique<BruschettaLauncher>(guest_id.vm_name, profile_); + auto mount_id = guest_os::GuestOsService::GetForProfile(profile_) + ->MountProviderRegistry() + ->Register(std::make_unique<BruschettaMountProvider>( + profile_, std::move(guest_id))); + + runnable_vms_.insert( + {std::move(vm_name), VmRegistration{std::move(launcher), mount_id}}); +} + +void BruschettaService::BlockLaunch(guest_os::GuestId guest_id) { + auto it = runnable_vms_.find(guest_id.vm_name); + if (it == runnable_vms_.end()) { + // Already blocked, do nothing. + return; + } + guest_os::GuestOsService::GetForProfile(profile_) ->MountProviderRegistry() - ->Register(std::make_unique<BruschettaMountProvider>(profile_, guest_id)); + ->Unregister(it->second.mount_id); + + runnable_vms_.erase(it); +} + +void BruschettaService::RegisterInPrefs(const guest_os::GuestId& guest_id, + const std::string& config_id) { + base::Value::Dict properties; + properties.Set(guest_os::prefs::kBruschettaConfigId, config_id); + guest_os::AddContainerToPrefs(profile_, guest_id, std::move(properties)); + + RegisterWithTerminal(guest_id); + + if (GetRunnableConfig(profile_, config_id).has_value()) { + AllowLaunch(guest_id); + } +} + +void BruschettaService::RegisterWithTerminal(guest_os::GuestId guest_id) { guest_os::GuestOsService::GetForProfile(profile_) ->TerminalProviderRegistry() - ->Register( - std::make_unique<BruschettaTerminalProvider>(profile_, guest_id)); + ->Register(std::make_unique<BruschettaTerminalProvider>( + profile_, std::move(guest_id))); } base::WeakPtr<BruschettaLauncher> BruschettaService::GetLauncher( std::string vm_name) { - auto it = launchers_.find(vm_name); - if (it == launchers_.end()) { + auto it = runnable_vms_.find(vm_name); + if (it == runnable_vms_.end()) { return nullptr; } - return it->second->GetWeakPtr(); + return it->second.launcher->GetWeakPtr(); } void BruschettaService::SetLauncherForTesting( std::string vm_name, std::unique_ptr<BruschettaLauncher> launcher) { - launchers_.insert({vm_name, std::move(launcher)}); + runnable_vms_.insert( + {std::move(vm_name), VmRegistration{std::move(launcher), -1}}); } } // namespace bruschetta
diff --git a/chrome/browser/ash/bruschetta/bruschetta_service.h b/chrome/browser/ash/bruschetta/bruschetta_service.h index fe204bfed..4e27ded 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_service.h +++ b/chrome/browser/ash/bruschetta/bruschetta_service.h
@@ -8,7 +8,9 @@ #include "base/containers/flat_map.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ash/guest_os/guest_id.h" +#include "chrome/browser/ash/guest_os/public/guest_os_mount_provider_registry.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/prefs/pref_change_registrar.h" class Profile; @@ -27,10 +29,13 @@ // Helper method to get the service instance for the given profile. static BruschettaService* GetForProfile(Profile* profile); - // Register a bruschetta instance with the GuestOS service. This is called at - // service construction for all installed instances, and from the installer - // for new instances. - void Register(const guest_os::GuestId& guest_id); + // Register an existing bruschetta instance with the terminal app. + void RegisterWithTerminal(guest_os::GuestId guest_id); + + // Register a new bruschetta instance in prefs. `config_id` controls which + // enterprise policy manages this instance. + void RegisterInPrefs(const guest_os::GuestId& guest_id, + const std::string& config_id); // Returns a handle to the launcher for the vm specified by `vm_name`. Will // return a null pointer if the name isn't recognised. @@ -40,7 +45,28 @@ std::unique_ptr<BruschettaLauncher> launcher); private: - base::flat_map<std::string, std::unique_ptr<BruschettaLauncher>> launchers_; + struct VmRegistration { + std::unique_ptr<BruschettaLauncher> launcher; + guest_os::GuestOsMountProviderRegistry::Id mount_id; + // We don't track the terminal registration because that should remain in + // place even if the VM is blocked from launching. + + VmRegistration(std::unique_ptr<BruschettaLauncher>, + guest_os::GuestOsMountProviderRegistry::Id); + VmRegistration(VmRegistration&&); + VmRegistration& operator=(VmRegistration&&); + VmRegistration(const VmRegistration&) = delete; + VmRegistration& operator=(const VmRegistration&) = delete; + ~VmRegistration(); + }; + + void OnPolicyChanged(); + void AllowLaunch(guest_os::GuestId guest_id); + void BlockLaunch(guest_os::GuestId guest_id); + + base::flat_map<std::string, VmRegistration> runnable_vms_; + + PrefChangeRegistrar pref_observer_; Profile* const profile_; };
diff --git a/chrome/browser/ash/bruschetta/bruschetta_service_unittest.cc b/chrome/browser/ash/bruschetta/bruschetta_service_unittest.cc index 66c0e084..2edb7c7 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_service_unittest.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_service_unittest.cc
@@ -5,14 +5,21 @@ #include "chrome/browser/ash/bruschetta/bruschetta_service.h" #include "ash/constants/ash_features.h" #include "base/test/scoped_feature_list.h" +#include "chrome/browser/ash/bruschetta/bruschetta_pref_names.h" #include "chrome/browser/ash/bruschetta/bruschetta_util.h" #include "chrome/test/base/testing_profile.h" +#include "components/prefs/pref_service.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace bruschetta { +namespace { +const char kTestVmName[] = "vm_name"; +const char kTestVmConfig[] = "vm_config"; +} // namespace + class BruschettaServiceTest : public testing::Test { public: BruschettaServiceTest() = default; @@ -22,27 +29,58 @@ protected: void SetUp() override { - feature_list_.InitAndEnableFeature(ash::features::kBruschetta); + feature_list_.InitWithFeatures( + {ash::features::kBruschetta, ash::features::kBruschettaAlphaMigrate}, + {}); service_ = std::make_unique<BruschettaService>(&profile_); } void TearDown() override {} + void EnableByPolicy() { + base::Value::Dict pref; + base::Value::Dict config; + config.Set(prefs::kPolicyEnabledKey, + static_cast<int>(prefs::PolicyEnabledState::RUN_ALLOWED)); + + pref.Set(kTestVmConfig, std::move(config)); + profile_.GetPrefs()->SetDict(prefs::kBruschettaVMConfiguration, + std::move(pref)); + } + + void DisableByPolicy() { + profile_.GetPrefs()->ClearPref(prefs::kBruschettaVMConfiguration); + } + base::test::ScopedFeatureList feature_list_; content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; std::unique_ptr<BruschettaService> service_; }; -// GetLauncher returns launcher. -TEST_F(BruschettaServiceTest, GetLauncher) { - service_->Register(GetBruschettaId()); +TEST_F(BruschettaServiceTest, GetLauncherForMigratedVm) { ASSERT_NE(service_->GetLauncher("bru"), nullptr); } -// GetLauncher returns null for unknown vm. -TEST_F(BruschettaServiceTest, GetLauncherNullForUnknown) { - ASSERT_EQ(service_->GetLauncher("noname"), nullptr); +TEST_F(BruschettaServiceTest, GetLauncherPolicyEnabled) { + EnableByPolicy(); + service_->RegisterInPrefs(MakeBruschettaId(kTestVmName), kTestVmConfig); + ASSERT_NE(service_->GetLauncher(kTestVmName), nullptr); +} + +TEST_F(BruschettaServiceTest, GetLauncherPolicyDisabled) { + DisableByPolicy(); + service_->RegisterInPrefs(MakeBruschettaId(kTestVmName), kTestVmConfig); + ASSERT_EQ(service_->GetLauncher(kTestVmName), nullptr); +} + +TEST_F(BruschettaServiceTest, GetLauncherPolicyUpdate) { + EnableByPolicy(); + service_->RegisterInPrefs(MakeBruschettaId(kTestVmName), kTestVmConfig); + DisableByPolicy(); + ASSERT_EQ(service_->GetLauncher(kTestVmName), nullptr); + EnableByPolicy(); + ASSERT_NE(service_->GetLauncher(kTestVmName), nullptr); } } // namespace bruschetta
diff --git a/chrome/browser/ash/bruschetta/bruschetta_terminal_provider.cc b/chrome/browser/ash/bruschetta/bruschetta_terminal_provider.cc index 2b3dcc9..0cfd756 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_terminal_provider.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_terminal_provider.cc
@@ -55,20 +55,28 @@ startup_status->printer()->PrintStage( 1, l10n_util::GetStringUTF8(IDS_CROSTINI_TERMINAL_STATUS_START_TERMINA_VM)); - BruschettaService::GetForProfile(profile_) - ->GetLauncher(guest_id_.vm_name) - ->EnsureRunning(base::BindOnce( - [](base::OnceCallback<void(bool, std::string)> callback, - BruschettaResult result) { - bool success = (result == BruschettaResult::kSuccess); - std::move(callback).Run( - success, - success ? "" - : base::StringPrintf( - "Error starting bruschetta for terminal: %d (%s)", - result, BruschettaResultString(result))); - }, - std::move(callback))); + auto launcher = BruschettaService::GetForProfile(profile_)->GetLauncher( + guest_id_.vm_name); + + if (launcher) { + launcher->EnsureRunning(base::BindOnce( + [](base::OnceCallback<void(bool, std::string)> callback, + BruschettaResult result) { + bool success = (result == BruschettaResult::kSuccess); + std::move(callback).Run( + success, + success ? "" + : base::StringPrintf( + "Error starting bruschetta for terminal: %d (%s)", + result, BruschettaResultString(result))); + }, + std::move(callback))); + } else { + std::move(callback).Run( + false, + base::StringPrintf("Bruschetta VM %s unknown or disabled by policy", + guest_id_.vm_name.c_str())); + } } } // namespace bruschetta
diff --git a/chrome/browser/ash/bruschetta/bruschetta_util.cc b/chrome/browser/ash/bruschetta/bruschetta_util.cc index 89a21a6..12057a2 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_util.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_util.cc
@@ -4,8 +4,29 @@ #include "chrome/browser/ash/bruschetta/bruschetta_util.h" +#include "chrome/browser/ash/bruschetta/bruschetta_pref_names.h" +#include "chrome/browser/profiles/profile.h" +#include "components/prefs/pref_service.h" + namespace bruschetta { +namespace { +absl::optional<const base::Value::Dict*> GetConfigWithEnabledLevel( + const Profile* profile, + const std::string& config_id, + prefs::PolicyEnabledState enabled_level) { + const auto* config_ptr = profile->GetPrefs() + ->GetDict(prefs::kBruschettaVMConfiguration) + .FindDict(config_id); + if (!config_ptr || config_ptr->FindInt(prefs::kPolicyEnabledKey) < + static_cast<int>(enabled_level)) { + return absl::nullopt; + } + + return config_ptr; +} +} // namespace + const char kBruschettaVmName[] = "bru"; const char kBruschettaDisplayName[] = "Bruschetta"; @@ -25,9 +46,20 @@ return "unknown code"; } -guest_os::GuestId GetBruschettaId() { - return guest_os::GuestId{guest_os::VmType::BRUSCHETTA, kBruschettaVmName, +guest_os::GuestId GetBruschettaAlphaId() { + return MakeBruschettaId(kBruschettaVmName); +} + +guest_os::GuestId MakeBruschettaId(std::string vm_name) { + return guest_os::GuestId{guest_os::VmType::BRUSCHETTA, std::move(vm_name), "penguin"}; } +absl::optional<const base::Value::Dict*> GetRunnableConfig( + const Profile* profile, + const std::string& config_id) { + return GetConfigWithEnabledLevel(profile, config_id, + prefs::PolicyEnabledState::RUN_ALLOWED); +} + } // namespace bruschetta
diff --git a/chrome/browser/ash/bruschetta/bruschetta_util.h b/chrome/browser/ash/bruschetta/bruschetta_util.h index 1517f05b..a1bf470 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_util.h +++ b/chrome/browser/ash/bruschetta/bruschetta_util.h
@@ -7,6 +7,8 @@ #include "chrome/browser/ash/guest_os/guest_id.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + namespace bruschetta { extern const char kBruschettaVmName[]; @@ -24,7 +26,13 @@ // Returns the string name of the BruschettaResult. const char* BruschettaResultString(const BruschettaResult res); -guest_os::GuestId GetBruschettaId(); +guest_os::GuestId GetBruschettaAlphaId(); + +guest_os::GuestId MakeBruschettaId(std::string vm_name); + +absl::optional<const base::Value::Dict*> GetRunnableConfig( + const Profile* profile, + const std::string& config_id); } // namespace bruschetta
diff --git a/chrome/browser/ash/dbus/fusebox_service_provider.cc b/chrome/browser/ash/dbus/fusebox_service_provider.cc index 33ba43b..f58a42e 100644 --- a/chrome/browser/ash/dbus/fusebox_service_provider.cc +++ b/chrome/browser/ash/dbus/fusebox_service_provider.cc
@@ -31,6 +31,21 @@ << method_name; } +template <typename T> +void ReplyToProtoMethod(dbus::MethodCall* method_call, + dbus::ExportedObject::ResponseSender sender, + const T& proto) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + std::unique_ptr<dbus::Response> response = + dbus::Response::FromMethodCall(method_call); + dbus::MessageWriter writer(response.get()); + + writer.AppendProtoAsArrayOfBytes(proto); + + std::move(sender).Run(std::move(response)); +} + void ReplyToClose(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender, int32_t posix_error_code) { @@ -45,34 +60,6 @@ std::move(sender).Run(std::move(response)); } -void ReplyToClose2(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox_staging::Close2ResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - -void ReplyToMkDir(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox_staging::MkDirResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - void ReplyToOpen(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender, int32_t posix_error_code) { @@ -89,20 +76,6 @@ std::move(sender).Run(std::move(response)); } -void ReplyToOpen2(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox_staging::Open2ResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - void ReplyToRead(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender, int32_t posix_error_code, @@ -120,48 +93,6 @@ std::move(sender).Run(std::move(response)); } -void ReplyToRead2(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox_staging::Read2ResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - -void ReplyToReadDir2(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox::ReadDir2ResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - -void ReplyToRmDir(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox_staging::RmDirResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - void ReplyToStat(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender, int32_t posix_error_code, @@ -188,21 +119,6 @@ std::move(sender).Run(std::move(response)); } -void ReplyToListStorages( - dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender, - const fusebox::ListStoragesResponseProto& response_proto) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<dbus::Response> response = - dbus::Response::FromMethodCall(method_call); - dbus::MessageWriter writer(response.get()); - - writer.AppendProtoAsArrayOfBytes(response_proto); - - std::move(sender).Run(std::move(response)); -} - } // namespace FuseBoxServiceProvider::FuseBoxServiceProvider() : server_(this) {} @@ -220,6 +136,11 @@ base::BindRepeating(&FuseBoxServiceProvider::Close2, weak_ptr_factory_.GetWeakPtr()), base::BindOnce(&OnExportedCallback)); + object->ExportMethod(fusebox::kFuseBoxServiceInterface, + fusebox::kCreateMethod, + base::BindRepeating(&FuseBoxServiceProvider::Create, + weak_ptr_factory_.GetWeakPtr()), + base::BindOnce(&OnExportedCallback)); object->ExportMethod(fusebox::kFuseBoxServiceInterface, fusebox::kMkDirMethod, base::BindRepeating(&FuseBoxServiceProvider::MkDir, weak_ptr_factory_.GetWeakPtr()), @@ -311,12 +232,34 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox_staging::Close2ResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToClose2(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.Close2(request_proto, base::BindOnce(&ReplyToClose2, method_call, - std::move(sender))); + server_.Close2( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::Close2ResponseProto>, + method_call, std::move(sender))); +} + +void FuseBoxServiceProvider::Create( + dbus::MethodCall* method_call, + dbus::ExportedObject::ResponseSender sender) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + dbus::MessageReader reader(method_call); + fusebox_staging::CreateRequestProto request_proto; + if (!reader.PopArrayOfBytesAsProto(&request_proto)) { + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_posix_error_code(EINVAL); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); + return; + } + + server_.Create( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::CreateResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::MkDir( @@ -329,12 +272,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox_staging::MkDirResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToMkDir(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.MkDir(request_proto, - base::BindOnce(&ReplyToMkDir, method_call, std::move(sender))); + server_.MkDir( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::MkDirResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::Open(dbus::MethodCall* method_call, @@ -362,12 +307,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox_staging::Open2ResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToOpen2(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.Open2(request_proto, - base::BindOnce(&ReplyToOpen2, method_call, std::move(sender))); + server_.Open2( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::Open2ResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::Read(dbus::MethodCall* method_call, @@ -398,12 +345,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox_staging::Read2ResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToRead2(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.Read2(request_proto, - base::BindOnce(&ReplyToRead2, method_call, std::move(sender))); + server_.Read2( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::Read2ResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::ReadDir2( @@ -416,12 +365,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox::ReadDir2ResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToReadDir2(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.ReadDir2(request_proto, base::BindOnce(&ReplyToReadDir2, method_call, - std::move(sender))); + server_.ReadDir2( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox::ReadDir2ResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::RmDir( @@ -434,12 +385,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox_staging::RmDirResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToRmDir(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } - server_.RmDir(request_proto, - base::BindOnce(&ReplyToRmDir, method_call, std::move(sender))); + server_.RmDir( + request_proto, + base::BindOnce(&ReplyToProtoMethod<fusebox_staging::RmDirResponseProto>, + method_call, std::move(sender))); } void FuseBoxServiceProvider::Stat(dbus::MethodCall* method_call, @@ -468,13 +421,14 @@ if (!reader.PopArrayOfBytesAsProto(&request_proto)) { fusebox::ListStoragesResponseProto response_proto; response_proto.set_posix_error_code(EINVAL); - ReplyToListStorages(method_call, std::move(sender), response_proto); + ReplyToProtoMethod(method_call, std::move(sender), response_proto); return; } server_.ListStorages( request_proto, - base::BindOnce(&ReplyToListStorages, method_call, std::move(sender))); + base::BindOnce(&ReplyToProtoMethod<fusebox::ListStoragesResponseProto>, + method_call, std::move(sender))); } } // namespace ash
diff --git a/chrome/browser/ash/dbus/fusebox_service_provider.h b/chrome/browser/ash/dbus/fusebox_service_provider.h index 3bcc366..ed85cb9f 100644 --- a/chrome/browser/ash/dbus/fusebox_service_provider.h +++ b/chrome/browser/ash/dbus/fusebox_service_provider.h
@@ -40,6 +40,8 @@ dbus::ExportedObject::ResponseSender sender); void Close2(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender); + void Create(dbus::MethodCall* method_call, + dbus::ExportedObject::ResponseSender sender); void MkDir(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender); void Open(dbus::MethodCall* method_call,
diff --git a/chrome/browser/ash/extensions/file_manager/system_notification_manager.cc b/chrome/browser/ash/extensions/file_manager/system_notification_manager.cc index 8fdc1d1..621dd0f 100644 --- a/chrome/browser/ash/extensions/file_manager/system_notification_manager.cc +++ b/chrome/browser/ash/extensions/file_manager/system_notification_manager.cc
@@ -138,7 +138,7 @@ message_center::NOTIFICATION_TYPE_SIMPLE, notification_id, title, message, l10n_util::GetStringUTF16(IDS_FILEMANAGER_APP_NAME), GURL(), message_center::NotifierId(), message_center::RichNotificationData(), - delegate, ash::kFilesAppIcon, + delegate, ash::kFolderIcon, message_center::SystemNotificationWarningLevel::NORMAL); } @@ -226,8 +226,7 @@ base::MakeRefCounted<message_center::HandleNotificationClickDelegate>( base::BindRepeating(&SystemNotificationManager::HandleProgressClick, weak_ptr_factory_.GetWeakPtr(), notification_id)), - ash::kFilesAppIcon, - message_center::SystemNotificationWarningLevel::NORMAL); + ash::kFolderIcon, message_center::SystemNotificationWarningLevel::NORMAL); } std::unique_ptr<message_center::Notification> @@ -248,8 +247,7 @@ base::BindRepeating(&SystemNotificationManager::CancelTaskId, weak_ptr_factory_.GetWeakPtr(), task_id, notification_id)), - ash::kFilesAppIcon, - message_center::SystemNotificationWarningLevel::NORMAL); + ash::kFolderIcon, message_center::SystemNotificationWarningLevel::NORMAL); // Add the cancel button: notification->set_buttons({message_center::ButtonInfo(
diff --git a/chrome/browser/ash/fusebox/fusebox_server.cc b/chrome/browser/ash/fusebox/fusebox_server.cc index 61d45537..92ac1ca 100644 --- a/chrome/browser/ash/fusebox/fusebox_server.cc +++ b/chrome/browser/ash/fusebox/fusebox_server.cc
@@ -163,6 +163,74 @@ // looks unused, but we need to keep the storage::FileSystemContext reference // alive until the callbacks are run. +void RunCreateAndThenStatCallback( + Server::CreateCallback callback, + scoped_refptr<storage::FileSystemContext> fs_context, // See § above. + bool read_only, + uint64_t fuse_handle, + base::OnceClosure on_failure, + base::File::Error error_code, + const base::File::Info& info) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + int posix_error_code = FileErrorToErrno(error_code); + if (posix_error_code) { + std::move(on_failure).Run(); + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_posix_error_code(posix_error_code); + std::move(callback).Run(response_proto); + return; + } + + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_fuse_handle(fuse_handle); + fusebox_staging::DirEntryProto* stat = response_proto.mutable_stat(); + stat->set_mode_bits(Server::MakeModeBits(info.is_directory, read_only)); + stat->set_size(info.size); + stat->set_mtime( + info.last_modified.ToDeltaSinceWindowsEpoch().InMicroseconds()); + std::move(callback).Run(response_proto); +} + +void RunCreateCallback( + Server::CreateCallback callback, + scoped_refptr<storage::FileSystemContext> fs_context, // See § above. + storage::FileSystemURL fs_url, + bool read_only, + uint64_t fuse_handle, + base::OnceClosure on_failure, + base::File::Error error_code) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + int posix_error_code = FileErrorToErrno(error_code); + if (posix_error_code) { + std::move(on_failure).Run(); + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_posix_error_code(posix_error_code); + std::move(callback).Run(response_proto); + return; + } + + constexpr auto metadata_fields = + storage::FileSystemOperation::GET_METADATA_FIELD_IS_DIRECTORY | + storage::FileSystemOperation::GET_METADATA_FIELD_SIZE | + storage::FileSystemOperation::GET_METADATA_FIELD_LAST_MODIFIED; + + auto outer_callback = base::BindPostTask( + base::SequencedTaskRunnerHandle::Get(), + base::BindOnce(&RunCreateAndThenStatCallback, std::move(callback), + fs_context, read_only, fuse_handle, + std::move(on_failure))); + + content::GetIOThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce( + base::IgnoreResult(&storage::FileSystemOperationRunner::GetMetadata), + // Unretained is safe: fs_context owns its operation_runner. + base::Unretained(fs_context->operation_runner()), fs_url, + metadata_fields, std::move(outer_callback))); +} + void RunMkDirAndThenStatCallback( Server::MkDirCallback callback, scoped_refptr<storage::FileSystemContext> fs_context, // See § above. @@ -634,6 +702,52 @@ } } +void Server::Create(const fusebox_staging::CreateRequestProto& request_proto, + CreateCallback callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + std::string fs_url_as_string = request_proto.has_file_system_url() + ? request_proto.file_system_url() + : std::string(); + + auto common = ParseFileSystemURL(moniker_map_, prefix_map_, fs_url_as_string); + if (common.error_code != base::File::Error::FILE_OK) { + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_posix_error_code(FileErrorToErrno(common.error_code)); + std::move(callback).Run(response_proto); + return; + } else if (common.read_only) { + fusebox_staging::CreateResponseProto response_proto; + response_proto.set_posix_error_code(EACCES); + std::move(callback).Run(response_proto); + return; + } + + constexpr bool readable = true; + constexpr bool writable = true; + + uint64_t fuse_handle = InsertFuseFileMapEntry( + FuseFileMapEntry(common.fs_context, common.fs_url, readable, writable)); + + auto on_failure = base::BindOnce(&Server::EraseFuseFileMapEntry, + weak_ptr_factory_.GetWeakPtr(), fuse_handle); + + auto outer_callback = base::BindPostTask( + base::SequencedTaskRunnerHandle::Get(), + base::BindOnce(&RunCreateCallback, std::move(callback), common.fs_context, + common.fs_url, common.read_only, fuse_handle, + std::move(on_failure))); + + constexpr bool exclusive = true; + content::GetIOThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce( + base::IgnoreResult(&storage::FileSystemOperationRunner::CreateFile), + // Unretained is safe: context owns operation runner. + base::Unretained(common.fs_context->operation_runner()), + common.fs_url, exclusive, std::move(outer_callback))); +} + void Server::MkDir(const fusebox_staging::MkDirRequestProto& request_proto, MkDirCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -711,15 +825,9 @@ ((access_mode == fusebox_staging::AccessMode::WRITE_ONLY) || (access_mode == fusebox_staging::AccessMode::READ_WRITE)); - static uint64_t next_fuse_handle = 0; - uint64_t fuse_handle = ++next_fuse_handle; - // As the fusebox.proto comment says, "The high bit (also known as the 1<<63 - // bit) is also always zero for valid values". - DCHECK((fuse_handle >> 63) == 0); - fuse_file_map_.insert( - {fuse_handle, - FuseFileMapEntry(std::move(common.fs_context), std::move(common.fs_url), - readable, writable)}); + uint64_t fuse_handle = InsertFuseFileMapEntry( + FuseFileMapEntry(std::move(common.fs_context), std::move(common.fs_url), + readable, writable)); fusebox_staging::Open2ResponseProto response_proto; response_proto.set_fuse_handle(fuse_handle); @@ -1067,4 +1175,23 @@ } } +void Server::EraseFuseFileMapEntry(uint64_t fuse_handle) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + fuse_file_map_.erase(fuse_handle); +} + +uint64_t Server::InsertFuseFileMapEntry(FuseFileMapEntry&& entry) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + static uint64_t next_fuse_handle = 0; + uint64_t fuse_handle = ++next_fuse_handle; + // As the fusebox.proto comment says, "The high bit (also known as the 1<<63 + // bit) is also always zero for valid values". + DCHECK((fuse_handle >> 63) == 0); + + fuse_file_map_.insert({fuse_handle, std::move(entry)}); + return fuse_handle; +} + } // namespace fusebox
diff --git a/chrome/browser/ash/fusebox/fusebox_server.h b/chrome/browser/ash/fusebox/fusebox_server.h index dcf6769..fb8bf44 100644 --- a/chrome/browser/ash/fusebox/fusebox_server.h +++ b/chrome/browser/ash/fusebox/fusebox_server.h
@@ -97,6 +97,12 @@ void Close2(const fusebox_staging::Close2RequestProto& request, Close2Callback callback); + // Create creates a file (not a directory). + using CreateCallback = base::OnceCallback<void( + const fusebox_staging::CreateResponseProto& response)>; + void Create(const fusebox_staging::CreateRequestProto& request, + CreateCallback callback); + // MkDir is analogous to "/usr/bin/mkdir". using MkDirCallback = base::OnceCallback<void( const fusebox_staging::MkDirResponseProto& response)>; @@ -324,6 +330,11 @@ storage::AsyncFileUtil::EntryList entry_list, bool has_more); + // Removes the entry (if present) for the given map key. + void EraseFuseFileMapEntry(uint64_t fuse_handle); + // Returns the fuse_handle that is the map key. + uint64_t InsertFuseFileMapEntry(FuseFileMapEntry&& entry); + Delegate* delegate_; FuseFileMap fuse_file_map_; fusebox::MonikerMap moniker_map_;
diff --git a/chrome/browser/ash/fusebox/fusebox_staging.proto b/chrome/browser/ash/fusebox/fusebox_staging.proto index 37d7232..fc96038a 100644 --- a/chrome/browser/ash/fusebox/fusebox_staging.proto +++ b/chrome/browser/ash/fusebox/fusebox_staging.proto
@@ -51,6 +51,22 @@ optional int32 posix_error_code = 1; } +// Create creates and opens (in the Open2 sense) a file. It is exclusive (it +// fails if the name already exists). +// +// There are no mode_bits in the request proto, as there's no mode_bits arg to +// the storage::FileSystemOperationRunner::CreateFile method. + +message CreateRequestProto { + optional string file_system_url = 3; +} + +message CreateResponseProto { + optional int32 posix_error_code = 1; + optional uint64 fuse_handle = 2; + optional DirEntryProto stat = 3; +} + // MkDir is exclusive (it fails if the name already exists) and non-recursive // (it's plain "mkdir", not "mkdir -p"). //
diff --git a/chrome/browser/ash/guest_os/guest_id.cc b/chrome/browser/ash/guest_os/guest_id.cc index b491924..52028048c 100644 --- a/chrome/browser/ash/guest_os/guest_id.cc +++ b/chrome/browser/ash/guest_os/guest_id.cc
@@ -36,6 +36,7 @@ prefs::kTerminalSupportedKey, prefs::kTerminalLabel, prefs::kContainerSharedVmDevicesKey, + prefs::kBruschettaConfigId, }}; } // namespace
diff --git a/chrome/browser/ash/guest_os/guest_os_pref_names.cc b/chrome/browser/ash/guest_os/guest_os_pref_names.cc index fc2a4e6..9e0c2397 100644 --- a/chrome/browser/ash/guest_os/guest_os_pref_names.cc +++ b/chrome/browser/ash/guest_os/guest_os_pref_names.cc
@@ -53,6 +53,7 @@ const char kTerminalSupportedKey[] = "terminal_supported"; const char kTerminalLabel[] = "terminal_label"; const char kContainerSharedVmDevicesKey[] = "container_shared_vm_devices"; +const char kBruschettaConfigId[] = "bruschetta_config_id"; // Terminal const char kGuestOsTerminalSettings[] = "crostini.terminal_settings";
diff --git a/chrome/browser/ash/guest_os/guest_os_pref_names.h b/chrome/browser/ash/guest_os/guest_os_pref_names.h index a317438..b214b2a 100644 --- a/chrome/browser/ash/guest_os/guest_os_pref_names.h +++ b/chrome/browser/ash/guest_os/guest_os_pref_names.h
@@ -50,6 +50,7 @@ // The display name to use in the terminal. extern const char kTerminalLabel[]; extern const char kContainerSharedVmDevicesKey[]; +extern const char kBruschettaConfigId[]; // Terminal // Dictionary of terminal UI settings such as font style, colors, etc.
diff --git a/chrome/browser/ash/input_method/native_input_method_engine_observer.cc b/chrome/browser/ash/input_method/native_input_method_engine_observer.cc index b8477ef..44e327f 100644 --- a/chrome/browser/ash/input_method/native_input_method_engine_observer.cc +++ b/chrome/browser/ash/input_method/native_input_method_engine_observer.cc
@@ -574,15 +574,10 @@ } return (base::FeatureList::IsEnabled( - features::kSystemChinesePhysicalTyping) && - IsChineseEngine(engine_id)) || - (base::FeatureList::IsEnabled( features::kSystemJapanesePhysicalTyping) && IsJapaneseEngine(engine_id)) || - (base::FeatureList::IsEnabled( - features::kSystemTransliterationPhysicalTyping) && - IsTransliterationEngine(engine_id)) || - IsKoreanEngine(engine_id) || IsFstEngine(engine_id); + IsTransliterationEngine(engine_id) || IsKoreanEngine(engine_id) || + IsFstEngine(engine_id) || IsChineseEngine(engine_id); } NativeInputMethodEngineObserver::NativeInputMethodEngineObserver(
diff --git a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc index 85e42b402..5040e908 100644 --- a/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc +++ b/chrome/browser/ash/input_method/native_input_method_engine_unittest.cc
@@ -248,7 +248,6 @@ feature_list_.InitWithFeatures( /*enabled_features=*/ { - features::kSystemChinesePhysicalTyping, features::kAssistPersonalInfo, features::kAssistPersonalInfoEmail, features::kAssistPersonalInfoName,
diff --git a/chrome/browser/ash/login/demo_mode/demo_setup_controller.cc b/chrome/browser/ash/login/demo_mode/demo_setup_controller.cc index d17da20..912be0c 100644 --- a/chrome/browser/ash/login/demo_mode/demo_setup_controller.cc +++ b/chrome/browser/ash/login/demo_mode/demo_setup_controller.cc
@@ -9,6 +9,7 @@ #include "ash/components/arc/arc_util.h" #include "ash/constants/ash_features.h" +#include "ash/constants/ash_switches.h" #include "base/barrier_closure.h" #include "base/bind.h" #include "base/callback.h" @@ -427,6 +428,19 @@ // static std::string DemoSetupController::GetSubOrganizationEmail() { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + DCHECK(command_line); + + if (command_line->HasSwitch(switches::kDemoModeEnrollingUsername)) { + std::string customUser = + command_line->GetSwitchValueASCII(switches::kDemoModeEnrollingUsername); + if (!customUser.empty()) { + std::string email = customUser + "@" + policy::kDemoModeDomain; + VLOG(1) << "Enrolling into Demo Mode with user: " << email; + return email; + } + } + const std::string country = g_browser_process->local_state()->GetString(prefs::kDemoModeCountry);
diff --git a/chrome/browser/ash/login/demo_mode/demo_setup_controller.h b/chrome/browser/ash/login/demo_mode/demo_setup_controller.h index bd9709c..b7bce17 100644 --- a/chrome/browser/ash/login/demo_mode/demo_setup_controller.h +++ b/chrome/browser/ash/login/demo_mode/demo_setup_controller.h
@@ -177,7 +177,9 @@ // If the current country requires customization, returns an user email that // corresponds to the sub organization the device should be enrolled into. - // Otherwise, returns an empty string. + // If chrome flag "--demo-mode-enrolling-username" is set for test, it + // will override the current country-derived user. If neither of above is + // true, returns an empty string. static std::string GetSubOrganizationEmail(); // Returns a dictionary mapping setup steps to step indices.
diff --git a/chrome/browser/ash/login/demo_mode/demo_setup_controller_unittest.cc b/chrome/browser/ash/login/demo_mode/demo_setup_controller_unittest.cc index 312a709..8affdb9 100644 --- a/chrome/browser/ash/login/demo_mode/demo_setup_controller_unittest.cc +++ b/chrome/browser/ash/login/demo_mode/demo_setup_controller_unittest.cc
@@ -6,11 +6,13 @@ #include <memory> +#include "ash/constants/ash_switches.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" +#include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "chrome/browser/ash/login/demo_mode/demo_session.h" @@ -362,6 +364,15 @@ EXPECT_EQ(email, ""); } +TEST_F(DemoSetupControllerTest, GetSubOrganizationEmailForCustomOU) { + base::test::ScopedCommandLine command_line; + command_line.GetProcessCommandLine()->AppendSwitchASCII( + switches::kDemoModeEnrollingUsername, "test-user-name"); + + std::string email = DemoSetupController::GetSubOrganizationEmail(); + EXPECT_EQ(email, "test-user-name@cros-demo-mode.com"); +} + TEST_F(DemoSetupControllerTest, OnlineSuccessWithValidRetailerAndStoreId) { SetupMockDemoModeOnlineEnrollmentHelper(DemoModeSetupResult::SUCCESS);
diff --git a/chrome/browser/ash/login/screens/active_directory_login_screen.cc b/chrome/browser/ash/login/screens/active_directory_login_screen.cc index ae903ba..3d644e2 100644 --- a/chrome/browser/ash/login/screens/active_directory_login_screen.cc +++ b/chrome/browser/ash/login/screens/active_directory_login_screen.cc
@@ -24,6 +24,7 @@ #include "ui/base/l10n/l10n_util.h" namespace ash { + namespace { constexpr char kUserActionCancel[] = "cancel"; @@ -73,7 +74,7 @@ view_->Reset(); authpolicy_login_helper_->CancelRequestsAndRestart(); error_screen_visible_ = false; - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); error_screen_->Hide(); } @@ -191,7 +192,7 @@ if (error_screen_visible_ && error_screen_->GetParentScreen() == ActiveDirectoryLoginView::kScreenId) { error_screen_visible_ = false; - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); error_screen_->Hide(); if (view_) view_->Show();
diff --git a/chrome/browser/ash/login/screens/active_directory_login_screen.h b/chrome/browser/ash/login/screens/active_directory_login_screen.h index fcfe440b5..7b8d641 100644 --- a/chrome/browser/ash/login/screens/active_directory_login_screen.h +++ b/chrome/browser/ash/login/screens/active_directory_login_screen.h
@@ -85,10 +85,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ActiveDirectoryLoginScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ACTIVE_DIRECTORY_LOGIN_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/active_directory_password_change_screen.h b/chrome/browser/ash/login/screens/active_directory_password_change_screen.h index 478b0f7f..7786ad7 100644 --- a/chrome/browser/ash/login/screens/active_directory_password_change_screen.h +++ b/chrome/browser/ash/login/screens/active_directory_password_change_screen.h
@@ -75,10 +75,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ActiveDirectoryPasswordChangeScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ACTIVE_DIRECTORY_PASSWORD_CHANGE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/app_downloading_screen.h b/chrome/browser/ash/login/screens/app_downloading_screen.h index defda8d..5c8a519 100644 --- a/chrome/browser/ash/login/screens/app_downloading_screen.h +++ b/chrome/browser/ash/login/screens/app_downloading_screen.h
@@ -44,10 +44,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// migration is finished. -namespace chromeos { -using ::ash::AppDownloadingScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_APP_DOWNLOADING_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/arc_terms_of_service_screen.h b/chrome/browser/ash/login/screens/arc_terms_of_service_screen.h index 00386ca0..94dae08 100644 --- a/chrome/browser/ash/login/screens/arc_terms_of_service_screen.h +++ b/chrome/browser/ash/login/screens/arc_terms_of_service_screen.h
@@ -88,10 +88,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash ::ArcTermsOfServiceScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ARC_TERMS_OF_SERVICE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/assistant_optin_flow_screen.cc b/chrome/browser/ash/login/screens/assistant_optin_flow_screen.cc index c62c608..5343958a 100644 --- a/chrome/browser/ash/login/screens/assistant_optin_flow_screen.cc +++ b/chrome/browser/ash/login/screens/assistant_optin_flow_screen.cc
@@ -9,6 +9,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/ash/assistant/assistant_util.h" #include "chrome/browser/ash/login/users/chrome_user_manager_util.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/ash/login/assistant_optin_flow_screen_handler.h"
diff --git a/chrome/browser/ash/login/screens/assistant_optin_flow_screen.h b/chrome/browser/ash/login/screens/assistant_optin_flow_screen.h index 05f1501e..25cde9e 100644 --- a/chrome/browser/ash/login/screens/assistant_optin_flow_screen.h +++ b/chrome/browser/ash/login/screens/assistant_optin_flow_screen.h
@@ -60,10 +60,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash ::AssistantOptInFlowScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ASSISTANT_OPTIN_FLOW_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/base_screen.cc b/chrome/browser/ash/login/screens/base_screen.cc index 8ecdcd9..2c5362b 100644 --- a/chrome/browser/ash/login/screens/base_screen.cc +++ b/chrome/browser/ash/login/screens/base_screen.cc
@@ -10,6 +10,7 @@ #include "base/logging.h" #include "base/notreached.h" #include "base/values.h" +#include "chrome/browser/ash/login/wizard_context.h" namespace ash {
diff --git a/chrome/browser/ash/login/screens/base_screen.h b/chrome/browser/ash/login/screens/base_screen.h index 15ade6e..fe2e71d 100644 --- a/chrome/browser/ash/login/screens/base_screen.h +++ b/chrome/browser/ash/login/screens/base_screen.h
@@ -8,12 +8,12 @@ #include "ash/public/cpp/login_accelerators.h" #include "base/values.h" #include "chrome/browser/ash/login/oobe_screen.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/wizard_context.h" #include "components/login/base_screen_handler_utils.h" namespace ash { +class WizardContext; + // Base class for the all OOBE/login/before-session screens. // Screens are identified by ID, screen and it's JS counterpart must have same // id. @@ -87,22 +87,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::BaseScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::BaseScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::BaseScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_BASE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/chrome_user_selection_screen.h b/chrome/browser/ash/login/screens/chrome_user_selection_screen.h index cc57f36..e0eb5615 100644 --- a/chrome/browser/ash/login/screens/chrome_user_selection_screen.h +++ b/chrome/browser/ash/login/screens/chrome_user_selection_screen.h
@@ -78,10 +78,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ChromeUserSelectionScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_CHROME_USER_SELECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/chromevox_hint/chromevox_hint_detector.h b/chrome/browser/ash/login/screens/chromevox_hint/chromevox_hint_detector.h index e507c04..723f6a06 100644 --- a/chrome/browser/ash/login/screens/chromevox_hint/chromevox_hint_detector.h +++ b/chrome/browser/ash/login/screens/chromevox_hint/chromevox_hint_detector.h
@@ -8,8 +8,6 @@ #include <memory> #include "base/memory/weak_ptr.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chrome/browser/ash/idle_detector.h" namespace base { class TickClock; @@ -17,6 +15,8 @@ namespace ash { +class IdleDetector; + // Helper for ChromeVox hint idle detection. class ChromeVoxHintDetector { public:
diff --git a/chrome/browser/ash/login/screens/consolidated_consent_screen.cc b/chrome/browser/ash/login/screens/consolidated_consent_screen.cc index 55aa012..8312cf7 100644 --- a/chrome/browser/ash/login/screens/consolidated_consent_screen.cc +++ b/chrome/browser/ash/login/screens/consolidated_consent_screen.cc
@@ -47,16 +47,18 @@ #include "components/signin/public/identity_manager/identity_manager.h" #include "components/user_manager/user_manager.h" -using ArcBackupAndRestoreConsent = - sync_pb::UserConsentTypes::ArcBackupAndRestoreConsent; -using ArcGoogleLocationServiceConsent = - sync_pb::UserConsentTypes::ArcGoogleLocationServiceConsent; -using ArcPlayTermsOfServiceConsent = - sync_pb::UserConsentTypes::ArcPlayTermsOfServiceConsent; -using sync_pb::UserConsentTypes; - namespace ash { + namespace { + +using ArcBackupAndRestoreConsent = + ::sync_pb::UserConsentTypes::ArcBackupAndRestoreConsent; +using ArcGoogleLocationServiceConsent = + ::sync_pb::UserConsentTypes::ArcGoogleLocationServiceConsent; +using ArcPlayTermsOfServiceConsent = + ::sync_pb::UserConsentTypes::ArcPlayTermsOfServiceConsent; +using ::sync_pb::UserConsentTypes; + constexpr const char kBackDemoButtonClicked[] = "back"; constexpr const char kAcceptButtonClicked[] = "tos-accept"; @@ -269,9 +271,8 @@ // If the user is not the owner and the owner disabled metrics, the user // is not allowed to update the usage opt-in. if (view_) { - view_->SetUsageOptinHidden( - !is_owner_.value_or(false) && - !ash::StatsReportingController::Get()->IsEnabled()); + view_->SetUsageOptinHidden(!is_owner_.value_or(false) && + !StatsReportingController::Get()->IsEnabled()); } const bool is_demo = arc::IsArcDemoModeSetupFlow(); @@ -303,7 +304,7 @@ is_enabled = *metrics_service->GetCurrentUserMetricsConsent(); } else { DCHECK(g_browser_process->local_state()); - is_enabled = ash::StatsReportingController::Get()->IsEnabled(); + is_enabled = StatsReportingController::Get()->IsEnabled(); } UpdateMetricsMode(is_enabled, is_managed); @@ -374,7 +375,7 @@ void ConsolidatedConsentScreen::ReportUsageOptIn(bool is_enabled) { DCHECK(is_owner_.has_value()); if (is_owner_.value()) { - ash::StatsReportingController::Get()->SetEnabled( + StatsReportingController::Get()->SetEnabled( ProfileManager::GetActiveUserProfile(), is_enabled); return; }
diff --git a/chrome/browser/ash/login/screens/consolidated_consent_screen.h b/chrome/browser/ash/login/screens/consolidated_consent_screen.h index f0972b3..a3e93a7 100644 --- a/chrome/browser/ash/login/screens/consolidated_consent_screen.h +++ b/chrome/browser/ash/login/screens/consolidated_consent_screen.h
@@ -132,10 +132,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash ::ConsolidatedConsentScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_CONSOLIDATED_CONSENT_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/cryptohome_recovery_screen.h b/chrome/browser/ash/login/screens/cryptohome_recovery_screen.h index 9de6e76..e65d1d5 100644 --- a/chrome/browser/ash/login/screens/cryptohome_recovery_screen.h +++ b/chrome/browser/ash/login/screens/cryptohome_recovery_screen.h
@@ -44,10 +44,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::CryptohomeRecoveryScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_CRYPTOHOME_RECOVERY_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/demo_preferences_screen.h b/chrome/browser/ash/login/screens/demo_preferences_screen.h index ae24f91..d08dc078 100644 --- a/chrome/browser/ash/login/screens/demo_preferences_screen.h +++ b/chrome/browser/ash/login/screens/demo_preferences_screen.h
@@ -51,16 +51,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::DemoPreferencesScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::DemoPreferencesScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_DEMO_PREFERENCES_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/demo_setup_screen.h b/chrome/browser/ash/login/screens/demo_setup_screen.h index a335832..1c68e30d 100644 --- a/chrome/browser/ash/login/screens/demo_setup_screen.h +++ b/chrome/browser/ash/login/screens/demo_setup_screen.h
@@ -67,10 +67,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::DemoSetupScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_DEMO_SETUP_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/device_disabled_screen.h b/chrome/browser/ash/login/screens/device_disabled_screen.h index b96e4240..4ab2af1 100644 --- a/chrome/browser/ash/login/screens/device_disabled_screen.h +++ b/chrome/browser/ash/login/screens/device_disabled_screen.h
@@ -37,10 +37,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::DeviceDisabledScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_DEVICE_DISABLED_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/edu_coexistence_login_screen.h b/chrome/browser/ash/login/screens/edu_coexistence_login_screen.h index 6cfdde5..1591309 100644 --- a/chrome/browser/ash/login/screens/edu_coexistence_login_screen.h +++ b/chrome/browser/ash/login/screens/edu_coexistence_login_screen.h
@@ -7,12 +7,8 @@ #include "base/callback.h" #include "base/scoped_observation.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/screen_manager.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chrome/browser/ash/login/ui/login_display_host.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ui/webui/signin/ash/inline_login_dialog_onboarding.h" namespace gfx { @@ -21,6 +17,8 @@ namespace ash { +class ScreenManager; + // OOBE screen to add EDU account as a secondary account when the user is a // supervised user. class EduCoexistenceLoginScreen : public BaseScreen, @@ -63,10 +61,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EduCoexistenceLoginScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_EDU_COEXISTENCE_LOGIN_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/enable_adb_sideloading_screen.h b/chrome/browser/ash/login/screens/enable_adb_sideloading_screen.h index f51b095..754438c 100644 --- a/chrome/browser/ash/login/screens/enable_adb_sideloading_screen.h +++ b/chrome/browser/ash/login/screens/enable_adb_sideloading_screen.h
@@ -62,10 +62,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EnableAdbSideloadingScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ENABLE_ADB_SIDELOADING_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/enable_debugging_screen.h b/chrome/browser/ash/login/screens/enable_debugging_screen.h index f196d35..b9ea311 100644 --- a/chrome/browser/ash/login/screens/enable_debugging_screen.h +++ b/chrome/browser/ash/login/screens/enable_debugging_screen.h
@@ -70,10 +70,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EnableDebuggingScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ENABLE_DEBUGGING_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/encryption_migration_mode.h b/chrome/browser/ash/login/screens/encryption_migration_mode.h index d5e8d2f..afd7240 100644 --- a/chrome/browser/ash/login/screens/encryption_migration_mode.h +++ b/chrome/browser/ash/login/screens/encryption_migration_mode.h
@@ -19,10 +19,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EncryptionMigrationMode; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ENCRYPTION_MIGRATION_MODE_H_
diff --git a/chrome/browser/ash/login/screens/encryption_migration_screen.h b/chrome/browser/ash/login/screens/encryption_migration_screen.h index f76a140..2038940 100644 --- a/chrome/browser/ash/login/screens/encryption_migration_screen.h +++ b/chrome/browser/ash/login/screens/encryption_migration_screen.h
@@ -173,10 +173,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EncryptionMigrationScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ENCRYPTION_MIGRATION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/error_screen.cc b/chrome/browser/ash/login/screens/error_screen.cc index 3d4eec4b..b54b9af 100644 --- a/chrome/browser/ash/login/screens/error_screen.cc +++ b/chrome/browser/ash/login/screens/error_screen.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/ash/connectivity_diagnostics_dialog.h" #include "chrome/browser/ui/webui/ash/internet_detail_dialog.h" +#include "chrome/browser/ui/webui/ash/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/ash/login/error_screen_handler.h" #include "chrome/browser/ui/webui/ash/login/gaia_screen_handler.h" #include "chrome/browser/ui/webui/ash/login/offline_login_screen_handler.h" @@ -45,6 +46,7 @@ #include "ui/gfx/native_widget_types.h" namespace ash { + namespace { // TODO(https://crbug.com/1241511): Remove this global. @@ -342,7 +344,7 @@ } void ErrorScreen::DefaultHideCallback() { - if (parent_screen_ != ash::OOBE_SCREEN_UNKNOWN && view_) + if (parent_screen_ != OOBE_SCREEN_UNKNOWN && view_) view_->ShowOobeScreen(parent_screen_); // TODO(antrim): Due to potential race with GAIA reload and hiding network
diff --git a/chrome/browser/ash/login/screens/error_screen.h b/chrome/browser/ash/login/screens/error_screen.h index 6cdbff07..010a2ce 100644 --- a/chrome/browser/ash/login/screens/error_screen.h +++ b/chrome/browser/ash/login/screens/error_screen.h
@@ -12,16 +12,15 @@ #include "chrome/browser/ash/login/help_app_launcher.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chrome/browser/ash/login/screens/network_error.h" -#include "chromeos/ash/components/login/auth/login_performer.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/ui/captive_portal_window_proxy.h" #include "chrome/browser/ash/settings/device_settings_service.h" #include "chrome/browser/ui/webui/ash/login/network_state_informer.h" +#include "chromeos/ash/components/login/auth/login_performer.h" #include "chromeos/ash/components/network/network_connection_observer.h" #include "components/web_modal/web_contents_modal_dialog_manager_delegate.h" namespace ash { +class CaptivePortalWindowProxy; class ErrorScreenView; // Controller for the error screen. @@ -56,8 +55,7 @@ NetworkError::ErrorState GetErrorState() const; // Returns id of the screen behind error screen ("caller" screen). - // Returns ash::OOBE_SCREEN_UNKNOWN if error screen isn't the current - // screen. + // Returns `OOBE_SCREEN_UNKNOWN` if error screen isn't the current screen. OobeScreenId GetParentScreen() const; // Called when we're asked to hide captive portal dialog. @@ -173,7 +171,7 @@ NetworkError::UIState ui_state_ = NetworkError::UI_STATE_UNKNOWN; NetworkError::ErrorState error_state_ = NetworkError::ERROR_STATE_UNKNOWN; - OobeScreenId parent_screen_ = ash::OOBE_SCREEN_UNKNOWN; + OobeScreenId parent_screen_ = OOBE_SCREEN_UNKNOWN; // Optional callback that is called when NetworkError screen is hidden. base::OnceClosure on_hide_callback_; @@ -189,10 +187,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ErrorScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_ERROR_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/eula_screen.h b/chrome/browser/ash/login/screens/eula_screen.h index a4c5637..d2a8551b 100644 --- a/chrome/browser/ash/login/screens/eula_screen.h +++ b/chrome/browser/ash/login/screens/eula_screen.h
@@ -105,16 +105,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::EulaScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::EulaScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_EULA_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/family_link_notice_screen.h b/chrome/browser/ash/login/screens/family_link_notice_screen.h index 30bc603..3fd9cd4a 100644 --- a/chrome/browser/ash/login/screens/family_link_notice_screen.h +++ b/chrome/browser/ash/login/screens/family_link_notice_screen.h
@@ -54,10 +54,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::FamilyLinkNoticeScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_FAMILY_LINK_NOTICE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/fingerprint_setup_screen.cc b/chrome/browser/ash/login/screens/fingerprint_setup_screen.cc index 0803dc89..34313a5 100644 --- a/chrome/browser/ash/login/screens/fingerprint_setup_screen.cc +++ b/chrome/browser/ash/login/screens/fingerprint_setup_screen.cc
@@ -8,6 +8,7 @@ #include "base/metrics/histogram_functions.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_utils.h" #include "chrome/browser/ash/login/users/chrome_user_manager_util.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h"
diff --git a/chrome/browser/ash/login/screens/fingerprint_setup_screen.h b/chrome/browser/ash/login/screens/fingerprint_setup_screen.h index 5673b9e..952be13 100644 --- a/chrome/browser/ash/login/screens/fingerprint_setup_screen.h +++ b/chrome/browser/ash/login/screens/fingerprint_setup_screen.h
@@ -100,10 +100,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::FingerprintSetupScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_FINGERPRINT_SETUP_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/gaia_password_changed_screen.h b/chrome/browser/ash/login/screens/gaia_password_changed_screen.h index 32cf1ee2..7578151 100644 --- a/chrome/browser/ash/login/screens/gaia_password_changed_screen.h +++ b/chrome/browser/ash/login/screens/gaia_password_changed_screen.h
@@ -73,10 +73,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::GaiaPasswordChangedScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_GAIA_PASSWORD_CHANGED_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/gaia_screen.h b/chrome/browser/ash/login/screens/gaia_screen.h index 263337a..6fa2f7a 100644 --- a/chrome/browser/ash/login/screens/gaia_screen.h +++ b/chrome/browser/ash/login/screens/gaia_screen.h
@@ -79,10 +79,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::GaiaScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_GAIA_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/gesture_navigation_screen.cc b/chrome/browser/ash/login/screens/gesture_navigation_screen.cc index d4dc6c7a..54db3cab 100644 --- a/chrome/browser/ash/login/screens/gesture_navigation_screen.cc +++ b/chrome/browser/ash/login/screens/gesture_navigation_screen.cc
@@ -12,6 +12,7 @@ #include "base/metrics/histogram_functions.h" #include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "chrome/browser/ash/login/users/chrome_user_manager_util.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/ash/login/gesture_navigation_screen_handler.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/ash/login/screens/gesture_navigation_screen.h b/chrome/browser/ash/login/screens/gesture_navigation_screen.h index dd60b6c..f14b48a 100644 --- a/chrome/browser/ash/login/screens/gesture_navigation_screen.h +++ b/chrome/browser/ash/login/screens/gesture_navigation_screen.h
@@ -72,10 +72,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::GestureNavigationScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_GESTURE_NAVIGATION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/guest_tos_screen.h b/chrome/browser/ash/login/screens/guest_tos_screen.h index 6bc25e5..805dc3c 100644 --- a/chrome/browser/ash/login/screens/guest_tos_screen.h +++ b/chrome/browser/ash/login/screens/guest_tos_screen.h
@@ -49,10 +49,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::GuestTosScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_GUEST_TOS_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/hardware_data_collection_screen.cc b/chrome/browser/ash/login/screens/hardware_data_collection_screen.cc index c78bc0a..527e72c3 100644 --- a/chrome/browser/ash/login/screens/hardware_data_collection_screen.cc +++ b/chrome/browser/ash/login/screens/hardware_data_collection_screen.cc
@@ -9,6 +9,7 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "base/check_op.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/settings/hardware_data_usage_controller.h" #include "chrome/browser/browser_process.h" @@ -18,6 +19,7 @@ #include "components/user_manager/user_manager.h" namespace ash { + namespace { constexpr const char kUserActionAcceptButtonClicked[] = "accept-button";
diff --git a/chrome/browser/ash/login/screens/hardware_data_collection_screen.h b/chrome/browser/ash/login/screens/hardware_data_collection_screen.h index c7c7bf3..9ac7143 100644 --- a/chrome/browser/ash/login/screens/hardware_data_collection_screen.h +++ b/chrome/browser/ash/login/screens/hardware_data_collection_screen.h
@@ -54,10 +54,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::HWDataCollectionScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_HARDWARE_DATA_COLLECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/hid_detection_screen.cc b/chrome/browser/ash/login/screens/hid_detection_screen.cc index 052ef0090..9cc98e2b 100644 --- a/chrome/browser/ash/login/screens/hid_detection_screen.cc +++ b/chrome/browser/ash/login/screens/hid_detection_screen.cc
@@ -37,6 +37,7 @@ #define ENABLED_VLOG_LEVEL 1 namespace ash { + namespace { // Possible ui-states for device-blocks. @@ -147,7 +148,7 @@ : BaseScreen(HIDDetectionView::kScreenId, OobeScreenPriority::DEFAULT), view_(std::move(view)), exit_callback_(exit_callback) { - if (ash::features::IsOobeHidDetectionRevampEnabled()) { + if (features::IsOobeHidDetectionRevampEnabled()) { VLOG(1) << "OOBE HID detection revamped flow started"; const auto& hid_detection_manager_override = GetHidDetectionManagerOverrideForTesting(); @@ -166,7 +167,7 @@ } HIDDetectionScreen::~HIDDetectionScreen() { - if (ash::features::IsOobeHidDetectionRevampEnabled()) { + if (features::IsOobeHidDetectionRevampEnabled()) { return; } @@ -191,7 +192,7 @@ } void HIDDetectionScreen::OnContinueButtonClicked() { - if (ash::features::IsOobeHidDetectionRevampEnabled()) { + if (features::IsOobeHidDetectionRevampEnabled()) { hid_detection_manager_->StopHidDetection(); } else { hid_detection::RecordBluetoothPairingAttempts(num_pairing_attempts_); @@ -218,7 +219,7 @@ void HIDDetectionScreen::CheckIsScreenRequired( base::OnceCallback<void(bool)> on_check_done) { - if (ash::features::IsOobeHidDetectionRevampEnabled()) { + if (features::IsOobeHidDetectionRevampEnabled()) { hid_detection_manager_->GetIsHidDetectionRequired(std::move(on_check_done)); return; } @@ -243,7 +244,7 @@ if (!is_hidden()) return; - if (ash::features::IsOobeHidDetectionRevampEnabled()) { + if (features::IsOobeHidDetectionRevampEnabled()) { if (view_) view_->Show(); @@ -274,7 +275,7 @@ if (is_hidden()) return; - if (!ash::features::IsOobeHidDetectionRevampEnabled()) { + if (!features::IsOobeHidDetectionRevampEnabled()) { if (discovery_session_.get()) discovery_session_->Stop();
diff --git a/chrome/browser/ash/login/screens/hid_detection_screen.h b/chrome/browser/ash/login/screens/hid_detection_screen.h index 731178e..b0c51ef 100644 --- a/chrome/browser/ash/login/screens/hid_detection_screen.h +++ b/chrome/browser/ash/login/screens/hid_detection_screen.h
@@ -17,6 +17,7 @@ #include "base/memory/weak_ptr.h" #include "base/timer/elapsed_timer.h" #include "chrome/browser/ash/login/screens/base_screen.h" +#include "chrome/browser/ui/webui/ash/login/hid_detection_screen_handler.h" #include "chromeos/ash/components/hid_detection/hid_detection_manager.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_device.h" @@ -28,9 +29,6 @@ namespace ash { -class HIDDetectionView; -class WizardContext; - // Representation independent class that controls screen showing warning about // HID absence to users. class HIDDetectionScreen : public BaseScreen, @@ -282,9 +280,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove when the migration is finished. -namespace chromeos { -using ::ash::HIDDetectionScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_HID_DETECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/hid_detection_screen_browsertest.cc b/chrome/browser/ash/login/screens/hid_detection_screen_browsertest.cc index 2ea6433f..6368e62 100644 --- a/chrome/browser/ash/login/screens/hid_detection_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/hid_detection_screen_browsertest.cc
@@ -39,14 +39,13 @@ #include "services/device/public/mojom/input_service.mojom.h" namespace ash { + namespace { using ::testing::_; using HidType = hid_detection::HidType; using HidsMissing = hid_detection::HidsMissing; using InputState = hid_detection::HidDetectionManager::InputState; -using NiceMockDevice = - std::unique_ptr<testing::NiceMock<device::MockBluetoothDevice>>; const uint32_t kTestBluetoothClass = 1337u; const char kTestBluetoothName[] = "testName"; @@ -91,7 +90,7 @@ HIDDetectionScreenChromeboxTest() { if (GetParam()) { scoped_feature_list_.InitAndEnableFeature( - ash::features::kOobeHidDetectionRevamp); + features::kOobeHidDetectionRevamp); auto fake_hid_detection_manager = std::make_unique<hid_detection::FakeHidDetectionManager>(); @@ -102,7 +101,7 @@ } scoped_feature_list_.InitAndDisableFeature( - ash::features::kOobeHidDetectionRevamp); + features::kOobeHidDetectionRevamp); } HIDDetectionScreenChromeboxTest(const HIDDetectionScreenChromeboxTest&) = @@ -828,7 +827,7 @@ HIDDetectionScreenChromebaseTest() { if (GetParam()) { scoped_feature_list_.InitAndEnableFeature( - ash::features::kOobeHidDetectionRevamp); + features::kOobeHidDetectionRevamp); auto fake_hid_detection_manager = std::make_unique<hid_detection::FakeHidDetectionManager>(); @@ -841,7 +840,7 @@ } scoped_feature_list_.InitAndDisableFeature( - ash::features::kOobeHidDetectionRevamp); + features::kOobeHidDetectionRevamp); hid_controller_.set_wait_until_idle_after_device_update(false); hid_controller_.AddTouchscreen();
diff --git a/chrome/browser/ash/login/screens/kiosk_autolaunch_screen.h b/chrome/browser/ash/login/screens/kiosk_autolaunch_screen.h index 6ed896a..516d850 100644 --- a/chrome/browser/ash/login/screens/kiosk_autolaunch_screen.h +++ b/chrome/browser/ash/login/screens/kiosk_autolaunch_screen.h
@@ -48,16 +48,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::KioskAutolaunchScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::KioskAutolaunchScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_KIOSK_AUTOLAUNCH_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/kiosk_enable_screen.h b/chrome/browser/ash/login/screens/kiosk_enable_screen.h index fee344c0..b6e99046 100644 --- a/chrome/browser/ash/login/screens/kiosk_enable_screen.h +++ b/chrome/browser/ash/login/screens/kiosk_enable_screen.h
@@ -53,10 +53,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::KioskEnableScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_KIOSK_ENABLE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/lacros_data_backward_migration_screen.h b/chrome/browser/ash/login/screens/lacros_data_backward_migration_screen.h index 7b2e2a3e..b084f785 100644 --- a/chrome/browser/ash/login/screens/lacros_data_backward_migration_screen.h +++ b/chrome/browser/ash/login/screens/lacros_data_backward_migration_screen.h
@@ -44,10 +44,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::LacrosDataBackwardMigrationScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_LACROS_DATA_BACKWARD_MIGRATION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/lacros_data_migration_screen.h b/chrome/browser/ash/login/screens/lacros_data_migration_screen.h index 366ea7f..a64293c4 100644 --- a/chrome/browser/ash/login/screens/lacros_data_migration_screen.h +++ b/chrome/browser/ash/login/screens/lacros_data_migration_screen.h
@@ -99,10 +99,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::LacrosDataMigrationScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_LACROS_DATA_MIGRATION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/local_state_error_screen.h b/chrome/browser/ash/login/screens/local_state_error_screen.h index e590489..7f67d42d 100644 --- a/chrome/browser/ash/login/screens/local_state_error_screen.h +++ b/chrome/browser/ash/login/screens/local_state_error_screen.h
@@ -32,10 +32,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::LocalStateErrorScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_LOCAL_STATE_ERROR_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/locale_switch_screen.cc b/chrome/browser/ash/login/screens/locale_switch_screen.cc index e97641c..adefa951 100644 --- a/chrome/browser/ash/login/screens/locale_switch_screen.cc +++ b/chrome/browser/ash/login/screens/locale_switch_screen.cc
@@ -7,6 +7,7 @@ #include "base/time/time.h" #include "chrome/browser/ash/base/locale_util.h" #include "chrome/browser/ash/login/login_pref_names.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h"
diff --git a/chrome/browser/ash/login/screens/locale_switch_screen.h b/chrome/browser/ash/login/screens/locale_switch_screen.h index 69c91f92..b2ca754 100644 --- a/chrome/browser/ash/login/screens/locale_switch_screen.h +++ b/chrome/browser/ash/login/screens/locale_switch_screen.h
@@ -78,10 +78,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::LocaleSwitchScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_LOCALE_SWITCH_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/management_transition_screen.cc b/chrome/browser/ash/login/screens/management_transition_screen.cc index d61919e4..9760f89 100644 --- a/chrome/browser/ash/login/screens/management_transition_screen.cc +++ b/chrome/browser/ash/login/screens/management_transition_screen.cc
@@ -21,15 +21,12 @@ #include "chrome/browser/ui/managed_ui.h" #include "chrome/browser/ui/webui/ash/login/management_transition_screen_handler.h" +namespace ash { + namespace { constexpr base::TimeDelta kWaitingTimeout = base::Minutes(2); -} // namespace - -namespace ash { - -namespace { // Management transition screen step names. constexpr const char kUserActionfinishManagementTransition[] = "finish-management-transition"; @@ -68,9 +65,9 @@ // Disable system tray, shutdown button and prevent login as guest when // management transition screen is shown. SystemTrayClientImpl::Get()->SetPrimaryTrayEnabled(false); - ash::LoginScreen::Get()->EnableShutdownButton(false); - ash::LoginScreen::Get()->SetAllowLoginAsGuest(false); - ash::LoginScreen::Get()->SetIsFirstSigninStep(false); + LoginScreen::Get()->EnableShutdownButton(false); + LoginScreen::Get()->SetAllowLoginAsGuest(false); + LoginScreen::Get()->SetIsFirstSigninStep(false); arc::ArcManagementTransition arc_management_transition = arc::GetManagementTransition(profile);
diff --git a/chrome/browser/ash/login/screens/management_transition_screen.h b/chrome/browser/ash/login/screens/management_transition_screen.h index 10c05ef..713d1dc 100644 --- a/chrome/browser/ash/login/screens/management_transition_screen.h +++ b/chrome/browser/ash/login/screens/management_transition_screen.h
@@ -66,10 +66,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ManagementTransitionScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MANAGEMENT_TRANSITION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/marketing_opt_in_screen.cc b/chrome/browser/ash/login/screens/marketing_opt_in_screen.cc index 2cb990e73..0a09901 100644 --- a/chrome/browser/ash/login/screens/marketing_opt_in_screen.cc +++ b/chrome/browser/ash/login/screens/marketing_opt_in_screen.cc
@@ -41,6 +41,7 @@ #include "ui/base/l10n/l10n_util.h" namespace ash { + namespace { constexpr char kUserActionGetStarted[] = "get-started"; @@ -280,8 +281,7 @@ void MarketingOptInScreen::SetA11yNavigationButtonsEnabled(bool enabled) { ProfileManager::GetActiveUserProfile()->GetPrefs()->SetBoolean( - ash::prefs::kAccessibilityTabletModeShelfNavigationButtonsEnabled, - enabled); + prefs::kAccessibilityTabletModeShelfNavigationButtonsEnabled, enabled); a11y_nav_buttons_toggle_metrics_reporter_timer_.Start( FROM_HERE, base::Seconds(10), base::BindOnce(&RecordShowShelfNavigationButtonsValueChange, enabled));
diff --git a/chrome/browser/ash/login/screens/marketing_opt_in_screen.h b/chrome/browser/ash/login/screens/marketing_opt_in_screen.h index 56fc97e..52b89ea 100644 --- a/chrome/browser/ash/login/screens/marketing_opt_in_screen.h +++ b/chrome/browser/ash/login/screens/marketing_opt_in_screen.h
@@ -155,10 +155,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MarketingOptInScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MARKETING_OPT_IN_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_arc_terms_of_service_screen.h b/chrome/browser/ash/login/screens/mock_arc_terms_of_service_screen.h index d335422..d7d51b3 100644 --- a/chrome/browser/ash/login/screens/mock_arc_terms_of_service_screen.h +++ b/chrome/browser/ash/login/screens/mock_arc_terms_of_service_screen.h
@@ -48,11 +48,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockArcTermsOfServiceScreen; -using ::ash::MockArcTermsOfServiceScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_ARC_TERMS_OF_SERVICE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_consolidated_consent_screen.h b/chrome/browser/ash/login/screens/mock_consolidated_consent_screen.h index 138c2d7..2d81bc37 100644 --- a/chrome/browser/ash/login/screens/mock_consolidated_consent_screen.h +++ b/chrome/browser/ash/login/screens/mock_consolidated_consent_screen.h
@@ -42,11 +42,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockConsolidatedConsentScreen; -using ::ash::MockConsolidatedConsentScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_CONSOLIDATED_CONSENT_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_demo_preferences_screen.h b/chrome/browser/ash/login/screens/mock_demo_preferences_screen.h index 2ae14518..6dc90859 100644 --- a/chrome/browser/ash/login/screens/mock_demo_preferences_screen.h +++ b/chrome/browser/ash/login/screens/mock_demo_preferences_screen.h
@@ -47,11 +47,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockDemoPreferencesScreen; -using ::ash::MockDemoPreferencesScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_DEMO_PREFERENCES_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_demo_setup_screen.h b/chrome/browser/ash/login/screens/mock_demo_setup_screen.h index 66cbee93..b0f2b9a 100644 --- a/chrome/browser/ash/login/screens/mock_demo_setup_screen.h +++ b/chrome/browser/ash/login/screens/mock_demo_setup_screen.h
@@ -42,11 +42,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockDemoSetupScreen; -using ::ash::MockDemoSetupScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_DEMO_SETUP_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_device_disabled_screen_view.h b/chrome/browser/ash/login/screens/mock_device_disabled_screen_view.h index 565184b..0aff5f69 100644 --- a/chrome/browser/ash/login/screens/mock_device_disabled_screen_view.h +++ b/chrome/browser/ash/login/screens/mock_device_disabled_screen_view.h
@@ -24,10 +24,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockDeviceDisabledScreenView; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_DEVICE_DISABLED_SCREEN_VIEW_H_
diff --git a/chrome/browser/ash/login/screens/mock_enable_adb_sideloading_screen.h b/chrome/browser/ash/login/screens/mock_enable_adb_sideloading_screen.h index d563429..251b8780 100644 --- a/chrome/browser/ash/login/screens/mock_enable_adb_sideloading_screen.h +++ b/chrome/browser/ash/login/screens/mock_enable_adb_sideloading_screen.h
@@ -37,11 +37,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockEnableAdbSideloadingScreen; -using ::ash::MockEnableAdbSideloadingScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_ENABLE_ADB_SIDELOADING_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_enable_debugging_screen.h b/chrome/browser/ash/login/screens/mock_enable_debugging_screen.h index 6c13e20..31eb415 100644 --- a/chrome/browser/ash/login/screens/mock_enable_debugging_screen.h +++ b/chrome/browser/ash/login/screens/mock_enable_debugging_screen.h
@@ -36,11 +36,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockEnableDebuggingScreen; -using ::ash::MockEnableDebuggingScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_ENABLE_DEBUGGING_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_eula_screen.h b/chrome/browser/ash/login/screens/mock_eula_screen.h index 33356fc..1b9a510 100644 --- a/chrome/browser/ash/login/screens/mock_eula_screen.h +++ b/chrome/browser/ash/login/screens/mock_eula_screen.h
@@ -39,11 +39,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockEulaScreen; -using ::ash::MockEulaView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_EULA_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_network_screen.h b/chrome/browser/ash/login/screens/mock_network_screen.h index 507a713..eab4d085 100644 --- a/chrome/browser/ash/login/screens/mock_network_screen.h +++ b/chrome/browser/ash/login/screens/mock_network_screen.h
@@ -44,11 +44,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockNetworkScreen; -using ::ash::MockNetworkScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_NETWORK_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_update_screen.h b/chrome/browser/ash/login/screens/mock_update_screen.h index df66300..39b5a97 100644 --- a/chrome/browser/ash/login/screens/mock_update_screen.h +++ b/chrome/browser/ash/login/screens/mock_update_screen.h
@@ -51,11 +51,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockUpdateScreen; -using ::ash::MockUpdateView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_UPDATE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_welcome_screen.h b/chrome/browser/ash/login/screens/mock_welcome_screen.h index 8e00d53b..73238ad 100644 --- a/chrome/browser/ash/login/screens/mock_welcome_screen.h +++ b/chrome/browser/ash/login/screens/mock_welcome_screen.h
@@ -55,11 +55,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockWelcomeScreen; -using ::ash::MockWelcomeView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_WELCOME_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/mock_wrong_hwid_screen.h b/chrome/browser/ash/login/screens/mock_wrong_hwid_screen.h index aa5a7c5..845afb76 100644 --- a/chrome/browser/ash/login/screens/mock_wrong_hwid_screen.h +++ b/chrome/browser/ash/login/screens/mock_wrong_hwid_screen.h
@@ -34,11 +34,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MockWrongHWIDScreen; -using ::ash::MockWrongHWIDScreenView; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MOCK_WRONG_HWID_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/multidevice_setup_screen.cc b/chrome/browser/ash/login/screens/multidevice_setup_screen.cc index a3de34b9..032f982 100644 --- a/chrome/browser/ash/login/screens/multidevice_setup_screen.cc +++ b/chrome/browser/ash/login/screens/multidevice_setup_screen.cc
@@ -9,6 +9,7 @@ #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/ash/login/users/chrome_user_manager_util.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/ash/multidevice_setup/oobe_completion_tracker_factory.h" #include "chrome/browser/profiles/profile_manager.h" @@ -21,6 +22,7 @@ #define ENABLED_VLOG_LEVEL 1 namespace ash { + namespace { constexpr const char kAcceptedSetupUserAction[] = "setup-accepted";
diff --git a/chrome/browser/ash/login/screens/multidevice_setup_screen.h b/chrome/browser/ash/login/screens/multidevice_setup_screen.h index 19cbb07..e856903c 100644 --- a/chrome/browser/ash/login/screens/multidevice_setup_screen.h +++ b/chrome/browser/ash/login/screens/multidevice_setup_screen.h
@@ -84,10 +84,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::MultiDeviceSetupScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_MULTIDEVICE_SETUP_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/network_error.h b/chrome/browser/ash/login/screens/network_error.h index 40724bf..d697895c 100644 --- a/chrome/browser/ash/login/screens/network_error.h +++ b/chrome/browser/ash/login/screens/network_error.h
@@ -71,10 +71,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::NetworkError; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_NETWORK_ERROR_H_
diff --git a/chrome/browser/ash/login/screens/network_screen.h b/chrome/browser/ash/login/screens/network_screen.h index a7162bed..05b09977 100644 --- a/chrome/browser/ash/login/screens/network_screen.h +++ b/chrome/browser/ash/login/screens/network_screen.h
@@ -13,8 +13,6 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "base/timer/timer.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/helper.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chromeos/ash/components/network/network_state_handler_observer.h" @@ -23,6 +21,10 @@ class NetworkScreenView; class NetworkStateHandler; +namespace login { +class NetworkStateHelper; +} + // Controls network selection screen shown during OOBE. class NetworkScreen : public BaseScreen, public NetworkStateHandlerObserver { public: @@ -152,16 +154,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::NetworkScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::NetworkScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_NETWORK_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/offline_login_screen.h b/chrome/browser/ash/login/screens/offline_login_screen.h index 59e22e7..a9c7193e 100644 --- a/chrome/browser/ash/login/screens/offline_login_screen.h +++ b/chrome/browser/ash/login/screens/offline_login_screen.h
@@ -79,10 +79,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::OfflineLoginScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_OFFLINE_LOGIN_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/os_trial_screen.h b/chrome/browser/ash/login/screens/os_trial_screen.h index 2419838..5787d4a5 100644 --- a/chrome/browser/ash/login/screens/os_trial_screen.h +++ b/chrome/browser/ash/login/screens/os_trial_screen.h
@@ -43,10 +43,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::OsTrialScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_OS_TRIAL_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/os_trial_screen_browsertest.cc b/chrome/browser/ash/login/screens/os_trial_screen_browsertest.cc index e1686ee..acc7013 100644 --- a/chrome/browser/ash/login/screens/os_trial_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/os_trial_screen_browsertest.cc
@@ -16,7 +16,9 @@ #include "content/public/test/browser_test.h" namespace ash { + namespace { + const test::UIPath kWelcomeGetStartedButton = {"connect", "welcomeScreen", "getStarted"}; const test::UIPath kOsInstallBackButton = {"os-install", "osInstallExitButton"}; @@ -80,8 +82,8 @@ WizardController::default_controller()->AdvanceToScreen( UserCreationView::kScreenId); OobeScreenWaiter(UserCreationView::kScreenId).Wait(); - ASSERT_TRUE(ash::LoginScreenTestApi::IsOsInstallButtonShown()); - ASSERT_TRUE(ash::LoginScreenTestApi::ClickOsInstallButton()); + ASSERT_TRUE(LoginScreenTestApi::IsOsInstallButtonShown()); + ASSERT_TRUE(LoginScreenTestApi::ClickOsInstallButton()); OobeScreenWaiter(OsInstallScreenView::kScreenId).Wait(); } @@ -101,7 +103,7 @@ WizardController::default_controller()->AdvanceToScreen( UserCreationView::kScreenId); OobeScreenWaiter(UserCreationView::kScreenId).Wait(); - ASSERT_TRUE(ash::LoginScreenTestApi::ClickOsInstallButton()); + ASSERT_TRUE(LoginScreenTestApi::ClickOsInstallButton()); OobeScreenWaiter(OsInstallScreenView::kScreenId).Wait(); test::OobeJS().ClickOnPath(kOsInstallBackButton);
diff --git a/chrome/browser/ash/login/screens/packaged_license_screen.h b/chrome/browser/ash/login/screens/packaged_license_screen.h index 91a8b12..d6a1c34 100644 --- a/chrome/browser/ash/login/screens/packaged_license_screen.h +++ b/chrome/browser/ash/login/screens/packaged_license_screen.h
@@ -70,10 +70,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::PackagedLicenseScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_PACKAGED_LICENSE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/parental_handoff_screen.cc b/chrome/browser/ash/login/screens/parental_handoff_screen.cc index 4b01041c..2082829 100644 --- a/chrome/browser/ash/login/screens/parental_handoff_screen.cc +++ b/chrome/browser/ash/login/screens/parental_handoff_screen.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/ash/child_accounts/family_features.h" #include "chrome/browser/ash/login/oobe_screen.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/supervised_user/supervised_user_features/supervised_user_features.h" @@ -19,6 +20,7 @@ #include "ui/base/l10n/l10n_util.h" namespace ash { + namespace { constexpr char kUserActionNext[] = "next";
diff --git a/chrome/browser/ash/login/screens/parental_handoff_screen.h b/chrome/browser/ash/login/screens/parental_handoff_screen.h index 40f4e229..46bdabf 100644 --- a/chrome/browser/ash/login/screens/parental_handoff_screen.h +++ b/chrome/browser/ash/login/screens/parental_handoff_screen.h
@@ -51,10 +51,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ParentalHandoffScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_PARENTAL_HANDOFF_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/pin_setup_screen.h b/chrome/browser/ash/login/screens/pin_setup_screen.h index 1fc8572..c8ac43d 100644 --- a/chrome/browser/ash/login/screens/pin_setup_screen.h +++ b/chrome/browser/ash/login/screens/pin_setup_screen.h
@@ -12,13 +12,12 @@ #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "chrome/browser/ash/login/screens/base_screen.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/wizard_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { class PinSetupScreenView; +class WizardContext; class PinSetupScreen : public BaseScreen { public: @@ -91,10 +90,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::PinSetupScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_PIN_SETUP_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/quick_start_screen.h b/chrome/browser/ash/login/screens/quick_start_screen.h index 136b3e7..36ea3e11 100644 --- a/chrome/browser/ash/login/screens/quick_start_screen.h +++ b/chrome/browser/ash/login/screens/quick_start_screen.h
@@ -52,16 +52,10 @@ base::WeakPtr<TView> view_; ScreenExitCallback exit_callback_; - base::WeakPtr<ash::quick_start::TargetDeviceBootstrapController> + base::WeakPtr<quick_start::TargetDeviceBootstrapController> bootstrap_controller_; }; } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::QuickStartScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_QUICK_START_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher.h b/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher.h index 690be10..b292a4bb4 100644 --- a/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher.h +++ b/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher.h
@@ -30,10 +30,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::RecommendAppsFetcher; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RECOMMEND_APPS_RECOMMEND_APPS_FETCHER_H_
diff --git a/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher_delegate.h b/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher_delegate.h index f07ae12..af53419 100644 --- a/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher_delegate.h +++ b/chrome/browser/ash/login/screens/recommend_apps/recommend_apps_fetcher_delegate.h
@@ -28,10 +28,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::RecommendAppsFetcherDelegate; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RECOMMEND_APPS_RECOMMEND_APPS_FETCHER_DELEGATE_H_
diff --git a/chrome/browser/ash/login/screens/recommend_apps/scoped_test_recommend_apps_fetcher_factory.h b/chrome/browser/ash/login/screens/recommend_apps/scoped_test_recommend_apps_fetcher_factory.h index 0fe33cb..be89f06 100644 --- a/chrome/browser/ash/login/screens/recommend_apps/scoped_test_recommend_apps_fetcher_factory.h +++ b/chrome/browser/ash/login/screens/recommend_apps/scoped_test_recommend_apps_fetcher_factory.h
@@ -23,10 +23,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ScopedTestRecommendAppsFetcherFactory; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RECOMMEND_APPS_SCOPED_TEST_RECOMMEND_APPS_FETCHER_FACTORY_H_
diff --git a/chrome/browser/ash/login/screens/recommend_apps_screen.h b/chrome/browser/ash/login/screens/recommend_apps_screen.h index 6bb12ece..6fd6158 100644 --- a/chrome/browser/ash/login/screens/recommend_apps_screen.h +++ b/chrome/browser/ash/login/screens/recommend_apps_screen.h
@@ -89,10 +89,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash ::RecommendAppsScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RECOMMEND_APPS_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/recovery_eligibility_screen.cc b/chrome/browser/ash/login/screens/recovery_eligibility_screen.cc index aa4d5be..8792d4bf 100644 --- a/chrome/browser/ash/login/screens/recovery_eligibility_screen.cc +++ b/chrome/browser/ash/login/screens/recovery_eligibility_screen.cc
@@ -6,6 +6,7 @@ #include "ash/constants/ash_features.h" #include "base/callback.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ui/webui/ash/login/recovery_eligibility_screen_handler.h" #include "chromeos/ash/components/login/auth/public/user_context.h"
diff --git a/chrome/browser/ash/login/screens/recovery_eligibility_screen.h b/chrome/browser/ash/login/screens/recovery_eligibility_screen.h index e1b78b1..17eb0d1f 100644 --- a/chrome/browser/ash/login/screens/recovery_eligibility_screen.h +++ b/chrome/browser/ash/login/screens/recovery_eligibility_screen.h
@@ -34,10 +34,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::RecoveryEligibilityScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RECOVERY_ELIGIBILITY_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/reset_screen.cc b/chrome/browser/ash/login/screens/reset_screen.cc index 7467bfd..9ecab69b 100644 --- a/chrome/browser/ash/login/screens/reset_screen.cc +++ b/chrome/browser/ash/login/screens/reset_screen.cc
@@ -34,6 +34,7 @@ #include "chromeos/system/statistics_provider.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/user_manager/user_manager.h" // Enable VLOG level 1. #undef ENABLED_VLOG_LEVEL
diff --git a/chrome/browser/ash/login/screens/reset_screen.h b/chrome/browser/ash/login/screens/reset_screen.h index f67983b..e9f11d34 100644 --- a/chrome/browser/ash/login/screens/reset_screen.h +++ b/chrome/browser/ash/login/screens/reset_screen.h
@@ -98,10 +98,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ResetScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_RESET_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/saml_confirm_password_screen.h b/chrome/browser/ash/login/screens/saml_confirm_password_screen.h index 8b7ff0f..29d31773 100644 --- a/chrome/browser/ash/login/screens/saml_confirm_password_screen.h +++ b/chrome/browser/ash/login/screens/saml_confirm_password_screen.h
@@ -68,10 +68,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::SamlConfirmPasswordScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_SAML_CONFIRM_PASSWORD_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/signin_fatal_error_screen.h b/chrome/browser/ash/login/screens/signin_fatal_error_screen.h index 7200c04..ffa969b 100644 --- a/chrome/browser/ash/login/screens/signin_fatal_error_screen.h +++ b/chrome/browser/ash/login/screens/signin_fatal_error_screen.h
@@ -64,16 +64,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::SignInFatalErrorScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::SignInFatalErrorScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_SIGNIN_FATAL_ERROR_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/smart_privacy_protection_screen.cc b/chrome/browser/ash/login/screens/smart_privacy_protection_screen.cc index a9b0366..dcd01b0 100644 --- a/chrome/browser/ash/login/screens/smart_privacy_protection_screen.cc +++ b/chrome/browser/ash/login/screens/smart_privacy_protection_screen.cc
@@ -6,11 +6,13 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/ash/login/smart_privacy_protection_screen_handler.h" #include "components/prefs/pref_service.h" namespace ash { + namespace { constexpr const char kUserActionFeatureTurnOn[] = "continue-feature-on"; @@ -46,7 +48,7 @@ // SnoopingProtection and QuickDim. The screen should be skipped if none of // them is enabled. if (!context.skip_post_login_screens_for_tests && - ash::features::IsQuickDimEnabled()) { + features::IsQuickDimEnabled()) { return false; } exit_callback_.Run(Result::NOT_APPLICABLE); @@ -65,7 +67,7 @@ if (action_id == kUserActionFeatureTurnOn) { Profile* profile = ProfileManager::GetActiveUserProfile(); profile->GetPrefs()->SetBoolean(prefs::kPowerQuickDimEnabled, - ash::features::IsQuickDimEnabled()); + features::IsQuickDimEnabled()); exit_callback_.Run(Result::PROCEED_WITH_FEATURE_ON); } else if (action_id == kUserActionFeatureTurnOff) { Profile* profile = ProfileManager::GetActiveUserProfile();
diff --git a/chrome/browser/ash/login/screens/smart_privacy_protection_screen.h b/chrome/browser/ash/login/screens/smart_privacy_protection_screen.h index bc5a324..6261cea2 100644 --- a/chrome/browser/ash/login/screens/smart_privacy_protection_screen.h +++ b/chrome/browser/ash/login/screens/smart_privacy_protection_screen.h
@@ -57,10 +57,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::SmartPrivacyProtectionScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_SMART_PRIVACY_PROTECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/sync_consent_screen.h b/chrome/browser/ash/login/screens/sync_consent_screen.h index f70391f..6378fb5 100644 --- a/chrome/browser/ash/login/screens/sync_consent_screen.h +++ b/chrome/browser/ash/login/screens/sync_consent_screen.h
@@ -206,10 +206,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::SyncConsentScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_SYNC_CONSENT_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/terms_of_service_screen.h b/chrome/browser/ash/login/screens/terms_of_service_screen.h index 08f7ef8..29513fc 100644 --- a/chrome/browser/ash/login/screens/terms_of_service_screen.h +++ b/chrome/browser/ash/login/screens/terms_of_service_screen.h
@@ -105,10 +105,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::TermsOfServiceScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_TERMS_OF_SERVICE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/terms_of_service_screen_browsertest.cc b/chrome/browser/ash/login/screens/terms_of_service_screen_browsertest.cc index 408e7fbf..4f35a49 100644 --- a/chrome/browser/ash/login/screens/terms_of_service_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/terms_of_service_screen_browsertest.cc
@@ -54,8 +54,6 @@ using ::net::test_server::BasicHttpResponse; using ::net::test_server::HttpRequest; using ::net::test_server::HttpResponse; -using ::testing::_; -using ::testing::InvokeWithoutArgs; const char kAccountId[] = "dla@example.com"; const char kDisplayName[] = "display name"; @@ -103,7 +101,7 @@ // Prevent browser start in user session so that we do not need to wait // for its initialization. - ash::test::UserSessionManagerTestApi(ash::UserSessionManager::GetInstance()) + test::UserSessionManagerTestApi(UserSessionManager::GetInstance()) .SetShouldLaunchBrowserInTests(false); } @@ -498,7 +496,7 @@ OobeScreenId PendingScreenToId(PendingScreen pending_screen) { switch (pending_screen) { case PendingScreen::kEmpty: - return ash::OOBE_SCREEN_UNKNOWN; + return OOBE_SCREEN_UNKNOWN; case PendingScreen::kTermsOfService: return TermsOfServiceScreenView::kScreenId; case PendingScreen::kSyncConsent: @@ -568,7 +566,7 @@ EnsurePendingScreenIsEmpty(); EXPECT_EQ(WizardController::default_controller() ->get_screen_after_managed_tos_for_testing(), - ash::OOBE_SCREEN_UNKNOWN); + OOBE_SCREEN_UNKNOWN); test::WaitForPrimaryUserSessionStart(); break; case PendingScreen::kTermsOfService:
diff --git a/chrome/browser/ash/login/screens/theme_selection_screen.cc b/chrome/browser/ash/login/screens/theme_selection_screen.cc index 4ec8939..a76a9e569 100644 --- a/chrome/browser/ash/login/screens/theme_selection_screen.cc +++ b/chrome/browser/ash/login/screens/theme_selection_screen.cc
@@ -9,6 +9,7 @@ #include "ash/public/cpp/schedule_enums.h" #include "ash/system/scheduled_feature/scheduled_feature.h" #include "chrome/browser/ash/login/screens/base_screen.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/ash/login/theme_selection_screen_handler.h" #include "components/prefs/pref_service.h" @@ -17,6 +18,7 @@ namespace ash { namespace { + constexpr const char kUserActionNext[] = "next"; constexpr const char kUserActionSelect[] = "select";
diff --git a/chrome/browser/ash/login/screens/theme_selection_screen.h b/chrome/browser/ash/login/screens/theme_selection_screen.h index 3dd98a26..a4befd0f8 100644 --- a/chrome/browser/ash/login/screens/theme_selection_screen.h +++ b/chrome/browser/ash/login/screens/theme_selection_screen.h
@@ -58,12 +58,7 @@ base::WeakPtr<ThemeSelectionScreenView> view_; ScreenExitCallback exit_callback_; }; -} // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::ThemeSelectionScreen; -} +} // namespace ash #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_THEME_SELECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/theme_selection_screen_browsertest.cc b/chrome/browser/ash/login/screens/theme_selection_screen_browsertest.cc index fa6af37..93a399a 100644 --- a/chrome/browser/ash/login/screens/theme_selection_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/theme_selection_screen_browsertest.cc
@@ -29,7 +29,9 @@ #include "content/public/test/browser_test.h" namespace ash { + namespace { + constexpr char kThemeSelectionId[] = "theme-selection"; constexpr char kLightThemeButton[] = "lightThemeButton"; constexpr char kDarkThemeButton[] = "darkThemeButton"; @@ -43,6 +45,7 @@ kThemeSelectionId, "theme-selection-subtitle-clamshell"}; const test::UIPath kScreenSubtitleTabletPath = { kThemeSelectionId, "theme-selection-subtitle-tablet"}; + } // namespace class ThemeSelectionScreenTest @@ -81,8 +84,8 @@ } void setTabletMode(bool enabled) { - ash::TabletMode::Waiter waiter(enabled); - ash::Shell::Get()->tablet_mode_controller()->SetEnabledForTest(enabled); + TabletMode::Waiter waiter(enabled); + Shell::Get()->tablet_mode_controller()->SetEnabledForTest(enabled); waiter.Wait(); } @@ -127,12 +130,12 @@ if (selectedOption == kDarkThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetBoolean(prefs::kDarkModeEnabled), true); EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 0); - EXPECT_TRUE(ash::DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); + EXPECT_TRUE(DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); } else if (selectedOption == kLightThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetBoolean(prefs::kDarkModeEnabled), false); EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 0); - EXPECT_FALSE(ash::DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); + EXPECT_FALSE(DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); } else if (selectedOption == kAutoThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 1); @@ -196,12 +199,12 @@ if (selectedOption == kDarkThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetBoolean(prefs::kDarkModeEnabled), true); EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 0); - EXPECT_TRUE(ash::DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); + EXPECT_TRUE(DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); } else if (selectedOption == kLightThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetBoolean(prefs::kDarkModeEnabled), false); EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 0); - EXPECT_FALSE(ash::DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); + EXPECT_FALSE(DarkLightModeControllerImpl::Get()->IsDarkModeEnabled()); } else if (selectedOption == kAutoThemeButton) { EXPECT_EQ(profile->GetPrefs()->GetInteger(prefs::kDarkModeScheduleType), 1);
diff --git a/chrome/browser/ash/login/screens/tpm_error_screen.cc b/chrome/browser/ash/login/screens/tpm_error_screen.cc index d2fa247..200d1cb 100644 --- a/chrome/browser/ash/login/screens/tpm_error_screen.cc +++ b/chrome/browser/ash/login/screens/tpm_error_screen.cc
@@ -5,10 +5,12 @@ #include "chrome/browser/ash/login/screens/tpm_error_screen.h" #include "base/memory/weak_ptr.h" +#include "chrome/browser/ash/login/wizard_context.h" #include "chrome/browser/ui/webui/ash/login/tpm_error_screen_handler.h" #include "chromeos/dbus/power/power_manager_client.h" namespace ash { + namespace { constexpr char kUserActionReboot[] = "reboot-system";
diff --git a/chrome/browser/ash/login/screens/tpm_error_screen.h b/chrome/browser/ash/login/screens/tpm_error_screen.h index a328bc2..a7a40e6 100644 --- a/chrome/browser/ash/login/screens/tpm_error_screen.h +++ b/chrome/browser/ash/login/screens/tpm_error_screen.h
@@ -31,10 +31,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::TpmErrorScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_TPM_ERROR_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/update_required_screen.cc b/chrome/browser/ash/login/screens/update_required_screen.cc index 588d7d0..a0d4c17 100644 --- a/chrome/browser/ash/login/screens/update_required_screen.cc +++ b/chrome/browser/ash/login/screens/update_required_screen.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" +#include "chrome/browser/ash/settings/cros_settings.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/ui/webui/ash/login/update_required_screen_handler.h" @@ -34,6 +35,7 @@ #define ENABLED_VLOG_LEVEL 1 namespace ash { + namespace { constexpr char kUserActionSelectNetworkButtonClicked[] = "select-network"; @@ -416,7 +418,7 @@ } void UpdateRequiredScreen::OnErrorScreenHidden() { - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); // Return to the default state. error_screen_->SetIsPersistentError(false /* is_persistent */); Show(context());
diff --git a/chrome/browser/ash/login/screens/update_required_screen.h b/chrome/browser/ash/login/screens/update_required_screen.h index f7a9f311..8d90101 100644 --- a/chrome/browser/ash/login/screens/update_required_screen.h +++ b/chrome/browser/ash/login/screens/update_required_screen.h
@@ -13,12 +13,10 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "base/time/time.h" -#include "chromeos/ash/components/network/network_state_handler_observer.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/error_screens_histogram_helper.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chrome/browser/ash/login/screens/error_screen.h" #include "chrome/browser/ash/login/version_updater/version_updater.h" +#include "chromeos/ash/components/network/network_state_handler_observer.h" #include "components/user_manager/remove_user_delegate.h" namespace base { @@ -27,6 +25,7 @@ namespace ash { +class ErrorScreensHistogramHelper; class NetworkStateHandler; class UpdateRequiredView; @@ -157,10 +156,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::UpdateRequiredScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_UPDATE_REQUIRED_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/update_required_screen_browsertest.cc b/chrome/browser/ash/login/screens/update_required_screen_browsertest.cc index 943ff2ef..664d5e8 100644 --- a/chrome/browser/ash/login/screens/update_required_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/update_required_screen_browsertest.cc
@@ -35,6 +35,7 @@ #include "chromeos/ash/components/dbus/dbus_thread_manager.h" #include "chromeos/ash/components/dbus/update_engine/fake_update_engine_client.h" #include "chromeos/ash/components/network/network_state_test_helper.h" +#include "chromeos/ash/components/settings/cros_settings_names.h" #include "chromeos/dbus/constants/dbus_switches.h" #include "components/user_manager/user_manager.h" #include "content/public/test/browser_test.h" @@ -248,7 +249,7 @@ // process should start. network_state_test_helper_->SetServiceProperty( wifi_path, shill::kStateProperty, base::Value(shill::kStateOnline)); - EXPECT_EQ(ash::OOBE_SCREEN_UNKNOWN.AsId(), error_screen->GetParentScreen()); + EXPECT_EQ(OOBE_SCREEN_UNKNOWN.AsId(), error_screen->GetParentScreen()); SetUpdateEngineStatus(update_engine::Operation::CHECKING_FOR_UPDATE); SetUpdateEngineStatus(update_engine::Operation::UPDATE_AVAILABLE);
diff --git a/chrome/browser/ash/login/screens/update_screen.cc b/chrome/browser/ash/login/screens/update_screen.cc index 0f01a5d3..d72569b 100644 --- a/chrome/browser/ash/login/screens/update_screen.cc +++ b/chrome/browser/ash/login/screens/update_screen.cc
@@ -35,6 +35,7 @@ #define ENABLED_VLOG_LEVEL 1 namespace ash { + namespace { constexpr const char kUserActionAcceptUpdateOverCellular[] = @@ -90,7 +91,7 @@ RecordFinalizeTime(finalize_time); } -} // anonymous namespace +} // namespace // static std::string UpdateScreen::GetResultString(Result result) { @@ -129,7 +130,7 @@ return true; } - if (ash::IsRollbackFlow(context)) { + if (IsRollbackFlow(context)) { LOG(WARNING) << "Skip OOBE Update because enterprise rollback just happened."; exit_callback_.Run(VersionUpdater::Result::UPDATE_SKIPPED); @@ -522,7 +523,7 @@ } void UpdateScreen::OnErrorScreenHidden() { - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); Show(context()); }
diff --git a/chrome/browser/ash/login/screens/update_screen.h b/chrome/browser/ash/login/screens/update_screen.h index 3731e38..dd548858 100644 --- a/chrome/browser/ash/login/screens/update_screen.h +++ b/chrome/browser/ash/login/screens/update_screen.h
@@ -16,13 +16,9 @@ #include "base/time/time.h" #include "base/timer/timer.h" #include "chrome/browser/ash/accessibility/accessibility_manager.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/error_screens_histogram_helper.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chrome/browser/ash/login/screens/error_screen.h" #include "chrome/browser/ash/login/version_updater/version_updater.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/wizard_context.h" #include "chromeos/dbus/power/power_manager_client.h" namespace base { @@ -31,6 +27,7 @@ namespace ash { +class ErrorScreensHistogramHelper; class UpdateView; // Controller for the update screen. @@ -252,16 +249,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::UpdateScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::UpdateScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_UPDATE_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/update_screen_browsertest.cc b/chrome/browser/ash/login/screens/update_screen_browsertest.cc index ec86097..53d748d 100644 --- a/chrome/browser/ash/login/screens/update_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/update_screen_browsertest.cc
@@ -556,7 +556,7 @@ // If the network is a captive portal network, error message is shown with a // delay. EXPECT_TRUE(update_screen_->GetErrorMessageTimerForTesting()->IsRunning()); - EXPECT_EQ(ash::OOBE_SCREEN_UNKNOWN.AsId(), error_screen_->GetParentScreen()); + EXPECT_EQ(OOBE_SCREEN_UNKNOWN.AsId(), error_screen_->GetParentScreen()); // If network goes back online, the error message timer should be canceled. network_portal_detector_.SimulateDefaultNetworkState( @@ -698,7 +698,7 @@ "fake_path", base::DoNothing(), base::DoNothing(), false /* check_error_state */, ConnectCallbackMode::ON_COMPLETED); - ASSERT_EQ(ash::OOBE_SCREEN_UNKNOWN.AsId(), error_screen_->GetParentScreen()); + ASSERT_EQ(OOBE_SCREEN_UNKNOWN.AsId(), error_screen_->GetParentScreen()); if (!GetParam().is_eu || !features::IsConsumerAutoUpdateToggleAllowed()) { EXPECT_TRUE(update_screen_->GetShowTimerForTesting()->IsRunning()); update_screen_->GetShowTimerForTesting()->FireNow();
diff --git a/chrome/browser/ash/login/screens/user_creation_screen.cc b/chrome/browser/ash/login/screens/user_creation_screen.cc index 1f2272b..a9d14c3 100644 --- a/chrome/browser/ash/login/screens/user_creation_screen.cc +++ b/chrome/browser/ash/login/screens/user_creation_screen.cc
@@ -17,6 +17,7 @@ #include "chromeos/ash/components/network/network_state_handler.h" namespace ash { + namespace { constexpr char kUserActionSignIn[] = "signin"; @@ -108,7 +109,7 @@ void UserCreationScreen::HideImpl() { scoped_observation_.Reset(); error_screen_visible_ = false; - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); error_screen_->Hide(); } @@ -158,7 +159,7 @@ if (error_screen_visible_ && error_screen_->GetParentScreen() == UserCreationView::kScreenId) { error_screen_visible_ = false; - error_screen_->SetParentScreen(ash::OOBE_SCREEN_UNKNOWN); + error_screen_->SetParentScreen(OOBE_SCREEN_UNKNOWN); error_screen_->Hide(); view_->Show(); histogram_helper_->OnErrorHide();
diff --git a/chrome/browser/ash/login/screens/user_creation_screen.h b/chrome/browser/ash/login/screens/user_creation_screen.h index 885c755..85aeea76 100644 --- a/chrome/browser/ash/login/screens/user_creation_screen.h +++ b/chrome/browser/ash/login/screens/user_creation_screen.h
@@ -90,10 +90,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::UserCreationScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_USER_CREATION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/user_selection_screen.cc b/chrome/browser/ash/login/screens/user_selection_screen.cc index 2e5857e..2373610a 100644 --- a/chrome/browser/ash/login/screens/user_selection_screen.cc +++ b/chrome/browser/ash/login/screens/user_selection_screen.cc
@@ -74,6 +74,7 @@ #define ENABLED_VLOG_LEVEL 1 namespace ash { + namespace { const char kWakeLockReason[] = "TPMLockedIssue"; @@ -748,14 +749,14 @@ void UserSelectionScreen::ShowUserPodCustomIcon( const AccountId& account_id, const proximity_auth::ScreenlockBridge::UserPodCustomIconInfo& icon_info) { - if (base::FeatureList::IsEnabled(ash::features::kSmartLockUIRevamp)) + if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) return; view_->ShowUserPodCustomIcon(account_id, icon_info); } void UserSelectionScreen::HideUserPodCustomIcon(const AccountId& account_id) { - if (base::FeatureList::IsEnabled(ash::features::kSmartLockUIRevamp)) + if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) return; view_->HideUserPodCustomIcon(account_id); @@ -763,14 +764,14 @@ void UserSelectionScreen::SetSmartLockState(const AccountId& account_id, SmartLockState state) { - if (base::FeatureList::IsEnabled(ash::features::kSmartLockUIRevamp)) { + if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) { view_->SetSmartLockState(account_id, state); } } void UserSelectionScreen::NotifySmartLockAuthResult(const AccountId& account_id, bool success) { - if (base::FeatureList::IsEnabled(ash::features::kSmartLockUIRevamp)) { + if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) { view_->NotifySmartLockAuthResult(account_id, success); } }
diff --git a/chrome/browser/ash/login/screens/user_selection_screen.h b/chrome/browser/ash/login/screens/user_selection_screen.h index 7f57ab4..0eacc59 100644 --- a/chrome/browser/ash/login/screens/user_selection_screen.h +++ b/chrome/browser/ash/login/screens/user_selection_screen.h
@@ -13,8 +13,6 @@ #include "base/scoped_observation.h" #include "base/time/time.h" #include "base/timer/timer.h" -// TODO(https://crbug.com/1164001): move to forward declaration -#include "chrome/browser/ash/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/ash/login/saml/password_sync_token_checkers_collection.h" #include "chrome/browser/ash/login/signin/token_handle_util.h" #include "chrome/browser/ash/login/ui/login_display.h" @@ -31,8 +29,10 @@ class AccountId; namespace ash { -struct LoginUserInfo; + +class EasyUnlockService; class UserBoardView; +struct LoginUserInfo; enum class DisplayedScreen { SIGN_IN_SCREEN, USER_ADDING_SCREEN, LOCK_SCREEN }; @@ -191,11 +191,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::DisplayedScreen; -using ::ash::UserSelectionScreen; -} // namespace chromeos - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_USER_SELECTION_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc b/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc index 130a1edd..f840d64 100644 --- a/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc
@@ -266,8 +266,7 @@ test::OobeJS().ExpectVisiblePath(kErrorMessageOfflineSigninLink); } -class DarkLightEnabledTest : public LoginManagerTest, - public ash::ColorModeObserver { +class DarkLightEnabledTest : public LoginManagerTest, public ColorModeObserver { public: DarkLightEnabledTest() { feature_list_.InitAndEnableFeature(chromeos::features::kDarkLightMode); @@ -275,7 +274,7 @@ protected: void StartLogin(const AccountId& account_id) { - ash::DarkLightModeControllerImpl::Get()->AddObserver(this); + DarkLightModeControllerImpl::Get()->AddObserver(this); wait_for_color_mode_change_ = true; LoginDisplayHost::default_host() ->GetWizardContext() @@ -283,7 +282,7 @@ login_manager_mixin_.LoginWithDefaultContext( LoginManagerMixin::TestUserInfo(account_id)); WaitForColorModeChange(); - ash::DarkLightModeControllerImpl::Get()->RemoveObserver(this); + DarkLightModeControllerImpl::Get()->RemoveObserver(this); } void FinishLogin() { LoginDisplayHost::default_host() @@ -320,7 +319,7 @@ // OOBE + login of the first user. IN_PROC_BROWSER_TEST_F(DarkLightEnabledTest, PRE_PRE_OobeLogin) { OobeScreenWaiter(UserCreationView::kScreenId).Wait(); - auto* dark_light_mode_controller = ash::DarkLightModeControllerImpl::Get(); + auto* dark_light_mode_controller = DarkLightModeControllerImpl::Get(); EXPECT_FALSE(dark_light_mode_controller->IsDarkModeEnabled()); StartLogin(user1); @@ -339,7 +338,7 @@ IN_PROC_BROWSER_TEST_F(DarkLightEnabledTest, PRE_OobeLogin) { // Oobe is hidden - prefs of the focused user are applied. EXPECT_FALSE(LoginScreenTestApi::IsOobeDialogVisible()); - auto* dark_light_mode_controller = ash::DarkLightModeControllerImpl::Get(); + auto* dark_light_mode_controller = DarkLightModeControllerImpl::Get(); EXPECT_TRUE(dark_light_mode_controller->IsDarkModeEnabled()); LoginScreenTestApi::ClickAddUserButton(); @@ -376,7 +375,7 @@ // Test focusing different pods. IN_PROC_BROWSER_TEST_F(DarkLightEnabledTest, OobeLogin) { ASSERT_EQ(LoginScreenTestApi::GetFocusedUser(), user2); - auto* dark_light_mode_controller = ash::DarkLightModeControllerImpl::Get(); + auto* dark_light_mode_controller = DarkLightModeControllerImpl::Get(); EXPECT_FALSE(dark_light_mode_controller->IsDarkModeEnabled()); ASSERT_TRUE(LoginScreenTestApi::FocusUser(user1));
diff --git a/chrome/browser/ash/login/screens/welcome_screen.cc b/chrome/browser/ash/login/screens/welcome_screen.cc index 7e060ac2..f977775 100644 --- a/chrome/browser/ash/login/screens/welcome_screen.cc +++ b/chrome/browser/ash/login/screens/welcome_screen.cc
@@ -47,6 +47,7 @@ #include "content/public/browser/browser_thread.h" namespace ash { + namespace { constexpr const char kRemoraRequisitionIdentifier[] = "remora"; @@ -305,7 +306,7 @@ return; timezone_ = timezone_id; - chromeos::system::SetSystemAndSigninScreenTimezone(timezone_id); + system::SetSystemAndSigninScreenTimezone(timezone_id); } std::string WelcomeScreen::GetTimezone() const { @@ -329,8 +330,8 @@ // CfM devices default to static timezone. g_browser_process->local_state()->SetInteger( ::prefs::kResolveDeviceTimezoneByGeolocationMethod, - static_cast<int>(chromeos::system::TimeZoneResolverManager:: - TimeZoneResolveMethod::DISABLED)); + static_cast<int>( + system::TimeZoneResolverManager::TimeZoneResolveMethod::DISABLED)); } // Exit Chrome to force the restart as soon as a new requisition is set. @@ -409,7 +410,7 @@ void WelcomeScreen::OnUserAction(const base::Value::List& args) { const std::string& action_id = args[0].GetString(); if (action_id == kUserActionQuickStartClicked) { - DCHECK(ash::features::IsOobeQuickStartEnabled()); + DCHECK(features::IsOobeQuickStartEnabled()); Exit(Result::QUICK_START); return; } @@ -693,9 +694,9 @@ } void WelcomeScreen::OnAccessibilityStatusChanged( - const ash::AccessibilityStatusEventDetails& details) { + const AccessibilityStatusEventDetails& details) { if (details.notification_type == - ash::AccessibilityNotificationType::kManagerShutdown) { + AccessibilityNotificationType::kManagerShutdown) { accessibility_subscription_ = {}; } else { UpdateA11yState();
diff --git a/chrome/browser/ash/login/screens/welcome_screen.h b/chrome/browser/ash/login/screens/welcome_screen.h index 4a62aa6a..08ef91b 100644 --- a/chrome/browser/ash/login/screens/welcome_screen.h +++ b/chrome/browser/ash/login/screens/welcome_screen.h
@@ -15,25 +15,25 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/ash/accessibility/accessibility_manager.h" -// TODO(https://crbug.com/1164001): forward declare LanguageSwitchResult -// after this file is moved to ash. -#include "chrome/browser/ash/base/locale_util.h" #include "chrome/browser/ash/login/oobe_quick_start/target_device_bootstrap_controller.h" #include "chrome/browser/ash/login/screens/base_screen.h" #include "chrome/browser/ash/login/screens/chromevox_hint/chromevox_hint_detector.h" -// TODO(https://crbug.com/1164001): move to forward declaration. -#include "chrome/browser/ash/login/ui/input_events_blocker.h" #include "chrome/browser/ash/login/wizard_context.h" #include "ui/base/ime/ash/input_method_manager.h" namespace ash { +class InputEventsBlocker; class WelcomeView; +namespace locale_util { +struct LanguageSwitchResult; +} + class WelcomeScreen : public BaseScreen, public input_method::InputMethodManager::Observer, public ChromeVoxHintDetector::Observer, - public ash::SystemTrayObserver { + public SystemTrayObserver { public: using TView = WelcomeView; @@ -181,7 +181,7 @@ void UpdateChromadMigrationOobeFlow(bool exists); void OnAccessibilityStatusChanged( - const ash::AccessibilityStatusEventDetails& details); + const AccessibilityStatusEventDetails& details); void UpdateA11yState(); // Adds data to the OOBE.WelcomeScreen.UserChangedLocale metric and calls @@ -207,7 +207,7 @@ base::CallbackListSubscription accessibility_subscription_; - base::WeakPtr<ash::quick_start::TargetDeviceBootstrapController> + base::WeakPtr<quick_start::TargetDeviceBootstrapController> bootstrap_controller_; // WeakPtrFactory used to schedule and cancel tasks related to language update @@ -220,16 +220,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::WelcomeScreen; -} - -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace ash { -using ::chromeos::WelcomeScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_WELCOME_SCREEN_H_
diff --git a/chrome/browser/ash/login/screens/welcome_screen_browsertest.cc b/chrome/browser/ash/login/screens/welcome_screen_browsertest.cc index 993f789b..3adad761 100644 --- a/chrome/browser/ash/login/screens/welcome_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/welcome_screen_browsertest.cc
@@ -31,14 +31,17 @@ #include "chrome/browser/ash/login/test/test_predicate_waiter.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/wizard_controller.h" +#include "chrome/browser/ash/settings/cros_settings.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/ui/webui/ash/login/enable_debugging_screen_handler.h" #include "chrome/browser/ui/webui/ash/login/gaia_screen_handler.h" #include "chrome/browser/ui/webui/ash/login/oobe_ui.h" #include "chrome/browser/ui/webui/ash/login/welcome_screen_handler.h" +#include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chromeos/ash/components/settings/cros_settings_names.h" #include "chromeos/dbus/constants/dbus_switches.h" #include "chromeos/system/fake_statistics_provider.h" #include "components/language/core/browser/pref_names.h" @@ -49,6 +52,7 @@ #include "ui/base/ime/ash/extension_ime_util.h" namespace ash { + namespace { const char kStartupManifestEnglish[] = @@ -133,7 +137,7 @@ // done in chrome main, which has not happened yet. base::FilePath user_data_dir; EXPECT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)); - ash::RegisterStubPathOverrides(user_data_dir); + RegisterStubPathOverrides(user_data_dir); return true; } @@ -553,7 +557,7 @@ return false; base::FilePath preinstalled_components_dir; - EXPECT_TRUE(base::PathService::Get(ash::DIR_PREINSTALLED_COMPONENTS, + EXPECT_TRUE(base::PathService::Get(DIR_PREINSTALLED_COMPONENTS, &preinstalled_components_dir)); base::FilePath preserve_dir = @@ -886,7 +890,7 @@ // skipToLoginForTesting is called. IN_PROC_BROWSER_TEST_F(WelcomeScreenChromeVoxHintTest, SkipToLoginForTesting) { OobeScreenWaiter(WelcomeView::kScreenId).Wait(); - ash::WizardController::default_controller()->SkipToLoginForTesting(); + WizardController::default_controller()->SkipToLoginForTesting(); OobeScreenWaiter(GaiaView::kScreenId).Wait(); EXPECT_TRUE(IdleDetectionCancelledForTesting());
diff --git a/chrome/browser/ash/login/screens/wrong_hwid_screen.h b/chrome/browser/ash/login/screens/wrong_hwid_screen.h index 660849e..c1ff8cf 100644 --- a/chrome/browser/ash/login/screens/wrong_hwid_screen.h +++ b/chrome/browser/ash/login/screens/wrong_hwid_screen.h
@@ -48,10 +48,4 @@ } // namespace ash -// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos -// source migration is finished. -namespace chromeos { -using ::ash::WrongHWIDScreen; -} - #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_WRONG_HWID_SCREEN_H_
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc index e184813..0a876bd 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.cc
@@ -3,9 +3,11 @@ // found in the LICENSE file. #include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h" -#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h" #include "base/logging.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h" #include "chromeos/ash/services/cros_healthd/public/cpp/service_connection.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -15,26 +17,6 @@ namespace cros_healthd = ::ash::cros_healthd::mojom; -ThunderboltSecurityLevel TranslateThunderboltSecurityLevel( - cros_healthd::ThunderboltSecurityLevel security_level) { - switch (security_level) { - case cros_healthd::ThunderboltSecurityLevel::kNone: - return THUNDERBOLT_SECURITY_NONE_LEVEL; - case cros_healthd::ThunderboltSecurityLevel::kUserLevel: - return THUNDERBOLT_SECURITY_USER_LEVEL; - case cros_healthd::ThunderboltSecurityLevel::kSecureLevel: - return THUNDERBOLT_SECURITY_SECURE_LEVEL; - case cros_healthd::ThunderboltSecurityLevel::kDpOnlyLevel: - return THUNDERBOLT_SECURITY_DP_ONLY_LEVEL; - case cros_healthd::ThunderboltSecurityLevel::kUsbOnlyLevel: - return THUNDERBOLT_SECURITY_USB_ONLY_LEVEL; - case cros_healthd::ThunderboltSecurityLevel::kNoPcieLevel: - return THUNDERBOLT_SECURITY_NO_PCIE_LEVEL; - } - - NOTREACHED(); -} - MemoryEncryptionState TranslateMemoryEncryptionState( cros_healthd::EncryptionState encryption_state) { switch (encryption_state) { @@ -65,118 +47,6 @@ NOTREACHED(); } -void HandleBusResult(OptionalMetricCallback callback, - CrosHealthdMetricSampler::MetricType metric_type, - cros_healthd::TelemetryInfoPtr result) { - absl::optional<MetricData> metric_data; - const auto& bus_result = result->bus_result; - - if (!bus_result.is_null()) { - switch (bus_result->which()) { - case cros_healthd::BusResult::Tag::kError: { - DVLOG(1) << "cros_healthd: Error getting bus info: " - << bus_result->get_error()->msg; - break; - } - - case cros_healthd::BusResult::Tag::kBusDevices: { - for (const auto& bus_device : bus_result->get_bus_devices()) { - const auto& bus_info = bus_device->bus_info; - if (metric_type == CrosHealthdMetricSampler::MetricType::kInfo) { - if (bus_info->is_thunderbolt_bus_info()) { - if (!metric_data.has_value()) { - metric_data = absl::make_optional<MetricData>(); - } - auto* const thunderbolt_info_out = - metric_data->mutable_info_data() - ->mutable_bus_device_info() - ->add_thunderbolt_info(); - thunderbolt_info_out->set_security_level( - TranslateThunderboltSecurityLevel( - bus_info->get_thunderbolt_bus_info()->security_level)); - } - } else if (metric_type == - CrosHealthdMetricSampler::MetricType::kTelemetry) { - if (bus_info->is_usb_bus_info()) { - if (!metric_data.has_value()) { - metric_data = absl::make_optional<MetricData>(); - } - auto* const usb_telemetry_out = - metric_data->mutable_telemetry_data() - ->mutable_peripherals_telemetry() - ->add_usb_telemetry(); - usb_telemetry_out->set_vid( - bus_info->get_usb_bus_info()->vendor_id); - usb_telemetry_out->set_pid( - bus_info->get_usb_bus_info()->product_id); - usb_telemetry_out->set_class_id( - bus_info->get_usb_bus_info()->class_id); - usb_telemetry_out->set_subclass_id( - bus_info->get_usb_bus_info()->subclass_id); - usb_telemetry_out->set_vendor(bus_device->vendor_name); - usb_telemetry_out->set_name(bus_device->product_name); - if (bus_info->get_usb_bus_info()->fwupd_firmware_version_info) { - usb_telemetry_out->set_firmware_version( - bus_info->get_usb_bus_info() - ->fwupd_firmware_version_info->version); - } - } - } - } - break; - } - } - } - - std::move(callback).Run(std::move(metric_data)); -} - -void HandleCpuResult(OptionalMetricCallback callback, - CrosHealthdMetricSampler::MetricType metric_type, - cros_healthd::TelemetryInfoPtr result) { - absl::optional<MetricData> metric_data; - const auto& cpu_result = result->cpu_result; - - if (!cpu_result.is_null()) { - switch (cpu_result->which()) { - case cros_healthd::CpuResult::Tag::kError: { - DVLOG(1) << "cros_healthd: Error getting CPU info: " - << cpu_result->get_error()->msg; - break; - } - - case cros_healthd::CpuResult::Tag::kCpuInfo: { - const auto& cpu_info = cpu_result->get_cpu_info(); - if (cpu_info.is_null()) { - DVLOG(1) << "Null CpuInfo from cros_healthd"; - break; - } - - // Gather keylocker info. - if (metric_type == CrosHealthdMetricSampler::MetricType::kInfo) { - metric_data = absl::make_optional<MetricData>(); - auto* const keylocker_info_out = metric_data->mutable_info_data() - ->mutable_cpu_info() - ->mutable_keylocker_info(); - const auto* const keylocker_info = cpu_info->keylocker_info.get(); - if (keylocker_info) { - keylocker_info_out->set_supported(true); - keylocker_info_out->set_configured( - keylocker_info->keylocker_configured); - } else { - // If keylocker info isn't set, it is not supported on the board. - keylocker_info_out->set_supported(false); - keylocker_info_out->set_configured(false); - } - } - break; - } - } - } - - std::move(callback).Run(std::move(metric_data)); -} - void HandleBootPerformanceResult( OptionalMetricCallback callback, CrosHealthdMetricSampler::MetricType metric_type, @@ -497,11 +367,13 @@ break; } case cros_healthd::ProbeCategoryEnum::kBus: { - HandleBusResult(std::move(callback), metric_type, std::move(result)); + CrosHealthdBusSamplerHandler handler = CrosHealthdBusSamplerHandler(metric_type); + handler.HandleResult(std::move(result), std::move(callback)); break; } case cros_healthd::ProbeCategoryEnum::kCpu: { - HandleCpuResult(std::move(callback), metric_type, std::move(result)); + CrosHealthdCpuSamplerHandler handler = CrosHealthdCpuSamplerHandler(); + handler.HandleResult(std::move(result), std::move(callback)); break; } case cros_healthd::ProbeCategoryEnum::kMemory: {
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.cc index dadfe9e..9cacf5f6 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.cc +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.cc
@@ -1,4 +1,4 @@ -// Copyright 2021 The Chromium Authors +// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h index 36e6dfae..d3952e5 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_audio_sampler_handler.h
@@ -1,4 +1,4 @@ -// Copyright 2021 The Chromium Authors +// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.cc new file mode 100644 index 0000000..010e76d --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.cc
@@ -0,0 +1,116 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h" + +#include <utility> + +#include "base/logging.h" +#include "base/notreached.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h" +#include "components/reporting/metrics/sampler.h" +#include "components/reporting/proto/synced/metric_data.pb.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +namespace { + +ThunderboltSecurityLevel TranslateThunderboltSecurityLevel( + cros_healthd::ThunderboltSecurityLevel security_level) { + switch (security_level) { + case cros_healthd::ThunderboltSecurityLevel::kNone: + return THUNDERBOLT_SECURITY_NONE_LEVEL; + case cros_healthd::ThunderboltSecurityLevel::kUserLevel: + return THUNDERBOLT_SECURITY_USER_LEVEL; + case cros_healthd::ThunderboltSecurityLevel::kSecureLevel: + return THUNDERBOLT_SECURITY_SECURE_LEVEL; + case cros_healthd::ThunderboltSecurityLevel::kDpOnlyLevel: + return THUNDERBOLT_SECURITY_DP_ONLY_LEVEL; + case cros_healthd::ThunderboltSecurityLevel::kUsbOnlyLevel: + return THUNDERBOLT_SECURITY_USB_ONLY_LEVEL; + case cros_healthd::ThunderboltSecurityLevel::kNoPcieLevel: + return THUNDERBOLT_SECURITY_NO_PCIE_LEVEL; + } + + NOTREACHED(); +} + +} // namespace + +CrosHealthdBusSamplerHandler::CrosHealthdBusSamplerHandler( + CrosHealthdMetricSampler::MetricType metric_type) + : metric_type_(metric_type) {} + +CrosHealthdBusSamplerHandler::~CrosHealthdBusSamplerHandler() = default; + +void CrosHealthdBusSamplerHandler::HandleResult( + cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const { + absl::optional<MetricData> metric_data; + const auto& bus_result = result->bus_result; + + if (!bus_result.is_null()) { + switch (bus_result->which()) { + case cros_healthd::BusResult::Tag::kError: { + DVLOG(1) << "cros_healthd: Error getting bus info: " + << bus_result->get_error()->msg; + break; + } + + case cros_healthd::BusResult::Tag::kBusDevices: { + for (const auto& bus_device : bus_result->get_bus_devices()) { + const auto& bus_info = bus_device->bus_info; + if (metric_type_ == CrosHealthdMetricSampler::MetricType::kInfo) { + if (bus_info->is_thunderbolt_bus_info()) { + if (!metric_data.has_value()) { + metric_data = absl::make_optional<MetricData>(); + } + auto* const thunderbolt_info_out = + metric_data->mutable_info_data() + ->mutable_bus_device_info() + ->add_thunderbolt_info(); + thunderbolt_info_out->set_security_level( + TranslateThunderboltSecurityLevel( + bus_info->get_thunderbolt_bus_info()->security_level)); + } + } else if (metric_type_ == + CrosHealthdMetricSampler::MetricType::kTelemetry) { + if (bus_info->is_usb_bus_info()) { + if (!metric_data.has_value()) { + metric_data = absl::make_optional<MetricData>(); + } + auto* const usb_telemetry_out = + metric_data->mutable_telemetry_data() + ->mutable_peripherals_telemetry() + ->add_usb_telemetry(); + usb_telemetry_out->set_vid( + bus_info->get_usb_bus_info()->vendor_id); + usb_telemetry_out->set_pid( + bus_info->get_usb_bus_info()->product_id); + usb_telemetry_out->set_class_id( + bus_info->get_usb_bus_info()->class_id); + usb_telemetry_out->set_subclass_id( + bus_info->get_usb_bus_info()->subclass_id); + usb_telemetry_out->set_vendor(bus_device->vendor_name); + usb_telemetry_out->set_name(bus_device->product_name); + if (bus_info->get_usb_bus_info()->fwupd_firmware_version_info) { + usb_telemetry_out->set_firmware_version( + bus_info->get_usb_bus_info() + ->fwupd_firmware_version_info->version); + } + } + } + } + break; + } + } + } + + std::move(callback).Run(std::move(metric_data)); +} + +} // namespace reporting
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h new file mode 100644 index 0000000..ad75b8296 --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_bus_sampler_handler.h
@@ -0,0 +1,42 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_BUS_SAMPLER_HANDLER_H_ +#define CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_BUS_SAMPLER_HANDLER_H_ + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_metric_sampler.h" +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h" +#include "chromeos/ash/services/cros_healthd/public/mojom/cros_healthd_probe.mojom.h" +#include "components/reporting/metrics/sampler.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +// Class that handles the resulting data after probing the croshealthd for the +// Bus category. +class CrosHealthdBusSamplerHandler : public CrosHealthdSamplerHandler { + public: + CrosHealthdBusSamplerHandler( + CrosHealthdMetricSampler::MetricType metric_type); + + CrosHealthdBusSamplerHandler(const CrosHealthdBusSamplerHandler&) = delete; + CrosHealthdBusSamplerHandler& operator=(const CrosHealthdBusSamplerHandler&) = + delete; + + ~CrosHealthdBusSamplerHandler() override; + + // HandleResult converts |result_| to MetricData. + void HandleResult(cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const override; + + private: + // Holds the value of the passed in Metric Type to use when processing the + // |result| parameter. + CrosHealthdMetricSampler::MetricType metric_type_; +}; + +} // namespace reporting + +#endif // CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_BUS_SAMPLER_HANDLER_H_
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.cc b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.cc new file mode 100644 index 0000000..c71e91ce --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.cc
@@ -0,0 +1,65 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h" + +#include <utility> + +#include "base/logging.h" +#include "components/reporting/metrics/sampler.h" +#include "components/reporting/proto/synced/metric_data.pb.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +CrosHealthdCpuSamplerHandler::~CrosHealthdCpuSamplerHandler() = default; + +void CrosHealthdCpuSamplerHandler::HandleResult( + cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const { + absl::optional<MetricData> metric_data; + const auto& cpu_result = result->cpu_result; + + if (!cpu_result.is_null()) { + switch (cpu_result->which()) { + case cros_healthd::CpuResult::Tag::kError: { + DVLOG(1) << "cros_healthd: Error getting CPU info: " + << cpu_result->get_error()->msg; + break; + } + + case cros_healthd::CpuResult::Tag::kCpuInfo: { + const auto& cpu_info = cpu_result->get_cpu_info(); + if (cpu_info.is_null()) { + DVLOG(1) << "Null CpuInfo from cros_healthd"; + break; + } + + // Gather keylocker info. + metric_data = absl::make_optional<MetricData>(); + auto* const keylocker_info_out = metric_data->mutable_info_data() + ->mutable_cpu_info() + ->mutable_keylocker_info(); + const auto* const keylocker_info = cpu_info->keylocker_info.get(); + if (keylocker_info) { + keylocker_info_out->set_supported(true); + keylocker_info_out->set_configured( + keylocker_info->keylocker_configured); + } else { + // If keylocker info isn't set, it is not supported on the board. + keylocker_info_out->set_supported(false); + keylocker_info_out->set_configured(false); + } + + break; + } + } + } + + std::move(callback).Run(std::move(metric_data)); +} + +} // namespace reporting
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h new file mode 100644 index 0000000..cb27f96d --- /dev/null +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_cpu_sampler_handler.h
@@ -0,0 +1,35 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_CPU_SAMPLER_HANDLER_H_ +#define CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_CPU_SAMPLER_HANDLER_H_ + +#include "chrome/browser/ash/policy/reporting/metrics_reporting/cros_healthd_sampler_handlers/cros_healthd_sampler_handler.h" +#include "chromeos/ash/services/cros_healthd/public/mojom/cros_healthd_probe.mojom.h" +#include "components/reporting/metrics/sampler.h" + +namespace reporting { + +namespace cros_healthd = ::ash::cros_healthd::mojom; + +// Class that handles the resulting data after probing the croshealthd for the +// Cpu category. +class CrosHealthdCpuSamplerHandler : public CrosHealthdSamplerHandler { + public: + CrosHealthdCpuSamplerHandler() = default; + + CrosHealthdCpuSamplerHandler(const CrosHealthdCpuSamplerHandler&) = delete; + CrosHealthdCpuSamplerHandler& operator=(const CrosHealthdCpuSamplerHandler&) = + delete; + + ~CrosHealthdCpuSamplerHandler() override; + + // HandleResult converts |result| to MetricData. + void HandleResult(cros_healthd::TelemetryInfoPtr result, + OptionalMetricCallback callback) const override; +}; + +} // namespace reporting + +#endif // CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_CROS_HEALTHD_SAMPLER_HANDLERS_CROS_HEALTHD_CPU_SAMPLER_HANDLER_H_
diff --git a/chrome/browser/ash/web_applications/os_flags_system_web_app_info.cc b/chrome/browser/ash/web_applications/os_flags_system_web_app_info.cc index c3cf3ba9..7de32a8 100644 --- a/chrome/browser/ash/web_applications/os_flags_system_web_app_info.cc +++ b/chrome/browser/ash/web_applications/os_flags_system_web_app_info.cc
@@ -12,16 +12,6 @@ #include "chrome/grit/generated_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/chromeos/styles/cros_styles.h" - -namespace { - -SkColor GetBgColor(bool use_dark_mode) { - return cros_styles::ResolveColor(cros_styles::ColorName::kBgColor, - use_dark_mode); -} - -} // namespace OsFlagsSystemWebAppDelegate::OsFlagsSystemWebAppDelegate(Profile* profile) : ash::SystemWebAppDelegate(ash::SystemWebAppType::OS_FLAGS, @@ -48,8 +38,10 @@ }, *info); - info->theme_color = GetBgColor(/*use_dark_mode=*/false); - info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true); + info->theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/false); + info->dark_mode_theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/true); info->display_mode = blink::mojom::DisplayMode::kStandalone; info->user_display_mode = web_app::UserDisplayMode::kStandalone;
diff --git a/chrome/browser/ash/web_applications/os_settings_web_app_info.cc b/chrome/browser/ash/web_applications/os_settings_web_app_info.cc index 940cb06..f1c68f9 100644 --- a/chrome/browser/ash/web_applications/os_settings_web_app_info.cc +++ b/chrome/browser/ash/web_applications/os_settings_web_app_info.cc
@@ -17,16 +17,6 @@ #include "chrome/grit/os_settings_resources.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/chromeos/styles/cros_styles.h" - -namespace { - -SkColor GetBgColor(bool use_dark_mode) { - return cros_styles::ResolveColor(cros_styles::ColorName::kBgColor, - use_dark_mode); -} - -} // namespace std::unique_ptr<WebAppInstallInfo> CreateWebAppInfoForOSSettingsSystemWebApp() { std::unique_ptr<WebAppInstallInfo> info = @@ -41,8 +31,10 @@ }, *info); - info->theme_color = GetBgColor(/*use_dark_mode=*/false); - info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true); + info->theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/false); + info->dark_mode_theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/true); info->background_color = info->theme_color; info->dark_mode_background_color = info->dark_mode_theme_color; info->display_mode = blink::mojom::DisplayMode::kStandalone;
diff --git a/chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc b/chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc index 6020fcf6..d3efc2c 100644 --- a/chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc +++ b/chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc
@@ -18,17 +18,11 @@ #include "content/public/common/url_constants.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/chromeos/styles/cros_styles.h" namespace { bool g_enable_delegate_for_testing = false; -SkColor GetBgColor(bool use_dark_mode) { - return cros_styles::ResolveColor(cros_styles::ColorName::kBgColor, - use_dark_mode); -} - } // namespace OsUrlHandlerSystemWebAppDelegate::OsUrlHandlerSystemWebAppDelegate( @@ -59,8 +53,10 @@ }, *info); - info->theme_color = GetBgColor(/*use_dark_mode=*/false); - info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true); + info->theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/false); + info->dark_mode_theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/true); info->display_mode = blink::mojom::DisplayMode::kStandalone; info->user_display_mode = web_app::UserDisplayMode::kStandalone;
diff --git a/chrome/browser/ash/web_applications/projector_system_web_app_info.cc b/chrome/browser/ash/web_applications/projector_system_web_app_info.cc index 5f2237f..ace0d38 100644 --- a/chrome/browser/ash/web_applications/projector_system_web_app_info.cc +++ b/chrome/browser/ash/web_applications/projector_system_web_app_info.cc
@@ -13,16 +13,6 @@ #include "chrome/grit/generated_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/chromeos/styles/cros_styles.h" - -namespace { - -SkColor GetBgColor(bool use_dark_mode) { - return cros_styles::ResolveColor(cros_styles::ColorName::kBgColor, - use_dark_mode); -} - -} // namespace ProjectorSystemWebAppDelegate::ProjectorSystemWebAppDelegate(Profile* profile) : ash::SystemWebAppDelegate(ash::SystemWebAppType::PROJECTOR, @@ -62,8 +52,10 @@ }, *info); - info->theme_color = GetBgColor(/*use_dark_mode=*/false); - info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true); + info->theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/false); + info->dark_mode_theme_color = + web_app::GetDefaultBackgroundColor(/*use_dark_mode=*/true); info->display_mode = blink::mojom::DisplayMode::kStandalone; info->user_display_mode = web_app::UserDisplayMode::kStandalone;
diff --git a/chrome/browser/chrome_browser_application_mac.mm b/chrome/browser/chrome_browser_application_mac.mm index 20a559f..8be2152 100644 --- a/chrome/browser/chrome_browser_application_mac.mm +++ b/chrome/browser/chrome_browser_application_mac.mm
@@ -374,7 +374,7 @@ content::BrowserAccessibilityState* accessibility_state = content::BrowserAccessibilityState::GetInstance(); if (!accessibility_state->GetAccessibilityMode().has_mode( - ui::kAXModeBasic.mode())) { + ui::kAXModeBasic.flags())) { accessibility_state->AddAccessibilityModeFlags(ui::kAXModeBasic); } return [super accessibilityRole];
diff --git a/chrome/browser/dips/BUILD.gn b/chrome/browser/dips/BUILD.gn index 7d13ac7..4e71a0b 100644 --- a/chrome/browser/dips/BUILD.gn +++ b/chrome/browser/dips/BUILD.gn
@@ -24,7 +24,10 @@ source_set("browser_tests") { testonly = true - sources = [ "dips_bounce_detector_browsertest.cc" ] + sources = [ + "dips_bounce_detector_browsertest.cc", + "dips_helper_browsertest.cc", + ] defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] @@ -32,6 +35,7 @@ "//base", "//base/test:test_support", "//chrome/browser", + "//chrome/browser/browsing_data:constants", "//chrome/browser/ui", "//chrome/test:test_support", "//components/ukm:test_support", @@ -44,11 +48,6 @@ if (is_android) { deps += [ "//chrome/test:test_support_ui_android" ] } else { - # TODO(rtarpine): make DIPSTabHelperBrowserTest run on Android. - sources += [ "dips_helper_browsertest.cc" ] - deps += [ - "//chrome/browser/browsing_data:constants", - "//chrome/test:test_support_ui", - ] + deps += [ "//chrome/test:test_support_ui" ] } }
diff --git a/chrome/browser/dips/dips_bounce_detector.cc b/chrome/browser/dips/dips_bounce_detector.cc index 318a398e..abadbd6 100644 --- a/chrome/browser/dips/dips_bounce_detector.cc +++ b/chrome/browser/dips/dips_bounce_detector.cc
@@ -274,21 +274,47 @@ } // Record this bounce in the DIPS database. - delegate_->RecordBounce(redirect.url, clock_->Now(), - redirect.access_type > CookieAccessType::kRead); + if (redirect.access_type != CookieAccessType::kUnknown) { + DIPSRecordedEvent bounce = redirect.access_type > CookieAccessType::kRead + ? DIPSRecordedEvent::kStatefulBounce + : DIPSRecordedEvent::kStatelessBounce; + delegate_->RecordEvent(bounce, redirect.url, clock_->Now()); + } RedirectCategory category = ClassifyRedirect(redirect.access_type, level); UmaHistogramBounceCategory(category, delegate_->GetCookieMode(), redirect.redirect_type); } -void DIPSWebContentsObserver::RecordBounce(const GURL& url, - const base::Time& time, - bool stateful) { - dips_service_->storage() - ->AsyncCall(stateful ? &DIPSStorage::RecordStatefulBounce - : &DIPSStorage::RecordStatelessBounce) - .WithArgs(url, time); +void DIPSWebContentsObserver::RecordEvent(DIPSRecordedEvent event, + const GURL& url, + const base::Time& time) { + switch (event) { + case DIPSRecordedEvent::kStorage: { + dips_service_->storage() + ->AsyncCall(&DIPSStorage::RecordStorage) + .WithArgs(url, time, GetCookieMode()); + return; + } + case DIPSRecordedEvent::kInteraction: { + dips_service_->storage() + ->AsyncCall(&DIPSStorage::RecordInteraction) + .WithArgs(url, time, GetCookieMode()); + return; + } + case DIPSRecordedEvent::kStatelessBounce: { + dips_service_->storage() + ->AsyncCall(&DIPSStorage::RecordStatelessBounce) + .WithArgs(url, time); + return; + } + case DIPSRecordedEvent::kStatefulBounce: { + dips_service_->storage() + ->AsyncCall(&DIPSStorage::RecordStatefulBounce) + .WithArgs(url, time); + return; + } + } } const GURL& DIPSWebContentsObserver::GetLastCommittedURL() const { @@ -401,6 +427,9 @@ void DIPSBounceDetector::OnClientCookiesAccessed(const GURL& url, CookieOperation op) { + if (op == CookieOperation::kChange) { + delegate_->RecordEvent(DIPSRecordedEvent::kStorage, url, clock_->Now()); + } if (client_detection_state_ && GetSiteForDIPS(url) == client_detection_state_->current_site) { client_detection_state_->cookie_access_type = @@ -425,6 +454,9 @@ DIPSNavigationHandle* navigation_handle, const GURL& url, CookieOperation op) { + if (op == CookieOperation::kChange) { + delegate_->RecordEvent(DIPSRecordedEvent::kStorage, url, clock_->Now()); + } ServerBounceDetectionState* state = navigation_handle->GetServerState(); if (state) { state->filter.AddAccess(url, op); @@ -494,15 +526,26 @@ client_detection_state_->cookie_access_type = access_types.back(); } } - +// TODO(kaklilu): Follow up on how this interacts with Fenced Frames. void DIPSWebContentsObserver::FrameReceivedUserActivation( content::RenderFrameHost* render_frame_host) { + // Ignore iframe activations since we only care for its associated main-frame + // interactions on the top-level site. + if (!render_frame_host->IsInPrimaryMainFrame()) + return; + detector_.OnUserActivation(); } void DIPSBounceDetector::OnUserActivation() { + GURL url = delegate_->GetLastCommittedURL(); + if (!url.SchemeIsHTTPOrHTTPS()) + return; + if (client_detection_state_.has_value()) client_detection_state_->received_user_activation = true; + + delegate_->RecordEvent(DIPSRecordedEvent::kInteraction, url, clock_->Now()); } void DIPSWebContentsObserver::WebContentsDestroyed() {
diff --git a/chrome/browser/dips/dips_bounce_detector.h b/chrome/browser/dips/dips_bounce_detector.h index 1fc16e80..4d2fda2b 100644 --- a/chrome/browser/dips/dips_bounce_detector.h +++ b/chrome/browser/dips/dips_bounce_detector.h
@@ -165,9 +165,9 @@ virtual ukm::SourceId GetPageUkmSourceId() const = 0; virtual blink::mojom::EngagementLevel GetEngagementLevel( const GURL&) const = 0; - virtual void RecordBounce(const GURL& url, - const base::Time& time, - bool stateful) = 0; + virtual void RecordEvent(DIPSRecordedEvent event, + const GURL& url, + const base::Time& time) = 0; }; // ServerBounceDetectionState gets attached to NavigationHandle (which is a @@ -228,6 +228,7 @@ DIPSBounceDetector(const DIPSBounceDetector&) = delete; DIPSBounceDetector& operator=(const DIPSBounceDetector&) = delete; + void SetClockForTesting(base::Clock* clock) { clock_ = clock; } // The following methods are based on WebContentsObserver, simplified. void DidStartNavigation(DIPSNavigationHandle* navigation_handle); void OnClientCookiesAccessed(const GURL& url, CookieOperation op); @@ -264,6 +265,10 @@ detector_.SetRedirectHandlerForTesting(handler); } + void SetClockForTesting(base::Clock* clock) { + detector_.SetClockForTesting(clock); + } + private: explicit DIPSWebContentsObserver(content::WebContents* web_contents); // So WebContentsUserData::CreateForWebContents() can call the constructor. @@ -274,9 +279,9 @@ const GURL& GetLastCommittedURL() const override; ukm::SourceId GetPageUkmSourceId() const override; blink::mojom::EngagementLevel GetEngagementLevel(const GURL&) const override; - void RecordBounce(const GURL& url, - const base::Time& time, - bool stateful) override; + void RecordEvent(DIPSRecordedEvent event, + const GURL& url, + const base::Time& time) override; // WebContentsObserver overrides: void DidStartNavigation(
diff --git a/chrome/browser/dips/dips_bounce_detector_unittest.cc b/chrome/browser/dips/dips_bounce_detector_unittest.cc index 02af8f29..d50c77e 100644 --- a/chrome/browser/dips/dips_bounce_detector_unittest.cc +++ b/chrome/browser/dips/dips_bounce_detector_unittest.cc
@@ -72,10 +72,14 @@ return iter->second; } - void RecordBounce(const GURL& url, - const base::Time& time, - bool stateful) override { - recorded_bounces_.insert(std::make_tuple(url, time, stateful)); + void RecordEvent(DIPSRecordedEvent event, + const GURL& url, + const base::Time& time) override { + if (event == DIPSRecordedEvent::kStatefulBounce || + event == DIPSRecordedEvent::kStatelessBounce) { + recorded_bounces_.insert(std::make_tuple( + url, time, event == DIPSRecordedEvent::kStatefulBounce)); + } } // Get the (committed) URL that the SourceId was generated for. @@ -176,8 +180,11 @@ void RecordBouncesAndAppendRedirects(std::vector<std::string>* redirects, const DIPSRedirectInfo& redirect, const DIPSRedirectChainInfo& chain) { - delegate_.RecordBounce(redirect.url, test_clock_.Now(), - redirect.access_type > CookieAccessType::kRead); + DCHECK(redirect.access_type != CookieAccessType::kUnknown); + delegate_.RecordEvent(redirect.access_type > CookieAccessType::kRead + ? DIPSRecordedEvent::kStatefulBounce + : DIPSRecordedEvent::kStatelessBounce, + redirect.url, test_clock_.Now()); AppendRedirect(redirects, redirect, chain); }
diff --git a/chrome/browser/dips/dips_database.cc b/chrome/browser/dips/dips_database.cc index 8adc5a0..f45bc674 100644 --- a/chrome/browser/dips/dips_database.cc +++ b/chrome/browser/dips/dips_database.cc
@@ -684,7 +684,8 @@ num_deleted += GarbageCollectExpired(); // If expiration did not purge enough entries, remove entries with the oldest - // |last_user_interaction_time| until the |purge_goal| is satisfied. + // |MAX(last_user_interaction_time,last_site_storage_time)| values until the + // |purge_goal| is satisfied. if (num_deleted < static_cast<size_t>(purge_goal)) { num_deleted += GarbageCollectOldest(purge_goal - num_deleted); }
diff --git a/chrome/browser/dips/dips_database.h b/chrome/browser/dips/dips_database.h index 517eafd48..6d7ea41 100644 --- a/chrome/browser/dips/dips_database.h +++ b/chrome/browser/dips/dips_database.h
@@ -95,8 +95,8 @@ // (useful for debugging). size_t GarbageCollect(); - // Removes entries for sites without user interaction or site storage within - // |kMaxAge|. Returns the number of entries deleted. + // Removes entries for sites without user interaction within |kMaxAge|. + // Returns the number of entries deleted. size_t GarbageCollectExpired(); // Removes the |purge_goal| entries with the oldest
diff --git a/chrome/browser/dips/dips_helper.cc b/chrome/browser/dips/dips_helper.cc deleted file mode 100644 index 54c9842..0000000 --- a/chrome/browser/dips/dips_helper.cc +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/dips/dips_helper.h" - -#include <utility> - -#include "base/time/default_clock.h" -#include "chrome/browser/dips/dips_service.h" -#include "chrome/browser/dips/dips_utils.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/cookie_access_details.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/render_frame_host.h" - -namespace { - -// The Clock that a new DIPSTabHelper will use internally. Exposed as a global -// so that browser tests (which don't call the DIPSTabHelper constructor -// directly) can inject a fake clock. -base::Clock* g_clock = nullptr; - -} // namespace - -DIPSTabHelper::DIPSTabHelper(content::WebContents* web_contents, - DIPSService* service) - : content::WebContentsObserver(web_contents), - content::WebContentsUserData<DIPSTabHelper>(*web_contents), - service_(service), - clock_(g_clock ? g_clock : base::DefaultClock::GetInstance()) { - DCHECK(service_); -} - -DIPSCookieMode DIPSTabHelper::GetCookieMode() const { - return GetDIPSCookieMode( - web_contents()->GetBrowserContext()->IsOffTheRecord(), - service_->ShouldBlockThirdPartyCookies()); -} - -/* static */ -base::Clock* DIPSTabHelper::SetClockForTesting(base::Clock* clock) { - return std::exchange(g_clock, clock); -} - -void DIPSTabHelper::RecordStorage(const GURL& url) { - base::Time now = clock_->Now(); - DIPSCookieMode mode = GetCookieMode(); - - service_->storage() - ->AsyncCall(&DIPSStorage::RecordStorage) - .WithArgs(url, now, mode); -} - -void DIPSTabHelper::RecordInteraction(const GURL& url) { - base::Time now = clock_->Now(); - DIPSCookieMode mode = GetCookieMode(); - - service_->storage() - ->AsyncCall(&DIPSStorage::RecordInteraction) - .WithArgs(url, now, mode); -} - -void DIPSTabHelper::OnCookiesAccessed( - content::RenderFrameHost* render_frame_host, - const content::CookieAccessDetails& details) { - if (!render_frame_host->IsInPrimaryMainFrame()) - return; - if (details.type == content::CookieAccessDetails::Type::kChange) { - RecordStorage(details.url); - } -} - -void DIPSTabHelper::OnCookiesAccessed( - content::NavigationHandle* handle, - const content::CookieAccessDetails& details) { - if (!handle->IsInPrimaryMainFrame()) - return; - if (details.type == content::CookieAccessDetails::Type::kChange) { - RecordStorage(details.url); - } -} - -// TODO(kaklilu): Follow up on how this interacts with Fenced Frames. -void DIPSTabHelper::FrameReceivedUserActivation( - content::RenderFrameHost* render_frame_host) { - // Ignore iframe activations since we only care for its associated main-frame - // interactions on the top-level site. - if (!render_frame_host->IsInPrimaryMainFrame()) - return; - - const GURL& url = render_frame_host->GetLastCommittedURL(); - - if (!url.SchemeIsHTTPOrHTTPS()) { - return; - } - - RecordInteraction(url); -} - -WEB_CONTENTS_USER_DATA_KEY_IMPL(DIPSTabHelper);
diff --git a/chrome/browser/dips/dips_helper.h b/chrome/browser/dips/dips_helper.h deleted file mode 100644 index e97c0a1..0000000 --- a/chrome/browser/dips/dips_helper.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2022 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_DIPS_DIPS_HELPER_H_ -#define CHROME_BROWSER_DIPS_DIPS_HELPER_H_ - -#include "chrome/browser/dips/dips_utils.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_contents_user_data.h" - -namespace base { -class Clock; -} - -class DIPSService; - -// A WebContentsObserver subclass that listens for storage and user interaction -// events that DIPSService is interested in. -class DIPSTabHelper : public content::WebContentsObserver, - public content::WebContentsUserData<DIPSTabHelper> { - public: - DIPSTabHelper(const DIPSTabHelper&) = delete; - DIPSTabHelper& operator=(const DIPSTabHelper&) = delete; - - // Record that |url| wrote to storage. - void RecordStorage(const GURL& url); - // Record that the user interacted on |url| . - void RecordInteraction(const GURL& url); - - static base::Clock* SetClockForTesting(base::Clock* clock); - - private: - explicit DIPSTabHelper(content::WebContents* web_contents, - DIPSService* service); - - DIPSCookieMode GetCookieMode() const; - - // So WebContentsUserData::CreateForWebContents() can call the constructor. - friend class content::WebContentsUserData<DIPSTabHelper>; - - // WebContentsObserver overrides. - void FrameReceivedUserActivation( - content::RenderFrameHost* render_frame_host) override; - void OnCookiesAccessed(content::RenderFrameHost* render_frame_host, - const content::CookieAccessDetails& details) override; - void OnCookiesAccessed(content::NavigationHandle* navigation_handle, - const content::CookieAccessDetails& details) override; - - raw_ptr<DIPSService> service_; - raw_ptr<base::Clock> clock_; - - WEB_CONTENTS_USER_DATA_KEY_DECL(); -}; - -#endif // CHROME_BROWSER_DIPS_DIPS_HELPER_H_
diff --git a/chrome/browser/dips/dips_helper_browsertest.cc b/chrome/browser/dips/dips_helper_browsertest.cc index 4f5b457..f696797 100644 --- a/chrome/browser/dips/dips_helper_browsertest.cc +++ b/chrome/browser/dips/dips_helper_browsertest.cc
@@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/dips/dips_helper.h" +#include "chrome/browser/dips/dips_bounce_detector.h" #include "base/memory/raw_ptr.h" +#include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "base/time/time.h" #include "chrome/browser/browsing_data/browsing_data_important_sites_util.h" @@ -16,16 +18,20 @@ #include "chrome/browser/dips/dips_service_factory.h" #include "chrome/browser/dips/dips_storage.h" #include "chrome/browser/dips/dips_utils.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" +#include "chrome/test/base/chrome_test_utils.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/hit_test_region_observer.h" #include "net/dns/mock_host_resolver.h" #include "third_party/blink/public/common/switches.h" +#if !BUILDFLAG(IS_ANDROID) +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/ui_test_utils.h" +#endif // !BUILDFLAG(IS_ANDROID) + namespace { class UserActivationObserver : public content::WebContentsObserver { @@ -81,12 +87,13 @@ "Privacy.DIPS.TimeFromStorageToInteraction.Standard"; constexpr char kTimeToStorage[] = "Privacy.DIPS.TimeFromInteractionToStorage.Standard"; +#if !BUILDFLAG(IS_ANDROID) constexpr char kTimeToInteraction_OTR_Block3PC[] = "Privacy.DIPS.TimeFromStorageToInteraction.OffTheRecord_Block3PC"; - +#endif } // namespace -class DIPSTabHelperBrowserTest : public InProcessBrowserTest, +class DIPSTabHelperBrowserTest : public PlatformBrowserTest, public testing::WithParamInterface<bool> { protected: void SetUp() override { @@ -94,7 +101,7 @@ scoped_feature_list_.InitAndEnableFeatureWithParameters( dips::kFeature, {{"persist_database", "true"}}); } - InProcessBrowserTest::SetUp(); + PlatformBrowserTest::SetUp(); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -102,22 +109,16 @@ command_line->AppendSwitch(blink::switches::kAllowPreCommitInput); } - void SetUpInProcessBrowserTestFixture() override { - DIPSTabHelper::SetClockForTesting(&test_clock_); - } - void SetUpOnMainThread() override { ASSERT_TRUE(embedded_test_server()->Start()); host_resolver()->AddRule("a.test", "127.0.0.1"); host_resolver()->AddRule("b.test", "127.0.0.1"); - } - - void TearDownInProcessBrowserTestFixture() override { - DIPSTabHelper::SetClockForTesting(nullptr); + DIPSWebContentsObserver::FromWebContents(GetActiveWebContents()) + ->SetClockForTesting(&test_clock_); } content::WebContents* GetActiveWebContents() { - return browser()->tab_strip_model()->GetActiveWebContents(); + return chrome_test_utils::GetActiveWebContents(this); } void BlockUntilHelperProcessesPendingRequests() { @@ -153,6 +154,7 @@ } bool IsPersistentStorageEnabled() { return GetParam(); } + base::Clock* test_clock() { return &test_clock_; } private: base::SimpleTestClock test_clock_; @@ -201,7 +203,14 @@ base::Time frame_interaction_time = base::Time::FromDoubleT(2); SetDIPSTime(frame_interaction_time); UserActivationObserver observer_b(web_contents, iframe); + + // TODO(crbug.com/1386142): Remove the ExecJs workaround once + // SimulateMouseClickOrTapElementWithId is able to activate iframes on Android +#if !BUILDFLAG(IS_ANDROID) content::SimulateMouseClickOrTapElementWithId(web_contents, kIframeId); +#else + ASSERT_TRUE(content::ExecJs(iframe, "// empty script to activate iframe")); +#endif observer_b.Wait(); // User interaction on the top-level is updated by interacting with b.test @@ -224,7 +233,7 @@ SetDIPSTime(time); // Navigate to a.test. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); content::RenderFrameHost* frame = web_contents->GetPrimaryMainFrame(); content::WaitForHitTestData(frame); // Wait until we can click. @@ -265,7 +274,8 @@ // cookie, the cookie needs to be SameSite=None and Secure. net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES); - https_server.AddDefaultHandlers(GetChromeTestDataDir()); + https_server.AddDefaultHandlers( + base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(https_server.Start()); GURL url_a = embedded_test_server()->GetURL("a.test", "/iframe_blank.html"); @@ -275,7 +285,7 @@ content::WebContents* web_contents = GetActiveWebContents(); // The top-level page is on a.test, containing an iframe pointing at b.test. - ASSERT_TRUE(content::NavigateToURL(web_contents, url_a)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url_a, 1); ASSERT_TRUE(content::NavigateIframeToURL(web_contents, kIframeId, url_b)); content::RenderFrameHost* iframe = content::FrameMatchingPredicate( @@ -309,7 +319,8 @@ SetDIPSTime(time); // Navigating to this URL sets a cookie. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(GetActiveWebContents(), + url, 1); // One instance of site storage is recorded. absl::optional<StateValue> state_1 = GetDIPSState(url); @@ -321,7 +332,8 @@ SetDIPSTime(time + base::Seconds(10)); // Navigate to the URL again to rewrite the cookie. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(GetActiveWebContents(), + url, 1); // A second, different, instance of site storage is recorded for the same // site. @@ -343,7 +355,7 @@ SetDIPSTime(time); // Navigating to this URL sets a cookie. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); // Wait until we can click. content::WaitForHitTestData(web_contents->GetPrimaryMainFrame()); BlockUntilHelperProcessesPendingRequests(); @@ -365,16 +377,20 @@ IN_PROC_BROWSER_TEST_P(DIPSTabHelperBrowserTest, Histograms_StorageThenClick_Incognito) { +// TODO(crbug.com/1380410): Enable this test on Android once the logic to +// create an Incognito browser without regard to platform is public. +#if !BUILDFLAG(IS_ANDROID) base::HistogramTester histograms; GURL url = embedded_test_server()->GetURL("a.test", "/set-cookie?foo=bar"); base::Time time = base::Time::FromDoubleT(1); Browser* browser = CreateIncognitoBrowser(); content::WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); - + DIPSWebContentsObserver::FromWebContents(web_contents) + ->SetClockForTesting(test_clock()); SetDIPSTime(time); // Navigating to this URL sets a cookie. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser, url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); // Wait until we can click. content::WaitForHitTestData(web_contents->GetPrimaryMainFrame()); BlockUntilHelperProcessesPendingRequests(); @@ -396,6 +412,7 @@ histograms.ExpectTotalCount(kTimeToStorage, 0); histograms.ExpectUniqueTimeSample(kTimeToInteraction_OTR_Block3PC, base::Seconds(10), 1); +#endif } IN_PROC_BROWSER_TEST_P(DIPSTabHelperBrowserTest, Histograms_ClickThenStorage) { @@ -403,8 +420,9 @@ base::Time time = base::Time::FromDoubleT(1); content::WebContents* web_contents = GetActiveWebContents(); - ASSERT_TRUE(ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("a.test", "/title1.html"))); + content::NavigateToURLBlockUntilNavigationsComplete( + web_contents, embedded_test_server()->GetURL("a.test", "/title1.html"), + 1); content::RenderFrameHost* frame = web_contents->GetPrimaryMainFrame(); content::WaitForHitTestData(frame); // wait until we can click. SetDIPSTime(time); @@ -438,12 +456,12 @@ SetDIPSTime(time); // Navigating to this URL sets a cookie. - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); BlockUntilHelperProcessesPendingRequests(); // Navigate to the URL, setting the cookie again. SetDIPSTime(time + base::Seconds(3)); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); content::RenderFrameHost* frame = web_contents->GetPrimaryMainFrame(); // Wait until we can click. content::WaitForHitTestData(frame); @@ -482,7 +500,7 @@ base::Time time = base::Time::FromDoubleT(1); content::WebContents* web_contents = GetActiveWebContents(); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + content::NavigateToURLBlockUntilNavigationsComplete(web_contents, url, 1); content::RenderFrameHost* frame = web_contents->GetPrimaryMainFrame(); content::WaitForHitTestData(frame); // Wait until we can click. @@ -529,6 +547,8 @@ histograms.ExpectUniqueTimeSample(kTimeToStorage, base::Seconds(7), 1); } +// TODO(crbug.com/654704): Android does not support PRE_ tests. +#if !BUILDFLAG(IS_ANDROID) IN_PROC_BROWSER_TEST_P(DIPSTabHelperBrowserTest, PRE_PrepopulateTest) { // Simulate the user typing the URL to visit the page, which will record site // engagement. @@ -586,3 +606,4 @@ absl::optional<StateValue> state_final = GetDIPSState(GURL("http://a.test")); EXPECT_FALSE(state_final.has_value()); } +#endif // !BUILDFLAG(IS_ANDROID)
diff --git a/chrome/browser/dips/dips_utils.h b/chrome/browser/dips/dips_utils.h index 7de35e0..ae534c2 100644 --- a/chrome/browser/dips/dips_utils.h +++ b/chrome/browser/dips/dips_utils.h
@@ -129,7 +129,14 @@ // Returns an opaque value representing the "privacy boundary" that the URL // belongs to. Currently returns eTLD+1, but this is an implementation detail -// and may change (e.g. after adding support for First-Party Sets). +// and may change. std::string GetSiteForDIPS(const GURL& url); +enum class DIPSRecordedEvent { + kStorage, + kInteraction, + kStatelessBounce, + kStatefulBounce, +}; + #endif // CHROME_BROWSER_DIPS_DIPS_UTILS_H_
diff --git a/chrome/browser/download/download_item_warning_data.cc b/chrome/browser/download/download_item_warning_data.cc index 25d0db3..5250c69 100644 --- a/chrome/browser/download/download_item_warning_data.cc +++ b/chrome/browser/download/download_item_warning_data.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/download/download_item_warning_data.h" +#include "base/metrics/histogram_functions.h" #include "components/download/public/common/download_item.h" using download::DownloadItem; @@ -15,7 +16,32 @@ namespace { constexpr int kWarningActionEventMaxLength = 20; + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class AddWarningActionEventOutcome { + // `download` was nullptr. This should never happen. + NOT_ADDED_MISSING_DOWNLOAD = 0, + // The first warning shown event is already logged so it is not logged this + // time. + NOT_ADDED_WARNING_SHOWN_ALREADY_LOGGED = 1, + // The warning action event is not added because the first warning shown event + // was not logged before. + NOT_ADDED_MISSING_FIRST_WARNING = 2, + // The warning action event is not added because it exceeds the max length. + NOT_ADDED_EXCEED_MAX_LENGTH = 3, + // The first warning shown event is successfully added. + ADDED_WARNING_FIRST_SHOWN = 4, + // The warning action event is successfully added. + ADDED_WARNING_ACTION = 5, + kMaxValue = ADDED_WARNING_ACTION +}; + +void RecordAddWarningActionEventOutcome(AddWarningActionEventOutcome outcome) { + base::UmaHistogramEnumeration( + "Download.WarningData.AddWarningActionEventOutcome", outcome); } +} // namespace // static const char DownloadItemWarningData::kKey[] = "DownloadItemWarningData key"; @@ -35,8 +61,9 @@ void DownloadItemWarningData::AddWarningActionEvent(DownloadItem* download, WarningSurface surface, WarningAction action) { - // TODO(crbug.com/1363368): Add a histogram to log the result before return. if (!download) { + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::NOT_ADDED_MISSING_DOWNLOAD); return; } DownloadItemWarningData* data = @@ -47,14 +74,23 @@ } if (action == WarningAction::SHOWN) { if (data->warning_first_shown_time_.is_null()) { + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::ADDED_WARNING_FIRST_SHOWN); data->warning_first_shown_time_ = base::Time::Now(); + } else { + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::NOT_ADDED_WARNING_SHOWN_ALREADY_LOGGED); } return; } if (data->warning_first_shown_time_.is_null()) { + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::NOT_ADDED_MISSING_FIRST_WARNING); return; } if (data->action_events_.size() >= kWarningActionEventMaxLength) { + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::NOT_ADDED_EXCEED_MAX_LENGTH); return; } int64_t action_latency = @@ -64,6 +100,8 @@ DCHECK_NE(WarningAction::SHOWN, action); data->action_events_.emplace_back(surface, action, action_latency, is_terminal_action); + RecordAddWarningActionEventOutcome( + AddWarningActionEventOutcome::ADDED_WARNING_ACTION); } // static
diff --git a/chrome/browser/download/notification/download_item_notification.cc b/chrome/browser/download/notification/download_item_notification.cc index 7c85c3a2..feae094 100644 --- a/chrome/browser/download/notification/download_item_notification.cc +++ b/chrome/browser/download/notification/download_item_notification.cc
@@ -15,6 +15,7 @@ #include "base/files/file_util.h" #include "base/i18n/rtl.h" #include "base/metrics/user_metrics.h" +#include "base/strings/escape.h" #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" #include "base/time/time.h" @@ -953,8 +954,12 @@ break; case DownloadCommands::PLATFORM_OPEN: #if BUILDFLAG(IS_CHROMEOS_ASH) - return base::UTF8ToUTF16( - ash::features::kGalleryAppPdfEditNotificationText.Get()); + // If a flag is specified by chrome://flags UI, flags_state.cc escape + // params, i.e. a space is converted to a plus. Unescape the string for + // the case. + return base::UTF8ToUTF16(base::UnescapeURLComponent( + ash::features::kGalleryAppPdfEditNotificationText.Get(), + base::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); #else NOTREACHED(); return std::u16string();
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index cf14d148..06c80ac 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -80,8 +80,6 @@ "api/chrome_device_permissions_prompt.h", "api/chrome_extensions_api_client.cc", "api/chrome_extensions_api_client.h", - "api/command_line_private/command_line_private_api.cc", - "api/command_line_private/command_line_private_api.h", "api/commands/command_service.cc", "api/commands/command_service.h", "api/commands/commands.cc", @@ -250,8 +248,6 @@ "api/messaging/native_messaging_policy_handler.h", "api/metrics_private/chrome_metrics_private_delegate.cc", "api/metrics_private/chrome_metrics_private_delegate.h", - "api/module/module.cc", - "api/module/module.h", "api/networking_private/networking_private_ui_delegate_factory_impl.cc", "api/networking_private/networking_private_ui_delegate_factory_impl.h", "api/notifications/extension_notification_display_helper.cc", @@ -266,8 +262,6 @@ "api/omnibox/omnibox_api.h", "api/omnibox/suggestion_parser.cc", "api/omnibox/suggestion_parser.h", - "api/page_capture/page_capture_api.cc", - "api/page_capture/page_capture_api.h", "api/passwords_private/password_check_delegate.cc", "api/passwords_private/password_check_delegate.h", "api/passwords_private/passwords_private_api.cc",
diff --git a/chrome/browser/extensions/api/BUILD.gn b/chrome/browser/extensions/api/BUILD.gn index dd351317..ad96d79 100644 --- a/chrome/browser/extensions/api/BUILD.gn +++ b/chrome/browser/extensions/api/BUILD.gn
@@ -23,7 +23,12 @@ # The collection of API implementations. group("api_implementations") { # TODO(crbug.com/1381603): Add more API implementations here. - public_deps = [ "//chrome/browser/extensions/api/scripting" ] + public_deps = [ + "//chrome/browser/extensions/api/command_line_private", + "//chrome/browser/extensions/api/module", + "//chrome/browser/extensions/api/page_capture", + "//chrome/browser/extensions/api/scripting", + ] } # The step necessary to generate the code to register the corresponding
diff --git a/chrome/browser/extensions/api/command_line_private/BUILD.gn b/chrome/browser/extensions/api/command_line_private/BUILD.gn new file mode 100644 index 0000000..bf49dd038c --- /dev/null +++ b/chrome/browser/extensions/api/command_line_private/BUILD.gn
@@ -0,0 +1,21 @@ +# Copyright 2022 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//extensions/buildflags/buildflags.gni") + +assert(enable_extensions, + "Cannot depend on extensions because enable_extensions=false.") + +source_set("command_line_private") { + sources = [ + "command_line_private_api.cc", + "command_line_private_api.h", + ] + + deps = [ + "//base", + "//chrome/common/extensions/api", + "//extensions/browser", + ] +}
diff --git a/chrome/browser/extensions/api/module/BUILD.gn b/chrome/browser/extensions/api/module/BUILD.gn new file mode 100644 index 0000000..2d45754 --- /dev/null +++ b/chrome/browser/extensions/api/module/BUILD.gn
@@ -0,0 +1,24 @@ +# Copyright 2022 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//extensions/buildflags/buildflags.gni") + +assert(enable_extensions, + "Cannot depend on extensions because enable_extensions=false.") + +source_set("module") { + sources = [ + "module.cc", + "module.h", + ] + + deps = [ + "//base", + "//chrome/browser/extensions", + "//chrome/browser/profiles:profile", + "//content/public/browser", + "//extensions/browser", + "//extensions/common", + ] +}
diff --git a/chrome/browser/extensions/api/page_capture/BUILD.gn b/chrome/browser/extensions/api/page_capture/BUILD.gn new file mode 100644 index 0000000..139a53c3 --- /dev/null +++ b/chrome/browser/extensions/api/page_capture/BUILD.gn
@@ -0,0 +1,27 @@ +# Copyright 2022 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//extensions/buildflags/buildflags.gni") + +assert(enable_extensions, + "Cannot depend on extensions because enable_extensions=false.") + +source_set("page_capture") { + sources = [ + "page_capture_api.cc", + "page_capture_api.h", + ] + + deps = [ + "//base", + "//build:chromeos_buildflags", + "//chrome/browser/extensions", + "//chrome/common/extensions/api", + "//components/sessions", + "//content/public/browser", + "//extensions/browser", + "//extensions/common", + "//storage/browser", + ] +}
diff --git a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc index 1d9198d..bad867f5 100644 --- a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
@@ -584,10 +584,7 @@ features.Append(GenerateFeatureFlag( "roundCorners", base::FeatureList::IsEnabled( chromeos::features::kVirtualKeyboardRoundCorners))); - features.Append(GenerateFeatureFlag( - "systemchinesephysicaltyping", - base::FeatureList::IsEnabled( - chromeos::features::kSystemChinesePhysicalTyping))); + features.Append(GenerateFeatureFlag("systemchinesephysicaltyping", true)); features.Append(GenerateFeatureFlag( "systemjapanesephysicaltyping", base::FeatureList::IsEnabled(
diff --git a/chrome/browser/extensions/permissions_updater.cc b/chrome/browser/extensions/permissions_updater.cc index 9e37238..33049e3 100644 --- a/chrome/browser/extensions/permissions_updater.cc +++ b/chrome/browser/extensions/permissions_updater.cc
@@ -549,8 +549,7 @@ desired_permissions = &extension->permissions_data()->active_permissions(); } else { desired_permissions_wrapper = - PermissionsManager::Get(browser_context_) - ->GetBoundedExtensionDesiredPermissions(*extension); + permissions_manager->GetBoundedExtensionDesiredPermissions(*extension); desired_permissions = desired_permissions_wrapper.get(); }
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sections/StickySectionHeaderView.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sections/StickySectionHeaderView.java index c078bcd..f02e653 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sections/StickySectionHeaderView.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sections/StickySectionHeaderView.java
@@ -39,7 +39,7 @@ } /** - * This method is to set/update sticky heaer's margin. + * This method is to set/update the sticky header's margin. * @param marginValue the sticky header's margin */ @Override
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinator.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinator.java index 4115873..361885d 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinator.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinator.java
@@ -17,6 +17,7 @@ import org.chromium.chrome.browser.feed.StreamKind; import org.chromium.chrome.browser.feed.v2.ContentOrder; import org.chromium.chrome.browser.feed.v2.FeedUserActionType; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.components.browser_ui.widget.chips.ChipProperties; import org.chromium.components.browser_ui.widget.chips.ChipView; import org.chromium.components.browser_ui.widget.chips.ChipViewBinder; @@ -45,7 +46,7 @@ } private final FeedOptionsView mView; - private final FeedOptionsView mStickyHeaderOptionsView; + private @Nullable FeedOptionsView mStickyHeaderOptionsView; private final Context mContext; private List<PropertyModel> mChipModels; private PropertyModel mModel; @@ -58,23 +59,29 @@ this(context, (FeedOptionsView) LayoutInflater.from(context).inflate( R.layout.feed_options_panel, null, false), - (FeedOptionsView) LayoutInflater.from(context).inflate( - R.layout.feed_options_panel, null, false)); + ChromeFeatureList.isEnabled(ChromeFeatureList.FEED_HEADER_STICK_TO_TOP) + ? (FeedOptionsView) LayoutInflater.from(context).inflate( + R.layout.feed_options_panel, null, false) + : null); } @VisibleForTesting - FeedOptionsCoordinator( - Context context, FeedOptionsView view, FeedOptionsView stickyHeaderOptionsView) { + FeedOptionsCoordinator(Context context, FeedOptionsView view, + @Nullable FeedOptionsView stickyHeaderOptionsView) { mContext = context; mView = view; - mStickyHeaderOptionsView = stickyHeaderOptionsView; - mChipModels = createAndBindChips(); mModel = new PropertyModel.Builder(FeedOptionsProperties.getAllKeys()) .with(FeedOptionsProperties.VISIBILITY_KEY, false) .build(); PropertyModelChangeProcessor.create(mModel, mView, FeedOptionsCoordinator::bind); - PropertyModelChangeProcessor.create( - mModel, mStickyHeaderOptionsView, FeedOptionsCoordinator::bind); + + if (stickyHeaderOptionsView != null) { + mStickyHeaderOptionsView = stickyHeaderOptionsView; + PropertyModelChangeProcessor.create( + mModel, mStickyHeaderOptionsView, FeedOptionsCoordinator::bind); + } + // Create chip models last, after all expected option views are created. + mChipModels = createAndBindChips(); } /** Sets listener for feed options. */ @@ -89,6 +96,7 @@ /** Returns the options view which should be added to the sticky header. */ public View getStickyHeaderOptionsView() { + assert mStickyHeaderOptionsView != null : "mStickyHeaderOptionsView is null!"; return mStickyHeaderOptionsView; } @@ -163,9 +171,12 @@ for (PropertyModel model : chipModels) { ChipView chip = mView.createNewChip(); - ChipView stickyHeaderChip = mStickyHeaderOptionsView.createNewChip(); PropertyModelChangeProcessor.create(model, chip, ChipViewBinder::bind); - PropertyModelChangeProcessor.create(model, stickyHeaderChip, ChipViewBinder::bind); + + if (mStickyHeaderOptionsView != null) { + ChipView stickyHeaderChip = mStickyHeaderOptionsView.createNewChip(); + PropertyModelChangeProcessor.create(model, stickyHeaderChip, ChipViewBinder::bind); + } } return chipModels; }
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinatorTest.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinatorTest.java index f4ac9eae..413deeb 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinatorTest.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/sort_ui/FeedOptionsCoordinatorTest.java
@@ -4,12 +4,16 @@ package org.chromium.chrome.browser.feed.sort_ui; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import static org.chromium.chrome.browser.flags.ChromeFeatureList.FEED_HEADER_STICK_TO_TOP; + import android.app.Activity; import android.content.Context; +import android.view.View; import android.widget.TextView; import org.junit.Before; @@ -25,6 +29,8 @@ import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.feed.FeedServiceBridge; import org.chromium.chrome.browser.feed.v2.ContentOrder; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.test.util.browser.Features; import org.chromium.components.browser_ui.widget.chips.ChipProperties; import org.chromium.components.browser_ui.widget.chips.ChipView; import org.chromium.ui.modelutil.PropertyModel; @@ -37,6 +43,7 @@ */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) +@Features.EnableFeatures({ChromeFeatureList.FEED_HEADER_STICK_TO_TOP}) public class FeedOptionsCoordinatorTest { @Mock private FeedServiceBridge.Natives mFeedServiceBridgeJniMock; @@ -144,4 +151,17 @@ assertTrue(chipModels.get(0).get(ChipProperties.SELECTED)); assertTrue(listenerCalled.get()); } + + @Features.DisableFeatures({FEED_HEADER_STICK_TO_TOP}) + @Test + public void testStickyHeaderReturnsNullWhenFlagIsOff() { + mCoordinator = new FeedOptionsCoordinator(mContext, mView, null); + View stickyHeaderOptionsView = null; + try { + stickyHeaderOptionsView = mCoordinator.getStickyHeaderOptionsView(); + } catch (AssertionError e) { + // Success when the assertions are enabled. + } + assertEquals(null, stickyHeaderOptionsView); + } }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 56013f3..ab5ed0ca 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -861,6 +861,11 @@ "expiry_milestone": 110 }, { + "name": "cct-resizable-side-sheet", + "owners": ["kgrosu", "jinsukkim", "twellington"], + "expiry_milestone": 121 + }, + { "name": "cct-retaining-state-in-memory", "owners": ["katzz", "wenyufu"], "expiry_milestone": 116 @@ -961,7 +966,7 @@ { "name": "clear-cross-site-cross-browsing-context-group-window-name", "owners": [ "shuuran", "kaustubhag" ], - "expiry_milestone": 110 + "expiry_milestone": 115 }, { "name": "clear-identity-in-can-make-payment", @@ -1946,20 +1951,10 @@ "expiry_milestone": 120 }, { - "name": "enable-cros-system-chinese-physical-typing", - "owners": [ "shend", "essential-inputs-team@google.com" ], - "expiry_milestone": 111 - }, - { "name": "enable-cros-system-japanese-physical-typing", "owners": [ "keithlee", "essential-inputs-team@google.com" ], "expiry_milestone": 116 }, - { - "name": "enable-cros-system-transliteration-physical-typing", - "owners": [ "shend", "essential-inputs-team@google.com" ], - "expiry_milestone": 111 - }, { "name": "enable-cros-touch-text-editing-redesign", "owners": [ "michellegc", "essential-inputs-team@google.com" ], @@ -3878,6 +3873,11 @@ "expiry_milestone":120 }, { + "name": "gallery-app-pdf-edit-notification", + "owners": ["yawano@google.com", "assistive-eng@google.com"], + "expiry_milestone": 120 + }, + { "name": "gesture-properties-dbus-service", "owners": [ "hcutts", "chromeos-tango@google.com" ], // Used by developers for debugging and input device tuning. @@ -4077,11 +4077,6 @@ "expiry_milestone": 110 }, { - "name": "improved-desks-keyboard-shortcuts", - "owners": [ "zxdan", "janetmac"], - "expiry_milestone": 101 - }, - { "name": "improved-keyboard-shortcuts", "owners": [ "zentaro@google.com", "jimmyxgong@google.com", "cros-peripherals@google.com"], @@ -6827,7 +6822,7 @@ { "name": "use-winrt-midi-api", "owners": [ "toyoshim", "mjwilson", "deviceapi-team@google.com" ], - "expiry_milestone": 110 + "expiry_milestone": 112 }, { "name": "use-xps-for-printing",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 3b2a2cb5..2246275 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1499,6 +1499,12 @@ "If set, use the full (non-reduced) user agent string for the User-Agent " "request header and the JS APIs."; +const char kGalleryAppPdfEditNotificationName[] = + "Gallery App Pdf Edit Notification"; +const char kGalleryAppPdfEditNotificationDescription[] = + "Shows a notification to provide an option to open Gallery app for a " + "downloaded pdf file"; + const char kGlobalMediaControlsForCastName[] = "Global Media Controls for Cast"; const char kGlobalMediaControlsForCastDescription[] = "Shows Cast sessions in the Global Media Controls UI."; @@ -1654,13 +1660,6 @@ "resets the counter. The threshold is configurable via the " "MinGuResponsesToIgnoreKey feature parameter."; -const char kImprovedDesksKeyboardShortcutsName[] = - "Enable improved desks keyboard shortcuts"; -const char kImprovedDesksKeyboardShortcutsDescription[] = - "Enable keyboard shortcuts for activating desks at specific indices and " - "toggling whether a window is assigned to all desks. Must be used with " - "the #improved-keyboard-shortcuts flag."; - const char kImprovedKeyboardShortcutsName[] = "Enable improved keyboard shortcuts"; const char kImprovedKeyboardShortcutsDescription[] = @@ -3474,6 +3473,11 @@ "of the screen height, otherwise the maximum height is 100% of the screen " "height. In both cases, Custom Tabs will yield to the top status bar when " "at full stop"; +const char kCCTResizableAlwaysShowNavBarButtonsName[] = + "Always show the navigation bar buttons"; +const char kCCTResizableAlwaysShowNavBarButtonsDescription[] = + "The navigation bar buttons will remain visible while a Partial Chrome " + "Custom Tab is being resized."; const char kCCTResizableAllowResizeByUserGestureName[] = "Bottom sheet Custom Tabs allow resize by user gesture"; const char kCCTResizableAllowResizeByUserGestureDescription[] = @@ -3486,11 +3490,10 @@ "Bottom sheet Custom Tabs (third party)"; const char kCCTResizableForThirdPartiesDescription[] = "Enable bottom sheet Custom Tabs for third party apps."; -const char kCCTResizableAlwaysShowNavBarButtonsName[] = - "Always show the navigation bar buttons"; -const char kCCTResizableAlwaysShowNavBarButtonsDescription[] = - "The navigation bar buttons will remain visible while a Partial Chrome " - "Custom Tab is being resized."; +const char kCCTResizableSideSheetName[] = "Side sheet Custom Tabs"; +const char kCCTResizableSideSheetDescription[] = + "Enable side sheet Custom Tabs"; + const char kCCTRetainingStateInMemoryName[] = "Enable restoring of previous Custom Tab session"; const char kCCTRetainingStateInMemoryDescription[] = @@ -4679,6 +4682,11 @@ "Enables the ChromeOS APN Revamp, which updates cellular network APN " "system UI and related infrastructure."; +const char kAppDiscoveryForOobeName[] = + "OOBE app recommendations with App Discovery Service."; +const char kAppDiscoveryForOobeDescription[] = + "Use the App Discovery Service to request recommended apps for OOBE."; + const char kAppProvisioningStaticName[] = "App Provisioning with static server setup."; const char kAppProvisioningStaticDescription[] = @@ -5917,12 +5925,6 @@ "bootstrapping the Seccomp BPF sandbox. Can be overridden by " "#force-spectre-variant2-mitigation."; -const char kSystemChinesePhysicalTypingName[] = - "Use system IME for Chinese typing"; -const char kSystemChinesePhysicalTypingDescription[] = - "Use the system input engine instead of the Chrome extension for physical " - "typing in Chinese."; - const char kSystemJapanesePhysicalTypingName[] = "Use system IME for Japanese typing"; const char kSystemJapanesePhysicalTypingDescription[] = @@ -5930,12 +5932,6 @@ "typing in Japanese. This also replaces the Japanese extension settings " "page with one built into the UI and migrates the data to a new location."; -const char kSystemTransliterationPhysicalTypingName[] = - "Use system IME for Transliteration typing"; -const char kSystemTransliterationPhysicalTypingDescription[] = - "Use the system input engine instead of the Chrome extension for physical " - "typing in transliteration input methods."; - const char kQuickSettingsNetworkRevampName[] = "Enables the Quick Settings Network revamp."; const char kQuickSettingsNetworkRevampDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 910d5bb..8adb006 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -843,6 +843,9 @@ extern const char kFullUserAgentName[]; extern const char kFullUserAgentDescription[]; +extern const char kGalleryAppPdfEditNotificationName[]; +extern const char kGalleryAppPdfEditNotificationDescription[]; + extern const char kGlobalMediaControlsForCastName[]; extern const char kGlobalMediaControlsForCastDescription[]; @@ -927,9 +930,6 @@ extern const char kIgnoreSyncEncryptionKeysLongMissingName[]; extern const char kIgnoreSyncEncryptionKeysLongMissingDescription[]; -extern const char kImprovedDesksKeyboardShortcutsName[]; -extern const char kImprovedDesksKeyboardShortcutsDescription[]; - extern const char kImprovedKeyboardShortcutsName[]; extern const char kImprovedKeyboardShortcutsDescription[]; @@ -1989,6 +1989,8 @@ extern const char kCCTResizableForFirstPartiesDescription[]; extern const char kCCTResizableForThirdPartiesName[]; extern const char kCCTResizableForThirdPartiesDescription[]; +extern const char kCCTResizableSideSheetName[]; +extern const char kCCTResizableSideSheetDescription[]; extern const char kCCTRetainingStateInMemoryName[]; extern const char kCCTRetainingStateInMemoryDescription[]; @@ -3414,15 +3416,9 @@ extern const char kSpectreVariant2MitigationName[]; extern const char kSpectreVariant2MitigationDescription[]; -extern const char kSystemChinesePhysicalTypingName[]; -extern const char kSystemChinesePhysicalTypingDescription[]; - extern const char kSystemJapanesePhysicalTypingName[]; extern const char kSystemJapanesePhysicalTypingDescription[]; -extern const char kSystemTransliterationPhysicalTypingName[]; -extern const char kSystemTransliterationPhysicalTypingDescription[]; - extern const char kQuickSettingsNetworkRevampName[]; extern const char kQuickSettingsNetworkRevampDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 14cfc93..089e7ba 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -207,6 +207,7 @@ &kCCTResizableAlwaysShowNavBarButtons, &kCCTResizableForFirstParties, &kCCTResizableForThirdParties, + &kCCTResizableSideSheet, &kCCTRetainingState, &kCCTRetainingStateInMemory, &kCCTResourcePrefetch, @@ -622,6 +623,10 @@ "CCTResizableForThirdParties", base::FEATURE_ENABLED_BY_DEFAULT); +BASE_FEATURE(kCCTResizableSideSheet, + "CCTResizableSideSheet", + base::FEATURE_DISABLED_BY_DEFAULT); + BASE_FEATURE(kCCTResourcePrefetch, "CCTResourcePrefetch", base::FEATURE_ENABLED_BY_DEFAULT);
diff --git a/chrome/browser/flags/android/chrome_feature_list.h b/chrome/browser/flags/android/chrome_feature_list.h index 0afbb63b..3682dc84 100644 --- a/chrome/browser/flags/android/chrome_feature_list.h +++ b/chrome/browser/flags/android/chrome_feature_list.h
@@ -54,6 +54,7 @@ BASE_DECLARE_FEATURE(kCCTResizableAlwaysShowNavBarButtons); BASE_DECLARE_FEATURE(kCCTResizableForFirstParties); BASE_DECLARE_FEATURE(kCCTResizableForThirdParties); +BASE_DECLARE_FEATURE(kCCTResizableSideSheet); BASE_DECLARE_FEATURE(kCCTResourcePrefetch); BASE_DECLARE_FEATURE(kCCTRetainingState); BASE_DECLARE_FEATURE(kCCTRetainingStateInMemory);
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index 0531da2..8d9aeaf3 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -236,6 +236,7 @@ "CCTResizableAlwaysShowNavBarButtons"; public static final String CCT_RESIZABLE_FOR_FIRST_PARTIES = "CCTResizableForFirstParties"; public static final String CCT_RESIZABLE_FOR_THIRD_PARTIES = "CCTResizableForThirdParties"; + public static final String CCT_RESIZABLE_SIDE_SHEET = "CCTResizableSideSheet"; public static final String CCT_RESOURCE_PREFETCH = "CCTResourcePrefetch"; public static final String CCT_RETAINING_STATE = "CCTRetainingState"; public static final String CCT_RETAINING_STATE_IN_MEMORY = "CCTRetainingStateInMemory"; @@ -633,6 +634,8 @@ new CachedFlag(CCT_RESIZABLE_FOR_FIRST_PARTIES, true); public static final CachedFlag sCctResizableForThirdParties = new CachedFlag(CCT_RESIZABLE_FOR_THIRD_PARTIES, false); + public static final CachedFlag sCctResizableSideSheet = + new CachedFlag(CCT_RESIZABLE_SIDE_SHEET, false); public static final CachedFlag sCctRetainableStateInMemory = new CachedFlag(CCT_RETAINING_STATE_IN_MEMORY, false); public static final CachedFlag sCctToolbarCustomizations =
diff --git a/chrome/browser/infobars/infobars_browsertest.cc b/chrome/browser/infobars/infobars_browsertest.cc index 041d36e9..979ae74 100644 --- a/chrome/browser/infobars/infobars_browsertest.cc +++ b/chrome/browser/infobars/infobars_browsertest.cc
@@ -13,7 +13,6 @@ #include "build/build_config.h" #include "build/buildflag.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/buildflags.h" #include "chrome/browser/devtools/devtools_infobar_delegate.h" #include "chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h" #include "chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h" @@ -66,7 +65,7 @@ #include "chrome/browser/ui/startup/default_browser_infobar_delegate.h" #endif -#if BUILDFLAG(IS_MAC) && BUILDFLAG(ENABLE_UPDATER) +#if BUILDFLAG(IS_MAC) #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h" #endif @@ -280,7 +279,7 @@ break; case IBD::KEYSTONE_PROMOTION_INFOBAR_DELEGATE_MAC: -#if BUILDFLAG(IS_MAC) && BUILDFLAG(ENABLE_UPDATER) +#if BUILDFLAG(IS_MAC) KeystonePromotionInfoBarDelegate::Create(GetWebContents()); #else ADD_FAILURE() << "This infobar is not supported on this OS.";
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc index 8f73b83..9ef81e5f2 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc
@@ -172,8 +172,28 @@ new_routes.begin(), new_routes.end(), std::inserter(removed_routes, removed_routes.end())); + std::vector<MediaRoute::Id> added_routes; + std::set_difference(new_routes.begin(), new_routes.end(), + previous_routes_.begin(), previous_routes_.end(), + std::inserter(added_routes, removed_routes.end())); + previous_routes_ = new_routes; + if (added_routes.size() > 0) { + base::PostTaskAndReplyWithResult( + access_code_sink_service_->GetCastMediaSinkServiceImpl() + ->task_runner() + .get(), + FROM_HERE, + base::BindOnce( + &CastMediaSinkServiceImpl::GetSinkById, + base::Unretained( + access_code_sink_service_->GetCastMediaSinkServiceImpl()), + MediaRoute::GetSinkIdFromMediaRouteId(*added_routes.begin())), + base::BindOnce(&AccessCodeCastSinkService::HandleMediaRouteAdded, + access_code_sink_service_->GetWeakPtr())); + } + // No routes were removed. if (removed_routes.empty()) return; @@ -234,6 +254,15 @@ kExpirationDelay); } +void AccessCodeCastSinkService::HandleMediaRouteAdded( + const MediaSinkInternal* sink) { + if (!IsSinkValidAccessCodeSink(sink)) + return; + + AccessCodeCastMetrics::RecordAccessCodeRouteStarted( + GetAccessCodeDeviceDurationPref(profile_)); +} + void AccessCodeCastSinkService::OnAccessCodeRouteRemoved( const MediaSinkInternal* sink) { // If the sink is a cast sink discovered by Access Code, only expire it if
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h index 22077a1..034be6b0 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h
@@ -194,6 +194,8 @@ RefreshStoredDeviceInfo); FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, RefreshStoredDeviceTimer); + FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, + HandleMediaRouteAdded); // Use |AccessCodeCastSinkServiceFactory::GetForProfile(..)| to get // an instance of this service. @@ -221,6 +223,9 @@ // code cast sink has ended. void HandleMediaRouteRemovedByAccessCode(const MediaSinkInternal* sink); + // Reports to metrics whenever the added route is to an access code sink. + void HandleMediaRouteAdded(const MediaSinkInternal* sink); + void OnAccessCodeRouteRemoved(const MediaSinkInternal* sink); void OpenChannelIfNecessary(const MediaSinkInternal& sink, AddSinkResultCallback add_sink_callback,
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc index bbbb902..b19ab03 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/win/windows_version.h" #endif #include "base/task/task_runner_util.h" +#include "base/test/metrics/histogram_tester.h" #include "chrome/browser/buildflags.h" #include "chrome/browser/media/router/discovery/access_code/access_code_cast_constants.h" #include "chrome/browser/media/router/discovery/access_code/access_code_media_sink_util.h" @@ -65,6 +66,8 @@ // then ensures the devices was not saved when the browsertest starts up // again. + base::HistogramTester histogram_tester; + // Mock a successful fetch from our server. SetEndpointFetcherMockResponse(kEndpointResponseSuccess, net::HTTP_OK, net::OK); @@ -91,6 +94,11 @@ UpdateRoutes({media_route_cast}); base::RunLoop().RunUntilIdle(); + // Recorded once from the route created when pressing submit, and then again + // when we manually call `UpdateRoutes`. + histogram_tester.ExpectTotalCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 2); + EXPECT_CALL(*mock_cast_media_sink_service_impl(), DisconnectAndRemoveSink(_)); UpdateRoutes({}); WaitForPrefRemoval("cast:<1234>");
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc index 9b65b98..05a9751 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc
@@ -1387,4 +1387,69 @@ ->IsRunning()); } +TEST_F(AccessCodeCastSinkServiceTest, HandleMediaRouteAdded) { + // Initialize histogram tester so we can ensure metrics are collected. + base::HistogramTester histogram_tester; + + // Set duration pref since it will be recorded in metrics. + SetDeviceDurationPrefForTest(base::Seconds(10)); + + // Create fake sinks for the test. + + // cast_sink1 is not an access code sink. + MediaSinkInternal cast_sink1 = CreateCastSink(1); + auto cast_data1 = cast_sink1.cast_data(); + cast_data1.discovery_type = CastDiscoveryType::kMdns; + cast_sink1.set_cast_data(cast_data1); + + // cast_sink2 is a new access code sink. + MediaSinkInternal cast_sink2 = CreateCastSink(2); + auto cast_data2 = cast_sink2.cast_data(); + cast_data2.discovery_type = CastDiscoveryType::kAccessCodeManualEntry; + cast_sink2.set_cast_data(cast_data2); + + // cast_sink3 is a saved access code sink. + MediaSinkInternal cast_sink3 = CreateCastSink(3); + auto cast_data3 = cast_sink3.cast_data(); + cast_data3.discovery_type = CastDiscoveryType::kAccessCodeRememberedDevice; + cast_sink3.set_cast_data(cast_data3); + + // The histogram should start with nothing logged. + histogram_tester.ExpectTotalCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 0); + + access_code_cast_sink_service_->HandleMediaRouteAdded(&cast_sink1); + + // The histogram should not be logged to after a non access code route starts. + histogram_tester.ExpectTotalCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 0); + + access_code_cast_sink_service_->HandleMediaRouteAdded(&cast_sink2); + + // The histogram should log when a route starts to a new access code device. + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 10, 1); + + access_code_cast_sink_service_->HandleMediaRouteAdded(&cast_sink3); + + // The histogram should log when a route starts to a saved access code device. + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 10, 2); + + // Ensure various pref values are can be logged. + SetDeviceDurationPrefForTest(base::Seconds(100)); + access_code_cast_sink_service_->HandleMediaRouteAdded(&cast_sink2); + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 100, 1); + + SetDeviceDurationPrefForTest(base::Seconds(1000)); + access_code_cast_sink_service_->HandleMediaRouteAdded(&cast_sink2); + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 1000, 1); + + // Histogram logs should not have been lost. + histogram_tester.ExpectTotalCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 4); +} + } // namespace media_router
diff --git a/chrome/browser/metrics/chromeos_system_profile_provider.cc b/chrome/browser/metrics/chromeos_system_profile_provider.cc index 288a6df1..1ae6322 100644 --- a/chrome/browser/metrics/chromeos_system_profile_provider.cc +++ b/chrome/browser/metrics/chromeos_system_profile_provider.cc
@@ -216,8 +216,11 @@ void ChromeOSSystemProfileProvider::OnMachineStatisticsLoaded( base::OnceClosure callback) { - chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic( - "hardware_class", &full_hardware_class_); + if (const absl::optional<base::StringPiece> full_hardware_class = + chromeos::system::StatisticsProvider::GetInstance() + ->GetMachineStatistic("hardware_class")) { + full_hardware_class_ = std::string(full_hardware_class.value()); + } std::move(callback).Run(); }
diff --git a/chrome/browser/password_manager/android/BUILD.gn b/chrome/browser/password_manager/android/BUILD.gn index 3ddb0a07..a0036a91 100644 --- a/chrome/browser/password_manager/android/BUILD.gn +++ b/chrome/browser/password_manager/android/BUILD.gn
@@ -418,9 +418,6 @@ "password_manager_settings_service_android_impl_unittest.cc", "password_store_android_backend_unittest.cc", "password_sync_controller_delegate_android_unittest.cc", - "save_password_infobar_delegate_android_unittest.cc", - "save_update_password_message_delegate_unittest.cc", - "update_password_infobar_delegate_android_unittest.cc", ] deps = [
diff --git a/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.cc b/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.cc deleted file mode 100644 index 2b676d4..0000000 --- a/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h" - -#include <stddef.h> - -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/android/android_theme_resources.h" -#include "chrome/browser/password_manager/android/password_manager_launcher_android.h" -#include "chrome/grit/generated_resources.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" -#include "components/infobars/core/infobar_manager.h" -#include "components/password_manager/core/browser/manage_passwords_referrer.h" -#include "components/password_manager/core/browser/password_bubble_experiment.h" -#include "components/password_manager/core/browser/password_manager_constants.h" -#include "components/strings/grit/components_strings.h" -#include "ui/base/l10n/l10n_util.h" -#include "url/gurl.h" - -GeneratedPasswordSavedInfoBarDelegateAndroid:: - ~GeneratedPasswordSavedInfoBarDelegateAndroid() {} - -void GeneratedPasswordSavedInfoBarDelegateAndroid::OnInlineLinkClicked() { - password_manager_launcher::ShowPasswordSettings( - infobars::ContentInfoBarManager::WebContentsFromInfoBar(infobar()), - password_manager::ManagePasswordsReferrer:: - kPasswordGenerationConfirmation); -} - -GeneratedPasswordSavedInfoBarDelegateAndroid:: - GeneratedPasswordSavedInfoBarDelegateAndroid() - : button_label_(l10n_util::GetStringUTF16(IDS_OK)) { - std::u16string link = l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_LINK); - - size_t offset = 0; - message_text_ = - l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_CONFIRM_SAVED_TITLE); - details_message_text_ = l10n_util::GetStringFUTF16( - IDS_MANAGE_PASSWORDS_CONFIRM_GENERATED_TEXT, link, &offset); - inline_link_range_ = gfx::Range(offset, offset + link.length()); -} - -infobars::InfoBarDelegate::InfoBarIdentifier -GeneratedPasswordSavedInfoBarDelegateAndroid::GetIdentifier() const { - return GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID; -} - -int GeneratedPasswordSavedInfoBarDelegateAndroid::GetIconId() const { - return IDR_ANDROID_INFOBAR_SAVE_PASSWORD; -}
diff --git a/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h b/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h deleted file mode 100644 index ad4001d..0000000 --- a/chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID_H_ -#define CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID_H_ - -#include <string> - -#include "components/infobars/core/infobar_delegate.h" -#include "ui/gfx/range/range.h" - -namespace content { -class WebContents; -} - -// Android-only infobar to notify that the generated password was saved. -class GeneratedPasswordSavedInfoBarDelegateAndroid - : public infobars::InfoBarDelegate { - public: - // Creates and shows the infobar. Implemented with - // GeneratedPasswordSavedInfoBar. - static void Create(content::WebContents* web_contents); - - GeneratedPasswordSavedInfoBarDelegateAndroid( - const GeneratedPasswordSavedInfoBarDelegateAndroid&) = delete; - GeneratedPasswordSavedInfoBarDelegateAndroid& operator=( - const GeneratedPasswordSavedInfoBarDelegateAndroid&) = delete; - - ~GeneratedPasswordSavedInfoBarDelegateAndroid() override; - - // Returns the translated text of the message to display. - const std::u16string& message_text() const { return message_text_; } - - // Returns the translated text of the details message to display. T - const std::u16string& details_message_text() const { - return details_message_text_; - } - - // Returns the range of the details message text that should be a link. - const gfx::Range& inline_link_range() const { return inline_link_range_; } - - // Returns the translated label of the button. - const std::u16string& button_label() const { return button_label_; } - - // Called when the link in the message is clicked. - void OnInlineLinkClicked(); - - private: - GeneratedPasswordSavedInfoBarDelegateAndroid(); - - // infobars::InfoBarDelegate: - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - int GetIconId() const override; - - // The translated text of the message to display. - std::u16string message_text_; - - // The translated text of the details message to display. This message - // explains where the generated password is saved. - std::u16string details_message_text_; - - // The range of the details message that should be a link. - gfx::Range inline_link_range_; - - // The translated label of the button. - std::u16string button_label_; -}; - -#endif // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID_H_
diff --git a/chrome/browser/password_manager/android/password_infobar_utils.cc b/chrome/browser/password_manager/android/password_infobar_utils.cc index ec48508..e3245b8 100644 --- a/chrome/browser/password_manager/android/password_infobar_utils.cc +++ b/chrome/browser/password_manager/android/password_infobar_utils.cc
@@ -13,18 +13,6 @@ #include "components/signin/public/identity_manager/identity_manager.h" namespace password_manager { -AccountInfo GetAccountInfoForPasswordInfobars(Profile* profile, - bool is_syncing) { - DCHECK(profile); - if (!is_syncing) { - return AccountInfo(); - } - signin::IdentityManager* identity_manager = - IdentityManagerFactory::GetForProfile(profile); - CoreAccountId account_id = - identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSync); - return identity_manager->FindExtendedAccountInfoByAccountId(account_id); -} AccountInfo GetAccountInfoForPasswordMessages(Profile* profile) { DCHECK(profile);
diff --git a/chrome/browser/password_manager/android/password_infobar_utils.h b/chrome/browser/password_manager/android/password_infobar_utils.h index 042b3da..0b5a182c 100644 --- a/chrome/browser/password_manager/android/password_infobar_utils.h +++ b/chrome/browser/password_manager/android/password_infobar_utils.h
@@ -11,9 +11,6 @@ namespace password_manager { -AccountInfo GetAccountInfoForPasswordInfobars(Profile* profile, - bool is_syncing); - AccountInfo GetAccountInfoForPasswordMessages(Profile* profile); } // namespace password_manager
diff --git a/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.cc b/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.cc deleted file mode 100644 index c4e79d51..0000000 --- a/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.cc +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h" - -#include "chrome/browser/android/android_theme_resources.h" -#include "chrome/grit/generated_resources.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" -#include "components/password_manager/core/browser/password_manager_constants.h" -#include "content/public/browser/web_contents.h" -#include "ui/base/l10n/l10n_util.h" - -PasswordManagerInfoBarDelegate::~PasswordManagerInfoBarDelegate() = default; - -std::u16string PasswordManagerInfoBarDelegate::GetDetailsMessageText() const { - return details_message_; -} - -infobars::InfoBarDelegate::InfoBarAutomationType -PasswordManagerInfoBarDelegate::GetInfoBarAutomationType() const { - return PASSWORD_INFOBAR; -} - -int PasswordManagerInfoBarDelegate::GetIconId() const { - return IDR_ANDROID_INFOBAR_SAVE_PASSWORD; -} - -GURL PasswordManagerInfoBarDelegate::GetLinkURL() const { - return GURL(password_manager::kPasswordManagerHelpCenterSmartLock); -} - -bool PasswordManagerInfoBarDelegate::ShouldExpire( - const NavigationDetails& details) const { - return !details.is_redirect && ConfirmInfoBarDelegate::ShouldExpire(details); -} - -bool PasswordManagerInfoBarDelegate::LinkClicked( - WindowOpenDisposition disposition) { - ConfirmInfoBarDelegate::LinkClicked(disposition); - return true; -} - -std::u16string PasswordManagerInfoBarDelegate::GetMessageText() const { - return message_; -} - -PasswordManagerInfoBarDelegate::PasswordManagerInfoBarDelegate() = default; - -void PasswordManagerInfoBarDelegate::SetMessage(const std::u16string& message) { - message_ = message; -} - -void PasswordManagerInfoBarDelegate::SetDetailsMessage( - const std::u16string& details_message) { - details_message_ = details_message; -}
diff --git a/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h b/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h deleted file mode 100644 index e1edea0..0000000 --- a/chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_PASSWORD_MANAGER_INFOBAR_DELEGATE_ANDROID_H_ -#define CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_PASSWORD_MANAGER_INFOBAR_DELEGATE_ANDROID_H_ - -#include "components/infobars/core/confirm_infobar_delegate.h" - -// Base class for some of the password manager infobar delegates, e.g. -// SavePasswordInfoBarDelegate. -class PasswordManagerInfoBarDelegate : public ConfirmInfoBarDelegate { - public: - PasswordManagerInfoBarDelegate(const PasswordManagerInfoBarDelegate&) = - delete; - PasswordManagerInfoBarDelegate& operator=( - const PasswordManagerInfoBarDelegate&) = delete; - - ~PasswordManagerInfoBarDelegate() override; - - // Getter for the message displayed in adition to the title. If no message - // was set, this returns and empty string. - std::u16string GetDetailsMessageText() const; - - // ConfirmInfoBarDelegate: - InfoBarAutomationType GetInfoBarAutomationType() const override; - int GetIconId() const override; - GURL GetLinkURL() const override; - bool ShouldExpire(const NavigationDetails& details) const override; - bool LinkClicked(WindowOpenDisposition disposition) override; - std::u16string GetMessageText() const override; - - protected: - PasswordManagerInfoBarDelegate(); - - void SetMessage(const std::u16string& message); - void SetDetailsMessage(const std::u16string& details_message); - - private: - // Message for the infobar: branded as a part of Google Smart Lock for signed - // users. - std::u16string message_; - - // Used to display aditional information about where the passwords were saved. - std::u16string details_message_; -}; - -#endif // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_PASSWORD_MANAGER_INFOBAR_DELEGATE_ANDROID_H_
diff --git a/chrome/browser/password_manager/android/save_password_infobar_delegate_android.cc b/chrome/browser/password_manager/android/save_password_infobar_delegate_android.cc deleted file mode 100644 index 5c25434..0000000 --- a/chrome/browser/password_manager/android/save_password_infobar_delegate_android.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/save_password_infobar_delegate_android.h" - -#include <utility> - -#include "base/memory/ptr_util.h" -#include "base/metrics/histogram_macros.h" -#include "base/values.h" -#include "chrome/browser/password_manager/android/password_infobar_utils.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/sync_service_factory.h" -#include "chrome/browser/ui/android/infobars/save_password_infobar.h" -#include "chrome/browser/ui/passwords/ui_utils.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" -#include "components/infobars/core/infobar_manager.h" -#include "components/password_manager/core/browser/password_bubble_experiment.h" -#include "components/password_manager/core/browser/password_form_metrics_recorder.h" -#include "components/sync/driver/sync_service.h" -#include "content/public/browser/web_contents.h" -#include "ui/base/l10n/l10n_util.h" -#include "url/origin.h" - -// static -void SavePasswordInfoBarDelegate::Create( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save) { - Profile* profile = - Profile::FromBrowserContext(web_contents->GetBrowserContext()); - syncer::SyncService* sync_service = - SyncServiceFactory::GetForProfile(profile); - // is_smartlock_branding_enabled indicates whether the user is syncing - // passwords to their Google Account. - bool is_smartlock_branding_enabled = - password_bubble_experiment::HasChosenToSyncPasswords(sync_service); - infobars::ContentInfoBarManager* infobar_manager = - infobars::ContentInfoBarManager::FromWebContents(web_contents); - infobar_manager->AddInfoBar(std::make_unique<SavePasswordInfoBar>( - base::WrapUnique( - new SavePasswordInfoBarDelegate(web_contents, std::move(form_to_save), - is_smartlock_branding_enabled)), - password_manager::GetAccountInfoForPasswordInfobars( - profile, /*is_syncing=*/is_smartlock_branding_enabled))); -} - -SavePasswordInfoBarDelegate::~SavePasswordInfoBarDelegate() { - password_manager::metrics_util::LogSaveUIDismissalReason( - infobar_response_, - form_to_save_->GetPendingCredentials().submission_event, - /*user_state=*/absl::nullopt); - if (form_to_save_->WasUnblocklisted()) { - password_manager::metrics_util::LogSaveUIDismissalReasonAfterUnblocklisting( - infobar_response_); - } - if (auto* recorder = form_to_save_->GetMetricsRecorder()) { - recorder->RecordUIDismissalReason(infobar_response_); - } -} - -SavePasswordInfoBarDelegate::SavePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save, - bool is_smartlock_branding_enabled) - : PasswordManagerInfoBarDelegate(), - form_to_save_(std::move(form_to_save)), - infobar_response_(password_manager::metrics_util::NO_DIRECT_INTERACTION) { - PasswordTitleType type = - form_to_save_->GetPendingCredentials().federation_origin.opaque() - ? PasswordTitleType::SAVE_PASSWORD - : PasswordTitleType::SAVE_ACCOUNT; - SetMessage(GetSavePasswordDialogTitleText( - web_contents->GetVisibleURL(), - url::Origin::Create(form_to_save_->GetURL()), type)); - - if (type == PasswordTitleType::SAVE_PASSWORD && - is_smartlock_branding_enabled) { - SetDetailsMessage(l10n_util::GetStringUTF16(IDS_SAVE_PASSWORD_FOOTER)); - } - - if (auto* recorder = form_to_save_->GetMetricsRecorder()) { - recorder->RecordPasswordBubbleShown( - form_to_save_->GetCredentialSource(), - password_manager::metrics_util::AUTOMATIC_WITH_PASSWORD_PENDING); - } -} - -infobars::InfoBarDelegate::InfoBarIdentifier -SavePasswordInfoBarDelegate::GetIdentifier() const { - return SAVE_PASSWORD_INFOBAR_DELEGATE_MOBILE; -} - -void SavePasswordInfoBarDelegate::InfoBarDismissed() { - DCHECK(form_to_save_.get()); - infobar_response_ = password_manager::metrics_util::CLICKED_CANCEL; -} - -std::u16string SavePasswordInfoBarDelegate::GetButtonLabel( - InfoBarButton button) const { - return l10n_util::GetStringUTF16((button == BUTTON_OK) - ? IDS_PASSWORD_MANAGER_SAVE_BUTTON - : IDS_PASSWORD_MANAGER_BLOCKLIST_BUTTON); -} - -bool SavePasswordInfoBarDelegate::Accept() { - DCHECK(form_to_save_.get()); - form_to_save_->Save(); - infobar_response_ = password_manager::metrics_util::CLICKED_ACCEPT; - return true; -} - -bool SavePasswordInfoBarDelegate::Cancel() { - DCHECK(form_to_save_.get()); - form_to_save_->Blocklist(); - infobar_response_ = password_manager::metrics_util::CLICKED_NEVER; - return true; -}
diff --git a/chrome/browser/password_manager/android/save_password_infobar_delegate_android.h b/chrome/browser/password_manager/android/save_password_infobar_delegate_android.h deleted file mode 100644 index 8c051ab..0000000 --- a/chrome/browser/password_manager/android/save_password_infobar_delegate_android.h +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_SAVE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_ -#define CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_SAVE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_ - -#include <memory> - -#include "base/timer/elapsed_timer.h" -#include "chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h" -#include "components/infobars/core/confirm_infobar_delegate.h" -#include "components/password_manager/core/browser/password_form_manager_for_ui.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" -#include "ui/gfx/range/range.h" - -namespace content { -class WebContents; -} - -// After a successful *new* login attempt, we take the PasswordFormManager in -// provisional_save_manager_ and move it to a SavePasswordInfoBarDelegate while -// the user makes up their mind with the "save password" infobar. Note if the -// login is one we already know about, the end of the line is -// provisional_save_manager_ because we just update it on success and so such -// forms never end up in an infobar. -class SavePasswordInfoBarDelegate : public PasswordManagerInfoBarDelegate { - public: - // If we won't be showing the one-click signin infobar, creates a save - // password infobar and delegate and adds the infobar to the - // infobars::ContentInfoBarManager for |web_contents|. - static void Create( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save); - - SavePasswordInfoBarDelegate(const SavePasswordInfoBarDelegate&) = delete; - SavePasswordInfoBarDelegate& operator=(const SavePasswordInfoBarDelegate&) = - delete; - - ~SavePasswordInfoBarDelegate() override; - - // ConfirmInfoBarDelegate: - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - void InfoBarDismissed() override; - std::u16string GetButtonLabel(InfoBarButton button) const override; - bool Accept() override; - bool Cancel() override; - - protected: - // Makes a ctor available in tests. - SavePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save, - bool is_smartlock_branding_enabled); - - private: - // The PasswordFormManager managing the form we're asking the user about, - // and should update as per their decision. - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save_; - - // Used to track the results we get from the info bar. - password_manager::metrics_util::UIDismissalReason infobar_response_; - - // Measures the "Save password?" prompt lifetime. Used to report an UMA - // signal. - base::ElapsedTimer timer_; -}; - -// Creates the platform-specific SavePassword InfoBar. This function is defined -// in platform-specific .cc (or .mm) files. -std::unique_ptr<infobars::InfoBar> CreateSavePasswordInfoBar( - std::unique_ptr<SavePasswordInfoBarDelegate> delegate); - -#endif // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_SAVE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_
diff --git a/chrome/browser/password_manager/android/save_password_infobar_delegate_android_unittest.cc b/chrome/browser/password_manager/android/save_password_infobar_delegate_android_unittest.cc deleted file mode 100644 index 2d0d660..0000000 --- a/chrome/browser/password_manager/android/save_password_infobar_delegate_android_unittest.cc +++ /dev/null
@@ -1,318 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/save_password_infobar_delegate_android.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/strings/utf_string_conversions.h" -#include "base/test/metrics/histogram_tester.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "components/password_manager/core/browser/mock_password_form_manager_for_ui.h" -#include "components/password_manager/core/browser/password_form.h" -#include "components/password_manager/core/browser/password_form_manager.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" -#include "components/ukm/test_ukm_recorder.h" -#include "content/public/browser/web_contents.h" -#include "services/metrics/public/cpp/ukm_source.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/l10n/l10n_util.h" - -using password_manager::MockPasswordFormManagerForUI; -using password_manager::PasswordForm; -using password_manager::PasswordFormManagerForUI; -using password_manager::PasswordFormMetricsRecorder; -using testing::Return; -using testing::ReturnRef; - -namespace { - -class TestSavePasswordInfoBarDelegate : public SavePasswordInfoBarDelegate { - public: - TestSavePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<PasswordFormManagerForUI> form_to_save, - bool is_smartlock_branding_enabled) - : SavePasswordInfoBarDelegate(web_contents, - std::move(form_to_save), - is_smartlock_branding_enabled) {} - - ~TestSavePasswordInfoBarDelegate() override = default; -}; - -class SavePasswordInfoBarDelegateTest : public ChromeRenderViewHostTestHarness { - public: - SavePasswordInfoBarDelegateTest() = default; - ~SavePasswordInfoBarDelegateTest() override = default; - - void SetUp() override; - void TearDown() override; - - std::unique_ptr<MockPasswordFormManagerForUI> CreateMockFormManager( - scoped_refptr<PasswordFormMetricsRecorder> metrics_recorder, - bool with_federation_origin); - - protected: - std::unique_ptr<PasswordManagerInfoBarDelegate> CreateDelegate( - std::unique_ptr<PasswordFormManagerForUI> password_form_manager, - bool is_smartlock_branding_enabled); - void CreateTestForm(bool with_federation_origin); - - password_manager::PasswordForm test_form_; -}; - -std::unique_ptr<MockPasswordFormManagerForUI> -SavePasswordInfoBarDelegateTest::CreateMockFormManager( - scoped_refptr<PasswordFormMetricsRecorder> metrics_recorder, - bool with_federation_origin) { - auto password_form_manager = - std::make_unique<testing::NiceMock<MockPasswordFormManagerForUI>>(); - CreateTestForm(with_federation_origin); - - ON_CALL(*password_form_manager, GetPendingCredentials) - .WillByDefault(ReturnRef(test_form_)); - ON_CALL(*password_form_manager, GetURL) - .WillByDefault(ReturnRef(test_form_.url)); - if (metrics_recorder) { - ON_CALL(*password_form_manager, GetMetricsRecorder) - .WillByDefault(Return(metrics_recorder.get())); - } - return password_form_manager; -} - -std::unique_ptr<PasswordManagerInfoBarDelegate> -SavePasswordInfoBarDelegateTest::CreateDelegate( - std::unique_ptr<PasswordFormManagerForUI> password_form_manager, - bool is_smartlock_branding_enabled) { - return std::make_unique<TestSavePasswordInfoBarDelegate>( - web_contents(), std::move(password_form_manager), - is_smartlock_branding_enabled); -} - -void SavePasswordInfoBarDelegateTest::CreateTestForm( - bool with_federation_origin) { - test_form_.url = GURL("https://example.com"); - test_form_.username_value = u"username"; - test_form_.password_value = u"12345"; - if (with_federation_origin) { - test_form_.federation_origin = - url::Origin::Create(GURL("https://example.com")); - } -} - -void SavePasswordInfoBarDelegateTest::SetUp() { - ChromeRenderViewHostTestHarness::SetUp(); -} - -void SavePasswordInfoBarDelegateTest::TearDown() { - ChromeRenderViewHostTestHarness::TearDown(); -} - -TEST_F(SavePasswordInfoBarDelegateTest, CancelTest) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - EXPECT_CALL(*password_form_manager.get(), Blocklist()); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/true)); - EXPECT_TRUE(infobar->Cancel()); -} - -TEST_F(SavePasswordInfoBarDelegateTest, HasDetailsMessageWhenSyncing) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/true)); - EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SAVE_PASSWORD_FOOTER), - infobar->GetDetailsMessageText()); -} - -TEST_F(SavePasswordInfoBarDelegateTest, EmptyDetailsMessageWhenNotSyncing) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - EXPECT_TRUE(infobar->GetDetailsMessageText().empty()); -} - -TEST_F(SavePasswordInfoBarDelegateTest, - EmptyDetailsMessageForFederatedCredentialsWhenSyncing) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/true); - NavigateAndCommit(GURL("https://example.com")); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/true)); - EXPECT_TRUE(infobar->GetDetailsMessageText().empty()); -} - -TEST_F(SavePasswordInfoBarDelegateTest, - EmptyDetailsMessageForFederatedCredentialsWhenNotSyncing) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/true); - NavigateAndCommit(GURL("https://example.com")); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - EXPECT_TRUE(infobar->GetDetailsMessageText().empty()); -} - -TEST_F(SavePasswordInfoBarDelegateTest, RecordsSaveAfterUnblocklisting) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - ON_CALL(*password_form_manager, WasUnblocklisted).WillByDefault(Return(true)); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - base::HistogramTester histogram_tester; - infobar->Accept(); - infobar.reset(); - histogram_tester.ExpectUniqueSample( - "PasswordManager.SaveUIDismissalReasonAfterUnblacklisting", - password_manager::metrics_util::CLICKED_ACCEPT, 1); -} - -TEST_F(SavePasswordInfoBarDelegateTest, RecordNeverAfterUnblocklisting) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - ON_CALL(*password_form_manager, WasUnblocklisted).WillByDefault(Return(true)); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - base::HistogramTester histogram_tester; - infobar->Cancel(); - infobar.reset(); - histogram_tester.ExpectUniqueSample( - "PasswordManager.SaveUIDismissalReasonAfterUnblacklisting", - password_manager::metrics_util::CLICKED_NEVER, 1); -} - -TEST_F(SavePasswordInfoBarDelegateTest, RecordDismissAfterUnblocklisting) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - ON_CALL(*password_form_manager, WasUnblocklisted).WillByDefault(Return(true)); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - base::HistogramTester histogram_tester; - infobar->InfoBarDismissed(); - infobar.reset(); - histogram_tester.ExpectUniqueSample( - "PasswordManager.SaveUIDismissalReasonAfterUnblacklisting", - password_manager::metrics_util::CLICKED_CANCEL, 1); -} - -TEST_F(SavePasswordInfoBarDelegateTest, DontRecordIfNotUnblocklisted) { - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager( - /*metrics_recorder=*/nullptr, /*with_federation_origin=*/false); - ON_CALL(*password_form_manager, WasUnblocklisted) - .WillByDefault(Return(false)); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/false)); - base::HistogramTester histogram_tester; - infobar->InfoBarDismissed(); - infobar.reset(); - histogram_tester.ExpectTotalCount( - "PasswordManager.SaveUIDismissalReasonAfterUnblacklisting", 0); -} - -class SavePasswordInfoBarDelegateTestForUKMs - : public SavePasswordInfoBarDelegateTest, - public ::testing::WithParamInterface< - PasswordFormMetricsRecorder::BubbleDismissalReason> { - public: - SavePasswordInfoBarDelegateTestForUKMs() = default; - ~SavePasswordInfoBarDelegateTestForUKMs() = default; -}; - -// Verify that URL keyed metrics are recorded for showing and interacting with -// the password save prompt. -TEST_P(SavePasswordInfoBarDelegateTestForUKMs, VerifyUKMRecording) { - using BubbleTrigger = PasswordFormMetricsRecorder::BubbleTrigger; - using BubbleDismissalReason = - PasswordFormMetricsRecorder::BubbleDismissalReason; - using UkmEntry = ukm::builders::PasswordForm; - - BubbleDismissalReason dismissal_reason = GetParam(); - SCOPED_TRACE(::testing::Message() << "dismissal_reason = " - << static_cast<int64_t>(dismissal_reason)); - - ukm::SourceId expected_source_id = ukm::UkmRecorder::GetNewSourceID(); - ukm::TestAutoSetUkmRecorder test_ukm_recorder; - { - // Setup metrics recorder - auto recorder = base::MakeRefCounted<PasswordFormMetricsRecorder>( - /*is_main_frame_secure=*/true, expected_source_id, - /*pref_service=*/nullptr); - - // Exercise delegate. - std::unique_ptr<MockPasswordFormManagerForUI> password_form_manager = - CreateMockFormManager(recorder, /*with_federation_origin=*/false); - ON_CALL(*password_form_manager.get(), GetCredentialSource) - .WillByDefault(Return(password_manager::metrics_util:: - CredentialSourceType::kPasswordManager)); - if (dismissal_reason == BubbleDismissalReason::kDeclined) - EXPECT_CALL(*password_form_manager.get(), Blocklist()); - std::unique_ptr<ConfirmInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - /*is_smartlock_branding_enabled=*/true)); - switch (dismissal_reason) { - case BubbleDismissalReason::kAccepted: - EXPECT_TRUE(infobar->Accept()); - break; - case BubbleDismissalReason::kDeclined: - EXPECT_TRUE(infobar->Cancel()); - break; - case BubbleDismissalReason::kIgnored: - // Do nothing. - break; - case BubbleDismissalReason::kUnknown: - NOTREACHED(); - break; - } - } - - // Verify metrics. - const auto& entries = - test_ukm_recorder.GetEntriesByName(UkmEntry::kEntryName); - EXPECT_EQ(1u, entries.size()); - for (const auto* entry : entries) { - EXPECT_EQ(expected_source_id, entry->source_id); - test_ukm_recorder.ExpectEntryMetric(entry, - UkmEntry::kSaving_Prompt_ShownName, 1); - test_ukm_recorder.ExpectEntryMetric( - entry, UkmEntry::kSaving_Prompt_TriggerName, - static_cast<int64_t>( - BubbleTrigger::kPasswordManagerSuggestionAutomatic)); - test_ukm_recorder.ExpectEntryMetric( - entry, UkmEntry::kSaving_Prompt_InteractionName, - static_cast<int64_t>(dismissal_reason)); - } -} - -INSTANTIATE_TEST_SUITE_P( - All, - SavePasswordInfoBarDelegateTestForUKMs, - ::testing::Values( - PasswordFormMetricsRecorder::BubbleDismissalReason::kAccepted, - PasswordFormMetricsRecorder::BubbleDismissalReason::kDeclined, - PasswordFormMetricsRecorder::BubbleDismissalReason::kIgnored)); - -} // namespace
diff --git a/chrome/browser/password_manager/android/update_password_infobar_delegate_android.cc b/chrome/browser/password_manager/android/update_password_infobar_delegate_android.cc deleted file mode 100644 index 581cc599..0000000 --- a/chrome/browser/password_manager/android/update_password_infobar_delegate_android.cc +++ /dev/null
@@ -1,177 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/update_password_infobar_delegate_android.h" - -#include "base/memory/ptr_util.h" -#include "base/numerics/safe_conversions.h" -#include "chrome/browser/password_manager/android/password_infobar_utils.h" -#include "chrome/browser/password_manager/chrome_password_manager_client.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/sync_service_factory.h" -#include "chrome/browser/ui/android/infobars/update_password_infobar.h" -#include "chrome/browser/ui/passwords/ui_utils.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" -#include "components/password_manager/core/browser/password_bubble_experiment.h" -#include "components/password_manager/core/browser/password_form_metrics_recorder.h" -#include "components/password_manager/core/browser/password_ui_utils.h" -#include "components/strings/grit/components_strings.h" -#include "components/sync/driver/sync_service.h" -#include "content/public/browser/web_contents.h" -#include "ui/base/l10n/l10n_util.h" - -// static -void UpdatePasswordInfoBarDelegate::Create( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_save) { - Profile* profile = - Profile::FromBrowserContext(web_contents->GetBrowserContext()); - // is_smartlock_branding_enabled indicates whether the user is syncing - // passwords to their Google Account. - const bool is_smartlock_branding_enabled = - password_bubble_experiment::HasChosenToSyncPasswords( - SyncServiceFactory::GetForProfile( - Profile::FromBrowserContext(web_contents->GetBrowserContext()))); - infobars::ContentInfoBarManager::FromWebContents(web_contents) - ->AddInfoBar(std::make_unique<UpdatePasswordInfoBar>( - base::WrapUnique(new UpdatePasswordInfoBarDelegate( - web_contents, std::move(form_to_save), - is_smartlock_branding_enabled)), - password_manager::GetAccountInfoForPasswordInfobars( - profile, /*is_syncing=*/is_smartlock_branding_enabled))); -} - -UpdatePasswordInfoBarDelegate::~UpdatePasswordInfoBarDelegate() { - auto submission_event = - passwords_state_.form_manager()->GetPendingCredentials().submission_event; - password_manager::metrics_util::LogUpdateUIDismissalReason(infobar_response_, - submission_event); - if (auto* recorder = passwords_state_.form_manager()->GetMetricsRecorder()) { - recorder->RecordUIDismissalReason(infobar_response_); - } -} - -std::u16string UpdatePasswordInfoBarDelegate::GetBranding() const { - return l10n_util::GetStringUTF16(is_smartlock_branding_enabled_ - ? IDS_PASSWORD_MANAGER_SMART_LOCK - : IDS_PASSWORD_MANAGER_TITLE_BRAND); -} - -bool UpdatePasswordInfoBarDelegate::ShowMultipleAccounts() const { - return GetCurrentForms().size() > 1; -} - -const std::vector<std::unique_ptr<password_manager::PasswordForm>>& -UpdatePasswordInfoBarDelegate::GetCurrentForms() const { - return passwords_state_.GetCurrentForms(); -} - -const std::u16string& UpdatePasswordInfoBarDelegate::GetDefaultUsername() - const { - return passwords_state_.form_manager() - ->GetPendingCredentials() - .username_value; -} - -unsigned int UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - std::vector<std::u16string>* usernames) { - return UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - GetCurrentForms(), GetDefaultUsername(), usernames); -} - -// static -unsigned int UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - const std::vector<std::unique_ptr<password_manager::PasswordForm>>& - current_forms, - const std::u16string& default_username, - std::vector<std::u16string>* usernames) { - unsigned int selected_username = 0; - // TODO(crbug.com/1054410): Fix the update logic to use all best matches, - // rather than current_forms which is best_matches without PSL-matched - // credentials. - if (current_forms.size() > 1) { - // If multiple credentials can be updated, we display a dropdown with all - // the corresponding usernames. - for (const auto& form : current_forms) { - usernames->push_back(GetDisplayUsername(*form)); - if (form->username_value == default_username) { - selected_username = usernames->size() - 1; - } - } - } else if (default_username.empty()) { - usernames->push_back( - l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_EMPTY_LOGIN)); - } else { - usernames->push_back(default_username); - } - return selected_username; -} - -UpdatePasswordInfoBarDelegate::UpdatePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> form_to_update, - bool is_smartlock_branding_enabled) - : infobar_response_(password_manager::metrics_util::NO_DIRECT_INTERACTION), - is_smartlock_branding_enabled_(is_smartlock_branding_enabled) { - SetMessage(GetSavePasswordDialogTitleText( - web_contents->GetVisibleURL(), - url::Origin::Create(form_to_update->GetURL()), - PasswordTitleType::UPDATE_PASSWORD)); - if (is_smartlock_branding_enabled) - SetDetailsMessage(l10n_util::GetStringUTF16(IDS_SAVE_PASSWORD_FOOTER)); - - if (auto* recorder = form_to_update->GetMetricsRecorder()) { - recorder->RecordPasswordBubbleShown( - form_to_update->GetCredentialSource(), - password_manager::metrics_util::AUTOMATIC_WITH_PASSWORD_PENDING_UPDATE); - } - - passwords_state_.set_client( - ChromePasswordManagerClient::FromWebContents(web_contents)); - passwords_state_.OnUpdatePassword(std::move(form_to_update)); -} - -infobars::InfoBarDelegate::InfoBarIdentifier -UpdatePasswordInfoBarDelegate::GetIdentifier() const { - return UPDATE_PASSWORD_INFOBAR_DELEGATE_MOBILE; -} - -int UpdatePasswordInfoBarDelegate::GetButtons() const { - return BUTTON_OK; -} - -std::u16string UpdatePasswordInfoBarDelegate::GetButtonLabel( - InfoBarButton button) const { - return l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_UPDATE_BUTTON); -} - -void UpdatePasswordInfoBarDelegate::InfoBarDismissed() { - infobar_response_ = password_manager::metrics_util::CLICKED_CANCEL; -} - -bool UpdatePasswordInfoBarDelegate::Accept() { - infobar_response_ = password_manager::metrics_util::CLICKED_ACCEPT; - UpdatePasswordInfoBar* update_password_infobar = - static_cast<UpdatePasswordInfoBar*>(infobar()); - password_manager::PasswordFormManagerForUI* form_manager = - passwords_state_.form_manager(); - if (ShowMultipleAccounts()) { - int form_index = update_password_infobar->GetIdOfSelectedUsername(); - DCHECK_GE(form_index, 0); - DCHECK_LT(static_cast<size_t>(form_index), GetCurrentForms().size()); - UpdatePasswordFormUsernameAndPassword( - GetCurrentForms()[form_index]->username_value, - form_manager->GetPendingCredentials().password_value, form_manager); - } - form_manager->Save(); - return true; -} - -bool UpdatePasswordInfoBarDelegate::Cancel() { - infobar_response_ = password_manager::metrics_util::CLICKED_CANCEL; - return true; -}
diff --git a/chrome/browser/password_manager/android/update_password_infobar_delegate_android.h b/chrome/browser/password_manager/android/update_password_infobar_delegate_android.h deleted file mode 100644 index ea9e8da..0000000 --- a/chrome/browser/password_manager/android/update_password_infobar_delegate_android.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_UPDATE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_ -#define CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_UPDATE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_ - -#include <memory> -#include <string> -#include <vector> - -#include "chrome/browser/password_manager/android/password_manager_infobar_delegate_android.h" -#include "chrome/browser/ui/passwords/manage_passwords_state.h" -#include "components/password_manager/core/browser/password_form_manager_for_ui.h" -#include "components/password_manager/core/browser/password_manager_metrics_util.h" - -namespace content { -class WebContents; -} - -// An infobar delegate which asks the user if the password should be updated for -// a set of saved credentials for a site. If several such sets are present, the -// user can choose which one to update. PasswordManager displays this infobar -// when the user signs into the site with a new password for a known username -// or fills in a password change form. -class UpdatePasswordInfoBarDelegate : public PasswordManagerInfoBarDelegate { - public: - static void Create(content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> - form_to_update); - - UpdatePasswordInfoBarDelegate(const UpdatePasswordInfoBarDelegate&) = delete; - UpdatePasswordInfoBarDelegate& operator=( - const UpdatePasswordInfoBarDelegate&) = delete; - - ~UpdatePasswordInfoBarDelegate() override; - - std::u16string GetBranding() const; - bool is_smartlock_branding_enabled() const { - return is_smartlock_branding_enabled_; - } - - // Returns whether the user has multiple saved credentials, of which the - // infobar affects just one. In this case the infobar should clarify which - // credential is being affected. - bool ShowMultipleAccounts() const; - - const std::vector<std::unique_ptr<password_manager::PasswordForm>>& - GetCurrentForms() const; - - // Returns the username of the saved credentials to be updated by default. - const std::u16string& GetDefaultUsername() const; - - // Determines the usernames to be displayed in the update infobar and returns - // the index of the one selected by default. - unsigned int GetDisplayUsernames(std::vector<std::u16string>* usernames); - - // Exposed for testing. - static unsigned int GetDisplayUsernames( - const std::vector<std::unique_ptr<password_manager::PasswordForm>>& - current_forms, - const std::u16string& default_username, - std::vector<std::u16string>* usernames); - - protected: - // Makes a ctor available in tests. - UpdatePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManagerForUI> - form_to_update, - bool is_smartlock_branding_enabled); - - private: - // Used to track the results we get from the info bar. - password_manager::metrics_util::UIDismissalReason infobar_response_; - - // ConfirmInfoBarDelegate: - infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; - int GetButtons() const override; - std::u16string GetButtonLabel(InfoBarButton button) const override; - bool Accept() override; - void InfoBarDismissed() override; - bool Cancel() override; - - ManagePasswordsState passwords_state_; - std::u16string branding_; - bool is_smartlock_branding_enabled_; -}; - -#endif // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_UPDATE_PASSWORD_INFOBAR_DELEGATE_ANDROID_H_
diff --git a/chrome/browser/password_manager/android/update_password_infobar_delegate_android_unittest.cc b/chrome/browser/password_manager/android/update_password_infobar_delegate_android_unittest.cc deleted file mode 100644 index b079b64..0000000 --- a/chrome/browser/password_manager/android/update_password_infobar_delegate_android_unittest.cc +++ /dev/null
@@ -1,211 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/password_manager/android/update_password_infobar_delegate_android.h" - -#include <memory> -#include <string> - -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/password_manager/chrome_password_manager_client.h" -#include "chrome/browser/ui/autofill/chrome_autofill_client.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "components/password_manager/core/browser/fake_form_fetcher.h" -#include "components/password_manager/core/browser/password_form.h" -#include "components/password_manager/core/browser/password_form_manager.h" -#include "components/password_manager/core/browser/password_save_manager_impl.h" -#include "components/password_manager/core/browser/stub_form_saver.h" -#include "components/password_manager/core/browser/stub_password_manager_client.h" -#include "components/password_manager/core/browser/stub_password_manager_driver.h" -#include "components/strings/grit/components_strings.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/l10n/l10n_util.h" - -using password_manager::PasswordFormManager; -using password_manager::PasswordSaveManagerImpl; -using testing::ElementsAre; - -namespace { - -class TestUpdatePasswordInfoBarDelegate : public UpdatePasswordInfoBarDelegate { - public: - TestUpdatePasswordInfoBarDelegate( - content::WebContents* web_contents, - std::unique_ptr<password_manager::PasswordFormManager> form_to_save, - bool is_smartlock_branding_enabled) - : UpdatePasswordInfoBarDelegate(web_contents, - std::move(form_to_save), - is_smartlock_branding_enabled) {} - - ~TestUpdatePasswordInfoBarDelegate() override {} -}; - -} // namespace - -class UpdatePasswordInfoBarDelegateTest - : public ChromeRenderViewHostTestHarness { - public: - UpdatePasswordInfoBarDelegateTest(); - - UpdatePasswordInfoBarDelegateTest(const UpdatePasswordInfoBarDelegateTest&) = - delete; - UpdatePasswordInfoBarDelegateTest& operator=( - const UpdatePasswordInfoBarDelegateTest&) = delete; - - ~UpdatePasswordInfoBarDelegateTest() override {} - - void SetUp() override; - void TearDown() override; - - const password_manager::PasswordForm& test_form() { return test_form_; } - - // TODO(crbug.com/1048107): Replace real PasswordFormManager instance with the - // mock. - std::unique_ptr<password_manager::PasswordFormManager> - CreateTestFormManager(); - - protected: - std::unique_ptr<UpdatePasswordInfoBarDelegate> CreateDelegate( - std::unique_ptr<password_manager::PasswordFormManager> - password_form_manager, - bool is_smartlock_branding_enabled); - - password_manager::StubPasswordManagerClient client_; - password_manager::StubPasswordManagerDriver driver_; - - password_manager::PasswordForm test_form_; - autofill::FormData observed_form_; - - private: - password_manager::FakeFormFetcher fetcher_; -}; - -UpdatePasswordInfoBarDelegateTest::UpdatePasswordInfoBarDelegateTest() { - test_form_.url = GURL("https://example.com"); - test_form_.username_value = u"username"; - test_form_.password_value = u"12345"; - - // Create a simple sign-in form. - observed_form_.url = test_form_.url; - autofill::FormFieldData field; - field.form_control_type = "text"; - field.value = test_form_.username_value; - observed_form_.fields.push_back(field); - field.form_control_type = "password"; - field.value = test_form_.password_value; - observed_form_.fields.push_back(field); - - // Turn off waiting for server predictions in order to avoid dealing with - // posted tasks in PasswordFormManager. - PasswordFormManager::set_wait_for_server_predictions_for_filling(false); -} - -void UpdatePasswordInfoBarDelegateTest::SetUp() { - ChromeRenderViewHostTestHarness::SetUp(); - autofill::ChromeAutofillClient::CreateForWebContents(web_contents()); - ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient( - web_contents(), - autofill::ChromeAutofillClient::FromWebContents(web_contents())); -} - -void UpdatePasswordInfoBarDelegateTest::TearDown() { - ChromeRenderViewHostTestHarness::TearDown(); -} - -std::unique_ptr<password_manager::PasswordFormManager> -UpdatePasswordInfoBarDelegateTest::CreateTestFormManager() { - auto manager = std::make_unique<password_manager::PasswordFormManager>( - &client_, driver_.AsWeakPtr(), observed_form_, &fetcher_, - std::make_unique<PasswordSaveManagerImpl>( - /*profile_form_saver=*/std::make_unique< - password_manager::StubFormSaver>(), - /*account_form_saver=*/nullptr), - nullptr /* metrics_recorder */); - manager->ProvisionallySave(observed_form_, &driver_, nullptr); - return manager; -} - -std::unique_ptr<UpdatePasswordInfoBarDelegate> -UpdatePasswordInfoBarDelegateTest::CreateDelegate( - std::unique_ptr<password_manager::PasswordFormManager> - password_form_manager, - bool is_smartlock_branding_enabled) { - std::unique_ptr<UpdatePasswordInfoBarDelegate> delegate( - new TestUpdatePasswordInfoBarDelegate(web_contents(), - std::move(password_form_manager), - is_smartlock_branding_enabled)); - return delegate; -} - -TEST_F(UpdatePasswordInfoBarDelegateTest, HasDetailsMessageForSignedIn) { - std::unique_ptr<password_manager::PasswordFormManager> password_form_manager( - CreateTestFormManager()); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - true /* is_smartlock_branding_enabled */)); - EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SAVE_PASSWORD_FOOTER), - infobar->GetDetailsMessageText()); -} - -TEST_F(UpdatePasswordInfoBarDelegateTest, EmptyDetailsMessageForNotSignedIn) { - std::unique_ptr<password_manager::PasswordFormManager> password_form_manager( - CreateTestFormManager()); - std::unique_ptr<PasswordManagerInfoBarDelegate> infobar( - CreateDelegate(std::move(password_form_manager), - false /* is_smartlock_branding_enabled */)); - EXPECT_TRUE(infobar->GetDetailsMessageText().empty()); -} - -TEST_F(UpdatePasswordInfoBarDelegateTest, NoCurrentForms) { - std::vector<std::u16string> usernames; - std::vector<std::unique_ptr<password_manager::PasswordForm>> current_forms; - std::u16string default_username = u"username"; - unsigned int selected_username = - UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - current_forms, default_username, &usernames); - EXPECT_EQ(default_username, usernames[selected_username]); - EXPECT_THAT(usernames, ElementsAre(default_username)); -} - -TEST_F(UpdatePasswordInfoBarDelegateTest, MultipleCurrentForms) { - std::vector<std::unique_ptr<password_manager::PasswordForm>> current_forms; - password_manager::PasswordForm additional_form; - additional_form.username_value = u"another username"; - current_forms.push_back( - std::make_unique<password_manager::PasswordForm>(test_form_)); - current_forms.push_back( - std::make_unique<password_manager::PasswordForm>(additional_form)); - - std::u16string default_username = u"another username"; - - std::vector<std::u16string> usernames; - unsigned int selected_username = - UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - current_forms, default_username, &usernames); - EXPECT_EQ(default_username, usernames[selected_username]); - EXPECT_THAT(usernames, - ElementsAre(test_form_.username_value, default_username)); -} - -TEST_F(UpdatePasswordInfoBarDelegateTest, EmptyUsername) { - std::vector<std::unique_ptr<password_manager::PasswordForm>> current_forms; - password_manager::PasswordForm additional_form; - current_forms.push_back( - std::make_unique<password_manager::PasswordForm>(test_form_)); - current_forms.push_back( - std::make_unique<password_manager::PasswordForm>(additional_form)); - - std::u16string default_username = test_form_.username_value; - - std::vector<std::u16string> usernames; - unsigned int selected_username = - UpdatePasswordInfoBarDelegate::GetDisplayUsernames( - current_forms, default_username, &usernames); - std::u16string empty_username = - l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_EMPTY_LOGIN); - - EXPECT_EQ(default_username, usernames[selected_username]); - EXPECT_THAT(usernames, ElementsAre(default_username, empty_username)); -}
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 46d3639..d3f895f2 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -140,16 +140,11 @@ #include "chrome/browser/password_manager/android/auto_signin_first_run_dialog_android.h" #include "chrome/browser/password_manager/android/auto_signin_prompt_controller.h" #include "chrome/browser/password_manager/android/credential_leak_controller_android.h" -#include "chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h" #include "chrome/browser/password_manager/android/password_accessory_controller.h" #include "chrome/browser/password_manager/android/password_accessory_controller_impl.h" #include "chrome/browser/password_manager/android/password_generation_controller.h" #include "chrome/browser/password_manager/android/password_manager_launcher_android.h" -#include "chrome/browser/password_manager/android/save_password_infobar_delegate_android.h" -#include "chrome/browser/password_manager/android/update_password_infobar_delegate_android.h" #include "chrome/browser/touch_to_fill/touch_to_fill_controller.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "components/infobars/core/infobar.h" #include "components/messages/android/messages_feature.h" #include "components/password_manager/core/browser/credential_cache.h" #include "ui/base/ui_base_features.h" @@ -227,21 +222,6 @@ widget_host->AddInputEventObserver(observer); } -#if BUILDFLAG(IS_ANDROID) -void HideSavePasswordInfobar(content::WebContents* web_contents) { - infobars::ContentInfoBarManager* infobar_manager = - infobars::ContentInfoBarManager::FromWebContents(web_contents); - for (size_t i = 0; i < infobar_manager->infobar_count(); ++i) { - infobars::InfoBar* infobar = infobar_manager->infobar_at(i); - if (infobar->delegate()->GetIdentifier() == - SavePasswordInfoBarDelegate::SAVE_PASSWORD_INFOBAR_DELEGATE_MOBILE) { - infobar_manager->RemoveInfoBar(infobar); - break; - } - } -} -#endif // BUILDFLAG(IS_ANDROID) - #if !BUILDFLAG(IS_ANDROID) // Retrieves and formats the saved passwords domains from signon_realms. std::vector<std::string> GetMatchingDomains( @@ -350,23 +330,8 @@ if (form_to_save->IsBlocklisted()) return false; - if (update_password) { - if (messages::IsUpdatePasswordMessagesUiEnabled()) { - save_update_password_message_delegate_.DisplaySaveUpdatePasswordPrompt( - web_contents(), std::move(form_to_save), /*update_password=*/true); - } else { - UpdatePasswordInfoBarDelegate::Create(web_contents(), - std::move(form_to_save)); - } - } else { - if (messages::IsPasswordMessagesUiEnabled()) { - save_update_password_message_delegate_.DisplaySaveUpdatePasswordPrompt( - web_contents(), std::move(form_to_save), /*update_password=*/false); - } else { - SavePasswordInfoBarDelegate::Create(web_contents(), - std::move(form_to_save)); - } - } + save_update_password_message_delegate_.DisplaySaveUpdatePasswordPrompt( + web_contents(), std::move(form_to_save), update_password); #else PasswordsClientUIDelegate* manage_passwords_ui_controller = PasswordsClientUIDelegateFromWebContents(web_contents()); @@ -664,12 +629,8 @@ void ChromePasswordManagerClient::AutomaticPasswordSave( std::unique_ptr<password_manager::PasswordFormManagerForUI> saved_form) { #if BUILDFLAG(IS_ANDROID) - if (messages::IsPasswordMessagesUiEnabled()) { - generated_password_saved_message_delegate_.ShowPrompt( - web_contents(), std::move(saved_form)); - } else { - GeneratedPasswordSavedInfoBarDelegateAndroid::Create(web_contents()); - } + generated_password_saved_message_delegate_.ShowPrompt(web_contents(), + std::move(saved_form)); #else PasswordsClientUIDelegate* manage_passwords_ui_controller = PasswordsClientUIDelegateFromWebContents(web_contents()); @@ -722,10 +683,6 @@ } #if BUILDFLAG(IS_ANDROID) - if (!messages::IsPasswordMessagesUiEnabled()) { - HideSavePasswordInfobar(web_contents()); - } - auto metrics_recorder = std::make_unique< password_manager::metrics_util::LeakDialogMetricsRecorder>( web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId(),
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index e00eb53..32a8c0e 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -57,6 +57,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_enums.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_paths.h" @@ -333,19 +334,22 @@ } protected: - TestGuestViewManager* GetGuestViewManager() { + TestGuestViewManager* GetGuestViewManager( + content::BrowserContext* profile = nullptr) { + if (!profile) + profile = browser()->profile(); // TODO(wjmaclean): Re-implement FromBrowserContext in the // TestGuestViewManager class to avoid all callers needing this cast. auto* manager = static_cast<TestGuestViewManager*>( - TestGuestViewManager::FromBrowserContext(browser()->profile())); + TestGuestViewManager::FromBrowserContext(profile)); // Test code may access the TestGuestViewManager before it would be created // during creation of the first guest. if (!manager) { manager = static_cast<TestGuestViewManager*>( GuestViewManager::CreateWithDelegate( - browser()->profile(), + profile, ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate( - browser()->profile()))); + profile))); } return manager; } @@ -4587,3 +4591,66 @@ ASSERT_TRUE(content::WaitForLoadStop(GetActiveWebContents())); EXPECT_EQ(CountPDFProcesses(), 0); } + +// Exercise a race condition where the profile is destroyed in the middle of a +// PDF navigation and ensure that this doesn't crash. Specifically, +// `PdfNavigationThrottle` intercepts PDF navigations to PDF stream URLs, +// cancels them, and posts a task to navigate to the original URL instead. +// Triggering profile destruction after this task is posted but before it runs +// has previously led to issues in https://crbug.com/1382761. +IN_PROC_BROWSER_TEST_F(PDFExtensionTest, PdfNavigationDuringProfileShutdown) { + // Open an Incognito window and navigate it to a page with a PDF embedded in + // an iframe. + Browser* incognito = CreateIncognitoBrowser(); + content::WebContents* incognito_contents = + incognito->tab_strip_model()->GetActiveWebContents(); + incognito_contents->GetController().LoadURL( + embedded_test_server()->GetURL("/pdf/test-cross-site-iframe.html"), + content::Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); + + // Wait for the MimeHandleView guest to be created. This should return + // before the actual PDF navigation in the guest is started. + GuestViewBase* guest_view = GetGuestViewManager(incognito->profile()) + ->WaitForSingleGuestViewCreated(); + ASSERT_TRUE(guest_view); + + // Look up the PDF stream URL to which the navigation will take place. + extensions::MimeHandlerViewGuest* guest = + extensions::MimeHandlerViewGuest::FromWebContents( + guest_view->web_contents()); + ASSERT_TRUE(guest); + base::WeakPtr<extensions::StreamContainer> stream = guest->GetStreamWeakPtr(); + EXPECT_TRUE(stream); + GURL stream_url(stream->stream_url()); + + // Use TestNavigationManager to wait for first yield after running + // DidStartNavigation throttles. This should be precisely after the + // navigation to the stream URL gets canceled and the task to start a new + // navigation to the original URL is scheduled. + { + content::TestNavigationManager manager(guest_view->web_contents(), + stream_url); + manager.WaitForFirstYieldAfterDidStartNavigation(); + } + + // Now, close Incognito and destroy its profile. This is subtle: simply + // closing the Incognito window and waiting for browser destruction (e.g., + // with `ui_test_utils::WaitForBrowserToClose(incognito)`) will trigger + // asynchronous profile destruction which will allow the PDF task to run + // before profile destruction is complete, sidestepping the bug in + // https://crbug.com/1382761. Instead, use the hard shutdown/restart logic + // similar to that in `BrowserCloseManager::CloseBrowsers()`, which is used + // by `chrome::ExitIgnoreUnloadHandlers() and forces the `Browser` and its + // profile shutdown to complete synchronously, but only on the Incognito + // Browser object. Note that we can't just use + // `chrome::ExitIgnoreUnloadHandlers()` here, as that shuts down all Browser + // objects and the rest of the browser process and appears to be unsupported + // in tests. + chrome::CloseWindow(incognito); + BrowserView* incognito_view = static_cast<BrowserView*>(incognito->window()); + incognito_view->DestroyBrowser(); + + // The test succeeds if it doesn't crash when the posted PDF task attempts to + // run (the task should be canceled/ignored), so wait for this to happen. + base::RunLoop().RunUntilIdle(); +}
diff --git a/chrome/browser/predictors/loading_predictor_browsertest.cc b/chrome/browser/predictors/loading_predictor_browsertest.cc index b990ee5..5895f4e6 100644 --- a/chrome/browser/predictors/loading_predictor_browsertest.cc +++ b/chrome/browser/predictors/loading_predictor_browsertest.cc
@@ -663,46 +663,6 @@ }; } // namespace -// Tests that the LoadingPredictor doesn't preconnect during a prerender. -IN_PROC_BROWSER_TEST_F(LoadingPredictorBrowserTest, - PrepareForPageLoadDuringPrerender) { - GURL url("http://test.com"); - base::RunLoop prerender_run_loop; - TestPrerenderStopObserver prerender_observer( - prerender_run_loop.QuitClosure()); - - prerender::NoStatePrefetchManager* no_state_prefetch_manager = - prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( - browser()->profile()); - - std::unique_ptr<prerender::NoStatePrefetchHandle> handle = - no_state_prefetch_manager->StartPrefetchingFromNavigationPredictor( - url, - browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->GetController() - .GetDefaultSessionStorageNamespace(), - gfx::Size(640, 480)); - ASSERT_TRUE(handle); - handle->SetObserver(&prerender_observer); - prerender_run_loop.Run(); - - net::SchemefulSite site = net::SchemefulSite(url); - net::NetworkAnonymizationKey network_anonymization_key(site, site); - // Ensure that the prerender does not make a host lookup or attempt to - // preconnect. - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(preconnect_manager_observer()->HasHostBeenLookedUp( - url.host(), network_anonymization_key)); - EXPECT_FALSE(preconnect_manager_observer()->HasHostBeenLookedUp( - "", network_anonymization_key)); - EXPECT_FALSE(preconnect_manager_observer()->HasOriginAttemptedToPreconnect( - url.DeprecatedGetOriginAsURL())); - EXPECT_FALSE( - preconnect_manager_observer()->HasOriginAttemptedToPreconnect(GURL())); -} - // Tests that the LoadingPredictor preconnects to the main frame origin even if // it doesn't have any prediction for this origin. IN_PROC_BROWSER_TEST_F(LoadingPredictorBrowserTest,
diff --git a/chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_unittest.cc b/chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_unittest.cc index 6cd45f0..c6ec34e 100644 --- a/chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_unittest.cc +++ b/chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_unittest.cc
@@ -366,18 +366,6 @@ EXPECT_TRUE(AddSimpleLinkTrigger(url)); } -TEST_F(PrerendererNavigationPredictorPrefetchHoldbackTest, - PredictorPrefetchHoldbackPredictorReferrer) { - GURL url("http://www.notgoogle.com/"); - no_state_prefetch_manager()->CreateNextNoStatePrefetchContents( - url, absl::nullopt, ORIGIN_NAVIGATION_PREDICTOR, - FINAL_STATUS_PROFILE_DESTROYED); - EXPECT_EQ( - nullptr, - no_state_prefetch_manager()->StartPrefetchingFromNavigationPredictor( - url, nullptr, gfx::Size())); -} - // Verify that link-rel:next URLs are not prefetched. TEST_F(NoStatePrefetchTest, LinkRelNextWithNSPDisabled) { GURL url("http://www.notgoogle.com/"); @@ -410,19 +398,6 @@ EXPECT_TRUE(AddSimpleLinkTrigger(url)); } -TEST_F(PrerendererNavigationPredictorPrefetchHoldbackDisabledTest, - PredictorPrefetchHoldbackOffPredictorReferrer) { - GURL url("http://www.notgoogle.com/"); - no_state_prefetch_manager()->CreateNextNoStatePrefetchContents( - url, absl::nullopt, ORIGIN_NAVIGATION_PREDICTOR, - FINAL_STATUS_PROFILE_DESTROYED); - - EXPECT_NE( - nullptr, - no_state_prefetch_manager()->StartPrefetchingFromNavigationPredictor( - url, nullptr, gfx::Size())); -} - // Flaky on Android and Mac, crbug.com/1087876. TEST_F(NoStatePrefetchTest, DISABLED_PrerenderDisabledOnLowEndDevice) { GURL url("http://www.google.com/");
diff --git a/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc b/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc index ee72fb2..62bec597f 100644 --- a/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc +++ b/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_browsertest.cc
@@ -139,8 +139,6 @@ namespace { -constexpr gfx::Size kSize(640, 480); - const char kAllowedUAClientHint[] = "sec-ch-ua"; const char kAllowedUAMobileClientHint[] = "sec-ch-ua-mobile"; const char kAllowedUAPlatformClientHint[] = "sec-ch-ua-platform"; @@ -630,18 +628,6 @@ EXPECT_TRUE(ExecuteScript(GetWebContents(), speculation_script)); } - std::unique_ptr<prerender::NoStatePrefetchHandle> StartPrerender( - const GURL& url) { - prerender::NoStatePrefetchManager* no_state_prefetch_manager = - prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( - browser()->profile()); - - return no_state_prefetch_manager->StartPrefetchingFromNavigationPredictor( - url, - GetWebContents()->GetController().GetDefaultSessionStorageNamespace(), - kSize); - } - network::mojom::CustomProxyConfigPtr WaitForUpdatedCustomProxyConfig() { PrefetchProxyService* prefetch_proxy_service = PrefetchProxyServiceFactory::GetForProfile(browser()->profile()); @@ -915,8 +901,9 @@ std::unique_ptr<net::test_server::HttpResponse> HandleProxyRequest( const net::test_server::HttpRequest& request) { - if (request.all_headers.find("CONNECT auth_challenge.com:443") != - std::string::npos) { + EXPECT_EQ(request.method, net::test_server::METHOD_CONNECT); + + if (request.relative_url == "auth-challenge.test:443") { std::unique_ptr<net::test_server::BasicHttpResponse> resp = std::make_unique<net::test_server::BasicHttpResponse>(); resp->set_code(net::HTTP_UNAUTHORIZED); @@ -924,38 +911,21 @@ return resp; } - if (request.all_headers.find("CONNECT error.com:443") != - std::string::npos) { + if (request.relative_url == "error.test:443") { std::unique_ptr<net::test_server::BasicHttpResponse> resp = std::make_unique<net::test_server::BasicHttpResponse>(); resp->set_code(net::HTTP_BAD_REQUEST); return resp; } - std::vector<std::string> request_lines = - base::SplitString(request.all_headers, "\r\n", base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - DCHECK(!request_lines.empty()); - - std::vector<std::string> request_line = - base::SplitString(request_lines[0], " ", base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - DCHECK_EQ(3U, request_line.size()); - EXPECT_EQ("CONNECT", request_line[0]); - EXPECT_EQ("HTTP/1.1", request_line[2]); - - GURL request_origin("https://" + request_line[1]); + GURL request_origin("https://" + request.relative_url); EXPECT_TRUE("a.test" == request_origin.host() || "b.test" == request_origin.host()); - bool found_chrome_tunnel_header = false; - for (const std::string& header : request_lines) { - if (base::Contains(header, "chrome-tunnel") && - base::Contains(header, "key=" + google_apis::GetAPIKey())) { - found_chrome_tunnel_header = true; - break; - } - } + auto iter = request.headers.find("chrome-tunnel"); + bool found_chrome_tunnel_header = + iter != request.headers.end() && + base::Contains(iter->second, "key=" + google_apis::GetAPIKey()); EXPECT_TRUE(found_chrome_tunnel_header); auto new_tunnel = std::make_unique<TestProxyTunnelConnection>(); @@ -1127,7 +1097,7 @@ auth_observer->Reset(); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank"))); GURL doc_url("https://www.google.com/search?q=test"); - MakeNavigationPrediction(doc_url, {GURL("https://auth_challenge.com/")}); + MakeNavigationPrediction(doc_url, {GURL("https://auth-challenge.test/")}); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(auth_observer->GotAuthChallenge()); @@ -1142,7 +1112,7 @@ PrefetchProxyTabHelper::FromWebContents(GetWebContents()); TestTabHelperObserver tab_helper_observer(tab_helper); - GURL error_url("https://error.com/"); + GURL error_url("https://error.test/"); base::RunLoop run_loop; tab_helper_observer.SetOnPrefetchErrorClosure(run_loop.QuitClosure());
diff --git a/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor_unittest.cc b/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor_unittest.cc index e7d8c79..64d3d7da 100644 --- a/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor_unittest.cc +++ b/chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor_unittest.cc
@@ -19,12 +19,6 @@ #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" #include "url/gurl.h" -namespace { - -const gfx::Size kSize(640, 480); - -} // namespace - // These tests leak mojo objects (like the PrefetchProxyURLLoader) because // they do not have valid mojo channels, which would normally delete the bound // objects on destruction. This is expected and cannot be easily fixed without @@ -86,18 +80,6 @@ ChromeRenderViewHostTestHarness::TearDown(); } - std::unique_ptr<prerender::NoStatePrefetchHandle> StartPrerender( - const GURL& url) { - prerender::NoStatePrefetchManager* no_state_prefetch_manager = - prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( - profile()); - - return no_state_prefetch_manager->StartPrefetchingFromNavigationPredictor( - url, - web_contents()->GetController().GetDefaultSessionStorageNamespace(), - kSize); - } - void WaitForCallback() { if (was_intercepted_.has_value()) return;
diff --git a/chrome/browser/reading_list/android/reading_list_manager_impl_unittest.cc b/chrome/browser/reading_list/android/reading_list_manager_impl_unittest.cc index 8c29469b..04a6a06 100644 --- a/chrome/browser/reading_list/android/reading_list_manager_impl_unittest.cc +++ b/chrome/browser/reading_list/android/reading_list_manager_impl_unittest.cc
@@ -102,9 +102,9 @@ // Verifies load data into reading list model will update |manager_| as well. TEST_F(ReadingListManagerImplTest, Load) { // Load data into reading list model. - auto entries = std::make_unique<ReadingListEntries>(); + ReadingListEntries entries; GURL url(kURL); - entries->emplace(url, ReadingListEntry(url, kTitle, clock()->Now())); + entries.emplace(url, ReadingListEntry(url, kTitle, clock()->Now())); reading_list_model()->StoreLoaded(std::move(entries)); const auto* node = manager()->Get(url);
diff --git a/chrome/browser/resources/browsing_topics/browsing_topics_internals.ts b/chrome/browser/resources/browsing_topics/browsing_topics_internals.ts index 2d45510..bc2f0e6a 100644 --- a/chrome/browser/resources/browsing_topics/browsing_topics_internals.ts +++ b/chrome/browser/resources/browsing_topics/browsing_topics_internals.ts
@@ -163,7 +163,8 @@ async function asyncGetBrowsingTopicsState(calculateNow: boolean) { // Clear and hide existing content. - document.querySelector('#epoch-div-list-wrapper')!.innerHTML = ''; + document.querySelector('#epoch-div-list-wrapper')!.innerHTML = + window.trustedTypes!.emptyHTML; setElementVisible('topics-state-override-status-message-div', false); setElementVisible('topics-state-div', false); @@ -278,7 +279,7 @@ const div = document.querySelector<HTMLElement>( '#hosts-classification-input-validation-error'); - div!.innerHTML = ''; + div!.innerHTML = window.trustedTypes!.emptyHTML; setElementVisible('hosts-classification-loader-div', false); setElementVisible('hosts-classification-input-validation-error', false);
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn index adb3d150..280115d 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
@@ -22,7 +22,7 @@ "background/braille/cursor_dots.js", "background/braille/pan_strategy.js", "injected/api_implementation.js", - "injected/extension_bridge.js", + "injected/content_script_bridge.js", "injected/loader.js", "injected/script_installer.js", "third_party/tamachiyomi/ja_phonetic_data.js", @@ -143,7 +143,6 @@ "common/role_type.js", "common/spannable.js", "common/tree_dumper.js", - "common/tts_base.js", "common/tts_interface.js", "common/tts_types.js", "learn_mode/learn_mode.js",
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js index eac102af..78bb406 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js
@@ -8,12 +8,12 @@ */ import {constants} from '../../common/constants.js'; +import {AbstractTts} from '../common/abstract_tts.js'; import {BridgeConstants} from '../common/bridge_constants.js'; import {BridgeHelper} from '../common/bridge_helper.js'; import {CompositeTts} from '../common/composite_tts.js'; import {Msgs} from '../common/msgs.js'; import {PanelCommand, PanelCommandType} from '../common/panel_command.js'; -import {ChromeTtsBase} from '../common/tts_base.js'; import {TtsCapturingEventListener, TtsInterface} from '../common/tts_interface.js'; import * as ttsTypes from '../common/tts_types.js'; @@ -108,7 +108,7 @@ /** * This class is the default implementation for TTS in the background context. */ -export class PrimaryTts extends ChromeTtsBase { +export class PrimaryTts extends AbstractTts { constructor() { super();
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js index 4a1cb82..8e3fb438 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/abstract_tts.js
@@ -12,6 +12,15 @@ import * as ttsTypes from './tts_types.js'; /** + * @typedef {{ + * pitch: number, + * rate: number, + * volume: number, + * }} + */ +let PropertyValues; + +/** * Creates a new instance. * @implements {TtsInterface} */ @@ -23,39 +32,67 @@ * Default value for TTS properties. * Note that these as well as the subsequent properties might be different * on different host platforms (like Chrome, Android, etc.). - * @type {{pitch : number, - * rate: number, - * volume: number}} - * @protected + * @protected {PropertyValues} */ - this.propertyDefault = {'rate': 0.5, 'pitch': 0.5, 'volume': 0.5}; + this.propertyDefault; /** * Min value for TTS properties. - * @type {{pitch : number, - * rate: number, - * volume: number}} - * @protected + * @protected {PropertyValues} */ - this.propertyMin = {'rate': 0.0, 'pitch': 0.0, 'volume': 0.0}; + this.propertyMin; /** * Max value for TTS properties. - * @type {{pitch : number, - * rate: number, - * volume: number}} - * @protected + * @protected {PropertyValues} */ - this.propertyMax = {'rate': 1.0, 'pitch': 1.0, 'volume': 1.0}; + this.propertyMax; /** * Step value for TTS properties. - * @type {{pitch : number, - * rate: number, - * volume: number}} - * @protected + * @protected {PropertyValues} */ - this.propertyStep = {'rate': 0.1, 'pitch': 0.1, 'volume': 0.1}; + this.propertyStep; + + this.init_(); + } + + /** @private */ + init_() { + const pitchDefault = 1; + const pitchMin = 0.2; + const pitchMax = 2.0; + const pitchStep = 0.1; + + const rateDefault = 1; + const rateMin = 0.2; + const rateMax = 5.0; + const rateStep = 0.1; + + const volumeDefault = 1; + const volumeMin = 0.2; + const volumeMax = 1.0; + const volumeStep = 0.1; + + this.propertyDefault = { + pitch: pitchDefault, + rate: rateDefault, + volume: volumeDefault, + }; + + this.propertyMin = { + pitch: pitchMin, + rate: rateMin, + volume: volumeMin, + }; + + this.propertyMax = { + pitch: pitchMax, + rate: rateMax, + volume: volumeMax, + }; + + this.propertyStep = {rate: rateStep, pitch: pitchStep, volume: volumeStep}; if (AbstractTts.substitutionDictionaryRegexp_ === undefined) { // Create an expression that matches all words in the substitution
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/content_script_bridge.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/content_script_bridge.js index a5113724..31e00a5 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/content_script_bridge.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/content_script_bridge.js
@@ -3,13 +3,12 @@ // found in the LICENSE file. /** - * @fileoverview Bridge to aid in communication between a Chrome - * background page and content script. + * @fileoverview Bridge to aid in communication between the ChromeVox background + * page and content script. * * Use addMessageListener() to provide a message listener. * Messages can be any object that can be serialized using JSON. */ - export class ContentScriptBridge { /** @private */ constructor() { @@ -45,7 +44,7 @@ * The function gets called with two parameters: the message, and a * port that can be used to send replies. * - * @param {function(Object, Port)} listener The message listener. + * @param {function(Object, Port)} listener */ static addMessageListener(listener) { ContentScriptBridge.instance.messageListeners_.push(listener); @@ -108,18 +107,18 @@ * The name of the port between the content script and background page. * @const {string} */ -ContentScriptBridge.PORT_NAME = 'ExtensionBridge.Port'; +ContentScriptBridge.PORT_NAME = 'ContentScriptBridge.Port'; /** * The name of the message between the content script and background to * see if they're connected. * @const {string} */ -ContentScriptBridge.PING_MSG = 'ExtensionBridge.Ping'; +ContentScriptBridge.PING_MSG = 'ContentScriptBridge.Ping'; /** * The name of the message between the background and content script to * confirm that they're connected. * @const {string} */ -ContentScriptBridge.PONG_MSG = 'ExtensionBridge.Pong'; +ContentScriptBridge.PONG_MSG = 'ContentScriptBridge.Pong';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/tts_base.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/tts_base.js deleted file mode 100644 index d0a68e8..0000000 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/tts_base.js +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview A base class for Tts living on Chrome platforms. - * - */ -import {AbstractTts} from './abstract_tts.js'; - -export class ChromeTtsBase extends AbstractTts { - constructor() { - super(); - this.propertyDefault['pitch'] = 1; - this.propertyMin['pitch'] = 0.2; - this.propertyMax['pitch'] = 2.0; - - this.propertyDefault['rate'] = 1; - this.propertyMin['rate'] = 0.2; - this.propertyMax['rate'] = 5.0; - - this.propertyDefault['volume'] = 1; - this.propertyMin['volume'] = 0.2; - this.propertyMax['volume'] = 1.0; - } -}
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/injected/api_implementation.js b/chrome/browser/resources/chromeos/accessibility/chromevox/injected/api_implementation.js index 575a6f2..52593ea 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/injected/api_implementation.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/injected/api_implementation.js
@@ -10,7 +10,7 @@ goog.provide('ApiImplementation'); -goog.require('ContentExtensionBridge'); +goog.require('ContentScriptBridge'); goog.require('ScriptInstaller'); ApiImplementation = class { @@ -24,7 +24,7 @@ console.error('Unable to install api script'); } - ContentExtensionBridge.addDisconnectListener(function() { + ContentScriptBridge.addDisconnectListener(function() { ApiImplementation.port.postMessage(ApiImplementation.DISCONNECT_MSG); ScriptInstaller.uninstallScript('cvoxapi'); }); @@ -82,7 +82,7 @@ properties, }; - ContentExtensionBridge.send(message); + ContentScriptBridge.send(message); } };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/injected/extension_bridge.js b/chrome/browser/resources/chromeos/accessibility/chromevox/injected/content_script_bridge.js similarity index 82% rename from chrome/browser/resources/chromeos/accessibility/chromevox/injected/extension_bridge.js rename to chrome/browser/resources/chromeos/accessibility/chromevox/injected/content_script_bridge.js index afa94574..70bfda8a 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/injected/extension_bridge.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/injected/content_script_bridge.js
@@ -7,9 +7,9 @@ * background page and content script. */ -goog.provide('ContentExtensionBridge'); +goog.provide('ContentScriptBridge'); -ContentExtensionBridge = class { +ContentScriptBridge = class { /** @private */ constructor() { /** @private {!Array<!function()>} */ @@ -30,12 +30,12 @@ /** Initialize the extension bridge. */ static init() { - ContentExtensionBridge.instance = new ContentExtensionBridge(); + ContentScriptBridge.instance = new ContentScriptBridge(); } /** @param {Object} message The message to be sent. */ static send(message) { - ContentExtensionBridge.instance.send_(message); + ContentScriptBridge.instance.send_(message); } /** @@ -44,7 +44,7 @@ * @param {function()} listener The listener. */ static addDisconnectListener(listener) { - ContentExtensionBridge.instance.disconnectListeners_.push(listener); + ContentScriptBridge.instance.disconnectListeners_.push(listener); } /** @@ -80,7 +80,7 @@ */ setupBackgroundPort_() { this.backgroundPort_ = - chrome.extension.connect({name: ContentExtensionBridge.PORT_NAME}); + chrome.extension.connect({name: ContentScriptBridge.PORT_NAME}); if (!this.backgroundPort_) { return; } @@ -94,8 +94,8 @@ * @private */ onMessage_(message) { - if (message[ContentExtensionBridge.PONG_MSG]) { - this.gotPongFromBackgroundPage_(message[ContentExtensionBridge.PONG_MSG]); + if (message[ContentScriptBridge.PONG_MSG]) { + this.gotPongFromBackgroundPage_(message[ContentScriptBridge.PONG_MSG]); } } @@ -123,7 +123,7 @@ } this.pingAttempts_++; - if (this.pingAttempts_ > ContentExtensionBridge.MAX_PING_ATTEMPTS) { + if (this.pingAttempts_ > ContentScriptBridge.MAX_PING_ATTEMPTS) { // Could not connect after several ping attempts. Call the disconnect // handlers, which will disable ChromeVox. this.disconnectListeners_.forEach(listener => listener()); @@ -132,7 +132,7 @@ // Send the ping. const msg = { - [ContentExtensionBridge.PING_MSG]: 1, + [ContentScriptBridge.PING_MSG]: 1, }; if (!this.backgroundPort_) { @@ -145,7 +145,7 @@ // Check again after a short while in case we get no response. setTimeout( () => this.tryToPingBackgroundPage_(), - ContentExtensionBridge.TIME_BETWEEN_PINGS_MS); + ContentScriptBridge.TIME_BETWEEN_PINGS_MS); } /** @@ -190,26 +190,26 @@ * The name of the port between the content script and background page. * @const {string} */ -ContentExtensionBridge.PORT_NAME = 'ExtensionBridge.Port'; +ContentScriptBridge.PORT_NAME = 'ContentScriptBridge.Port'; /** * The name of the message between the content script and background to * see if they're connected. * @const {string} */ -ContentExtensionBridge.PING_MSG = 'ExtensionBridge.Ping'; +ContentScriptBridge.PING_MSG = 'ContentScriptBridge.Ping'; /** * The name of the message between the background and content script to * confirm that they're connected. * @const {string} */ -ContentExtensionBridge.PONG_MSG = 'ExtensionBridge.Pong'; +ContentScriptBridge.PONG_MSG = 'ContentScriptBridge.Pong'; /** @const {number} */ -ContentExtensionBridge.MAX_PING_ATTEMPTS = 5; +ContentScriptBridge.MAX_PING_ATTEMPTS = 5; /** @const {number} */ -ContentExtensionBridge.TIME_BETWEEN_PINGS_MS = 500; +ContentScriptBridge.TIME_BETWEEN_PINGS_MS = 500; -ContentExtensionBridge.init(); +ContentScriptBridge.init();
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/testing/chromevox_e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/chromevox/testing/chromevox_e2e_test_base.js index 9a43f5b8..a798348 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/testing/chromevox_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/testing/chromevox_e2e_test_base.js
@@ -18,11 +18,6 @@ testGenCppIncludes() { super.testGenCppIncludes(); GEN(` - #include "ash/accessibility/accessibility_delegate.h" - #include "ash/shell.h" - #include "base/bind.h" - #include "base/callback.h" - #include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "extensions/common/extension_l10n_util.h" `); }
diff --git a/chrome/browser/resources/chromeos/accessibility/common/testing/common_e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/common/testing/common_e2e_test_base.js index 9395b41..523d05f5 100644 --- a/chrome/browser/resources/chromeos/accessibility/common/testing/common_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/common/testing/common_e2e_test_base.js
@@ -10,18 +10,6 @@ */ CommonE2ETestBase = class extends E2ETestBase { /** @override */ - testGenCppIncludes() { - super.testGenCppIncludes(); - GEN(` -#include "ash/accessibility/accessibility_delegate.h" -#include "ash/shell.h" -#include "base/bind.h" -#include "base/callback.h" -#include "chrome/browser/ash/accessibility/accessibility_manager.h" - `); - } - - /** @override */ testGenPreamble() { super.testGenPreamble(); // Note that at least one accessibility common feature has to be enabled for
diff --git a/chrome/browser/resources/chromeos/accessibility/common/testing/e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/common/testing/e2e_test_base.js index 9cb4682..4d50b27 100644 --- a/chrome/browser/resources/chromeos/accessibility/common/testing/e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/common/testing/e2e_test_base.js
@@ -33,6 +33,11 @@ /** @override */ testGenCppIncludes() { GEN(` + #include "ash/accessibility/accessibility_delegate.h" + #include "ash/shell.h" + #include "base/bind.h" + #include "base/callback.h" + #include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "chrome/browser/ash/crosapi/browser_manager.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/ui/browser.h"
diff --git a/chrome/browser/resources/chromeos/accessibility/enhanced_network_tts/enhanced_network_tts_e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/enhanced_network_tts/enhanced_network_tts_e2e_test_base.js index 4452978..99b25c8b 100644 --- a/chrome/browser/resources/chromeos/accessibility/enhanced_network_tts/enhanced_network_tts_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/enhanced_network_tts/enhanced_network_tts_e2e_test_base.js
@@ -31,17 +31,6 @@ } /** @override */ - testGenCppIncludes() { - super.testGenCppIncludes(); - GEN(` -#include "ash/shell.h" -#include "base/bind.h" -#include "base/callback.h" -#include "chrome/browser/ash/accessibility/accessibility_manager.h" - `); - } - - /** @override */ testGenPreamble() { // TODO(leileilei@google.com): Figure out a better way to test Enhanced // Network TTS. Currently, loads Select-to-Speak for quick testing purpose.
diff --git a/chrome/browser/resources/chromeos/accessibility/select_to_speak/select_to_speak_e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/select_to_speak/select_to_speak_e2e_test_base.js index da32f90..665d84e 100644 --- a/chrome/browser/resources/chromeos/accessibility/select_to_speak/select_to_speak_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/select_to_speak/select_to_speak_e2e_test_base.js
@@ -12,12 +12,7 @@ testGenCppIncludes() { super.testGenCppIncludes(); GEN(` -#include "ash/accessibility/accessibility_delegate.h" #include "ash/keyboard/ui/keyboard_util.h" -#include "ash/shell.h" -#include "base/bind.h" -#include "base/callback.h" -#include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "ui/accessibility/accessibility_features.h" `); }
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/switch_access_e2e_test_base.js b/chrome/browser/resources/chromeos/accessibility/switch_access/switch_access_e2e_test_base.js index bc19af1..bbcc028 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/switch_access_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/switch_access_e2e_test_base.js
@@ -13,11 +13,6 @@ testGenCppIncludes() { super.testGenCppIncludes(); GEN(` -#include "ash/accessibility/accessibility_delegate.h" -#include "ash/shell.h" -#include "base/bind.h" -#include "base/callback.h" -#include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "ash/keyboard/ui/keyboard_util.h" `); }
diff --git a/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.html b/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.html new file mode 100644 index 0000000..0dbf8bb --- /dev/null +++ b/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.html
@@ -0,0 +1,134 @@ +<!DOCTYPE html> +<html> +<head> + <style> + :root { + color: #333; + font-family: 'Google Sans', Roboto, sans-serif; + font-size: 13px; + font-weight: 400; /* roboto-regular */ + } + + body { + margin: 0; + } + + #recommend-apps-container { + box-sizing: border-box; + display: flex; + flex-flow: row wrap; + gap: 16px; + overflow: hidden; + padding: 2px; + } + + #recommend-apps-container .item { + display: flex; + flex: 0 0 calc((100% - 32px) / 3); /* This size allows <= 3 items in a row */ + flex-flow: row nowrap; + float: left; + max-width: 280px; + min-width: 156px; + position: relative; + user-select: none; + } + + #recommend-apps-container .item .image-picker { + background: url(images/ic_checkmark.svg) no-repeat; + display: none; + flex-shrink: 0; + transform: translate(-32px, 8px); + width: 24px; + } + + #recommend-apps-container .item.checked .image-picker { + display: block; + } + + #recommend-apps-container .item .chip { + border-radius: 8px; + box-shadow: + 1px 1px 4px rgba(60, 64, 67, 0.30), + 1px 2px 4px 1px rgba(60, 64, 67, 0.15); + flex-shrink: 0; + height: 160px; + position: relative; + width: 100%; + --x: 0; + --y: 0; + } + + #recommend-apps-container .item .chip .chip-content-container { + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; + position: relative; + text-align: center; + } + + #recommend-apps-container .item .chip:focus, + #recommend-apps-container .item .chip .chip-content-container:focus { + outline: none; + } + + #recommend-apps-container .item .chip:focus > .chip-content-container { + outline: 2px solid rgba(26, 115, 232, 0.5); + } + + @keyframes ripple { + 30% { + transform: scale(7); + } + 100% { + opacity: 0; + } + } + + #recommend-apps-container .item .chip .chip-content-container .ripple { + animation: ripple 1s forwards; + background: rgba(32, 33, 36, 0.14); + border-radius: 50%; + height: 100px; + margin-inline-start: calc(var(--x) * 1px); + margin-top: calc(var(--y) * 1px); + position: absolute; + transform: translate(-50%, -50%); + width: 100px; + } + + #recommend-apps-container .item .chip:active { + box-shadow: + 0 1px 2px 0 rgba(60, 64, 67, 0.30), + 0 3px 6px 2px rgba(60, 64, 67, 0.15); + } + + img.app-icon { + height: 48px; + margin-bottom: 20px; + margin-inline: auto; + margin-top: 32px; + vertical-align: middle; + width: 48px; + } + + span.app-title { + color: rgb(32, 33, 36); + display: inline-block; + font-size: 13px; + line-height: 20px; + margin-bottom: 20px; + margin-inline: 8px; + overflow: hidden; + text-overflow: ellipsis; + vertical-align: middle; + white-space: nowrap; + } + </style> +</head> +<body> + <div id="scroll-top"></div> + <div id="recommend-apps-container"></div> + <div id="scroll-bottom"></div> +</body> +</html>
diff --git a/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.js b/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.js new file mode 100644 index 0000000..9f54be6 --- /dev/null +++ b/chrome/browser/resources/chromeos/arc_support/recommend_app_list_view.js
@@ -0,0 +1,150 @@ +// Copyright 2018 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +let appWindow; +let appOrigin; + +function generateContents(appIcon, appTitle, appPackageName) { + const doc = document; + const recommendAppsContainer = doc.getElementById('recommend-apps-container'); + const item = doc.createElement('div'); + item.classList.add('item'); + item.setAttribute('data-packagename', appPackageName); + + const chip = doc.createElement('div'); + chip.classList.add('chip'); + chip.tabIndex = 0; + chip.addEventListener('mousedown', addRippleCircle_); + chip.addEventListener('mouseup', toggleCheckStatus_); + chip.addEventListener('animationend', removeRippleCircle_); + + // Add keyboard events + let keyEventFired = false; + chip.addEventListener('keydown', function(e) { + if (!keyEventFired && isConfirmKey_(e)) { + addRippleCircle_(e); + } + keyEventFired = true; + }); + chip.addEventListener('keyup', function(e) { + if (isConfirmKey_(e)) { + toggleCheckStatus_(e); + keyEventFired = false; + } + }); + + const chipContent = doc.createElement('div'); + chipContent.classList.add('chip-content-container'); + chipContent.tabIndex = -1; + chip.appendChild(chipContent); + + item.appendChild(chip); + + const img = doc.createElement('img'); + img.classList.add('app-icon'); + img.setAttribute('src', decodeURIComponent(appIcon)); + + const title = doc.createElement('span'); + title.classList.add('app-title'); + title.innerHTML = appTitle; + + chipContent.appendChild(img); + chipContent.appendChild(title); + + const imagePicker = doc.createElement('div'); + imagePicker.classList.add('image-picker'); + imagePicker.addEventListener('click', toggleCheckStatus_); + item.appendChild(imagePicker); + + recommendAppsContainer.appendChild(item); +} + +/** + * Add a layer on top of the chip to create the ripple effect. + * @param {!Event} e + * @private + */ +function addRippleCircle_(e) { + const chip = e.currentTarget; + const item = chip.parentNode; + const offsetX = e.pageX - item.offsetLeft; + const offsetY = e.pageY - item.offsetTop; + chip.style.setProperty('--x', offsetX); + chip.style.setProperty('--y', offsetY); + const chipContent = chip.querySelector('.chip-content-container'); + chipContent.innerHTML += '<div class="ripple"></div>'; +} + +/** + * After the animation ends, remove the ripple layer. + * @param {!Event} e + * @private + */ +function removeRippleCircle_(e) { + const chip = e.currentTarget; + const rippleLayers = chip.querySelectorAll('.ripple'); + for (const rippleLayer of rippleLayers) { + if (rippleLayer.className === 'ripple') { + rippleLayer.remove(); + } + } +} + +/** + * Toggle the check status of an app. If an app is selected, add the "checked" + * lass so that the checkmark is visible. Otherwise, remove the checked class. + * @param {!Event} e + * @private + */ +function toggleCheckStatus_(e) { + const item = e.currentTarget.parentNode; + item.classList.toggle('checked'); + + sendNumberOfSelectedApps(); +} + +function getSelectedPackages() { + const selectedPackages = []; + const checkedItems = document.getElementsByClassName('checked'); + for (const checkedItem of checkedItems) { + selectedPackages.push(checkedItem.dataset.packagename); + } + return selectedPackages; +} + +function isConfirmKey_(e) { + return e.keyCode === 13 // Enter + || e.keyCode === 32; // Space +} + +/** + * Send the number of selected apps back to the embedding page. + */ +function sendNumberOfSelectedApps() { + if (appWindow && appOrigin) { + const checkedItems = document.querySelectorAll('.checked'); + appWindow.postMessage( + {type: 'NUM_OF_SELECTED_APPS', numOfSelected: checkedItems.length}, + appOrigin); + } +} + +function onMessage_(e) { + appWindow = e.source; + appOrigin = e.origin; +} + +/** + * Mark all recommended apps as checked. + */ +function selectAll() { + const allItems = document.getElementsByClassName('item'); + for (const item of allItems) { + item.classList.add('checked'); + } + + sendNumberOfSelectedApps(); +} + +window.addEventListener('message', onMessage_);
diff --git a/chrome/browser/resources/chromeos/emoji_picker/BUILD.gn b/chrome/browser/resources/chromeos/emoji_picker/BUILD.gn index b9459df..0645956 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/BUILD.gn +++ b/chrome/browser/resources/chromeos/emoji_picker/BUILD.gn
@@ -9,13 +9,13 @@ import("//ui/webui/resources/tools/generate_grd.gni") web_component_files = [ - "emoji_button.js", + "emoji_button.ts", "emoji_category_button.ts", "emoji_group.ts", "emoji_group_button.ts", "emoji_picker.js", - "emoji_search.js", - "emoji_variants.js", + "emoji_search.ts", + "emoji_variants.ts", "text_group_button.js", ] @@ -63,6 +63,11 @@ outputs = [ "$preprocessed_folder/fuse.js" ] } +copy("copy_fuse_dts") { + sources = [ "//third_party/fusejs/dist/fuse.d.ts" ] + outputs = [ "$preprocessed_folder/fuse.d.ts" ] +} + grit("resources") { # These arguments are needed since the grd is generated at build time. enable_input_discovery_for_gn_analyze = false @@ -203,6 +208,7 @@ tsconfig_base = "tsconfig_base.json" in_files = web_component_files + non_component_js_files + html_wrapper_files + mojo_js_files + [ "fuse.js" ] + definitions = [ "$target_gen_dir/preprocessed/fuse.d.ts" ] deps = [ "//third_party/polymer/v3_0:library", "//ui/webui/resources:library", @@ -210,6 +216,7 @@ extra_deps = [ ":copy_checked_in_ts_js_files", ":copy_fuse", + ":copy_fuse_dts", ":copy_mojo", ":html_wrapper_files", "//ash/webui/common/resources:generate_definitions",
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_button.html b/chrome/browser/resources/chromeos/emoji_picker/emoji_button.html index eca2e41..e6d2e7e 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_button.html +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_button.html
@@ -86,14 +86,14 @@ } </style> -<button id="emoji-button" class$="[[_className(variants)]]" - on-click="onClick" on-contextmenu="onContextMenu" - disabled="[[disabled]]" aria-label="[[_label(tooltip, emoji, variants)]]"> +<button id="emoji-button" class$="[[calculateClassName()]]" + on-click="onClick" on-contextmenu="onContextMenu" + disabled="[[disabled]]" aria-label="[[getLabel()]]"> [[emoji]] </button> <template is="dom-if" if="[[!variant]]"> <paper-tooltip id="tooltip" for="emoji-button" fit-to-visible-bounds - part="tooltip" offset="8"> + part="tooltip" offset="8"> [[tooltip]] </paper-tooltip> </template>
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_button.js b/chrome/browser/resources/chromeos/emoji_picker/emoji_button.ts similarity index 68% rename from chrome/browser/resources/chromeos/emoji_picker/emoji_button.js rename to chrome/browser/resources/chromeos/emoji_picker/emoji_button.ts index 11d2be9b..a159666 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_button.js +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_button.ts
@@ -13,7 +13,7 @@ export class EmojiButton extends PolymerElement { static get is() { - return 'emoji-button'; + return 'emoji-button' as const; } static get template() { @@ -22,23 +22,14 @@ static get properties() { return { - /** @type {!string} */ emoji: {type: String, readonly: true}, - /** @type {?Array<Emoji>} */ variants: {type: Array, readonly: true}, - /** @type {!boolean} */ variantsVisible: {type: Boolean, value: false}, - /** @type {!Boolean} */ variant: {type: Boolean, value: false, readonly: true}, - /** @type {!boolean} */ disabled: {type: Boolean, value: false, readonly: true}, - /** @type {!string} */ base: {type: String}, - /** @type {?Array<Emoji>} */ allVariants: {type: Array, readonly: true}, - /** @type {!string} */ tooltip: {type: String, readonly: true}, - /** @type {string} */ category: { type: String, value: CategoryEnum.EMOJI, @@ -46,20 +37,18 @@ }, }; } + emoji: string; + variants?: Emoji[]; + private variantsVisible: boolean; + private variant: boolean; + private disabled: boolean; + private base?: string; + private allVariants?: Emoji[]; + private tooltip?: string; + private category: string; - constructor() { - super(); - } - getButton() { - return this.$['emoji-button']; - } - - focusButton(options) { - this.$['emoji-button'].focus(options); - } - - onClick(ev) { + private onClick(): void { if (this.disabled) { return; } @@ -73,7 +62,7 @@ })); } - onContextMenu(ev) { + private onContextMenu(ev: Event): void { ev.preventDefault(); if (this.disabled) { @@ -89,19 +78,20 @@ // Polymer. beforeNextRender(this, () => { const variants = this.variantsVisible ? - this.shadowRoot.querySelector('emoji-variants') : + // ShadowRoot is guaranteed to exist so ! is safe + this.shadowRoot!.querySelector('emoji-variants') : null; - this.dispatchEvent( - createCustomEvent(EMOJI_VARIANTS_SHOWN, - {owner: this, variants: variants, baseEmoji: this.emoji})); + this.dispatchEvent(createCustomEvent( + EMOJI_VARIANTS_SHOWN, + {owner: this, variants: variants, baseEmoji: this.emoji})); }); } /** * Hides emoji variants if any is visible. */ - hideEmojiVariants() { + hideEmojiVariants(): void { /** * TODO(b/233130994): Remove the function as part of the component removal. * The function is only added to help merging emoji-button into @@ -110,19 +100,27 @@ this.variantsVisible = false; } - _className(variants) { - return variants && variants.length > 0 ? 'has-variants' : ''; + private calculateClassName(): string { + return (this.variants && this.variants.length > 0) ? 'has-variants' : ''; } - _label(tooltip, emoji, variants) { + private getLabel(): string { // TODO(crbug/1227852): Just use emoji as the tooltip once ChromeVox can // announce them properly. const emojiLabel = - navigator.languages.some(lang => lang.startsWith('en')) > 0 ? tooltip : - emoji; - return variants && variants.length ? emojiLabel + ' with variants.' : - emojiLabel; + (navigator.languages.some(lang => lang.startsWith('en')) && + this.tooltip) ? + this.tooltip : + this.emoji; + return this.variants?.length ? emojiLabel + ' with variants.' : emojiLabel; } } +declare global { + interface HTMLElementTagNameMap { + [EmojiButton.is]: EmojiButton; + } +} + + customElements.define(EmojiButton.is, EmojiButton);
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_search.html b/chrome/browser/resources/chromeos/emoji_picker/emoji_search.html index 32abc96..701ec32f 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_search.html +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_search.html
@@ -96,7 +96,7 @@ transform: translate(-50%, -50%); } - #search-shadow { + #searchShadow { background-color: var(--cros-bg-color); margin-inline-end: calc(0px - var(--emoji-picker-side-padding)); margin-inline-start: calc(0px - var(--emoji-picker-side-padding)); @@ -108,7 +108,7 @@ width: calc(var(--emoji-picker-width) - 2*var(--emoji-picker-side-padding)); } - :host([v2-enabled]) #search-shadow { + :host([v2-enabled]) #searchShadow { box-shadow: var(--cr-elevation-2); display: flex; margin-bottom: 7px; @@ -153,7 +153,7 @@ } </style> -<div id="search-shadow"> +<div id="searchShadow"> <cr-search-field id="search" label="Search Emojis" autofocus="true"> </cr-search-field> <template is="dom-if" if="[[v2Enabled]]">
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_search.js b/chrome/browser/resources/chromeos/emoji_picker/emoji_search.ts similarity index 60% rename from chrome/browser/resources/chromeos/emoji_picker/emoji_search.js rename to chrome/browser/resources/chromeos/emoji_picker/emoji_search.ts index 46151b8..806dcca 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_search.js +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_search.ts
@@ -7,15 +7,25 @@ import './emoji_category_button.js'; import './emoji_group.js'; -import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {CrSearchFieldElement} from 'chrome://resources/cr_elements/cr_search_field/cr_search_field.js'; +import {PolymerSpliceChange} from 'chrome://resources/polymer/v3_0/polymer/interfaces.js'; +import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './emoji_search.html.js'; import Fuse from './fuse.js'; import {CategoryEnum, EmojiGroupData, EmojiVariants} from './types.js'; +export interface EmojiSearch { + $: { + search: CrSearchFieldElement, + searchShadow: HTMLElement, + }; +} + + export class EmojiSearch extends PolymerElement { static get is() { - return 'emoji-search'; + return 'emoji-search' as const; } static get template() { @@ -24,23 +34,34 @@ static get properties() { return { - /** @type {EmojiGroupData} */ categoriesData: {type: Array, readonly: true}, - /** @type {!boolean} */ lazyIndexing: {type: Boolean, value: true}, - /** @private {EmojiGroupData} */ searchResults: {type: Array}, - /** @private {!boolean} */ v2Enabled: { type: Boolean, value: false, reflectToAttribute: true, readonly: true, }, - /** @private {!boolean} */ needIndexing: {type: Boolean, value: false}, }; } + categoriesData: EmojiGroupData; + lazyIndexing: boolean; + private searchResults: EmojiGroupData; + private v2Enabled: boolean; + private needIndexing: boolean; + // TODO(b/235419647): Update the config to use extended search. + private fuseConfig: Fuse.IFuseOptions<EmojiVariants> = { + threshold: 0.0, // Exact match only. + ignoreLocation: true, // Match in all locations. + keys: + [ + {name: 'base.name', weight: 10}, // Increase scoring of emoji name. + 'base.keywords', + ], + }; + private fuseInstances = new Map<CategoryEnum, Fuse<EmojiVariants>>(); static get observers() { return [ @@ -48,36 +69,19 @@ ]; } - constructor() { - super(); - - // TODO(b/235419647): Update the config to use extended search. - /** @private {Object<string, Object>} */ - this.fuseConfig = { - threshold: 0.0, // Exact match only. - ignoreLocation: true, // Match in all locations. - keys: [ - {name: 'base.name', weight: 10}, // Increase scoring of emoji name. - 'base.keywords', - ], - }; - /** @private {Map<CategoryEnum,Object>} */ - this.fuseInstances = new Map(); - } - - ready() { + override ready() { super.ready(); this.addEventListener('scroll', () => this.onSearchScroll()); - this.addEventListener('search', ev => this.onSearch(ev.detail)); - this.$.search.getSearchInput().addEventListener( - 'keydown', - (ev) => this.onSearchKeyDown(/** @type {KeyboardEvent} */ (ev))); + // Cast here is safe since that is the spec from the cr search field mixin. this.addEventListener( - 'keydown', ev => this.onKeyDown(/** @type {KeyboardEvent} */ (ev))); + 'search', (ev) => this.onSearch((ev as CustomEvent<string>).detail)); + this.$.search.getSearchInput().addEventListener( + 'keydown', (ev: KeyboardEvent) => this.onSearchKeyDown(ev)); + this.addEventListener('keydown', (ev: KeyboardEvent) => this.onKeyDown(ev)); } - onSearch(newSearch) { + private onSearch(newSearch: string): void { this.searchResults = this.computeSearchResults(newSearch); } @@ -86,18 +90,18 @@ * needed or not. It also triggers indexing if mode is not lazy and there * are new changes. * - * @param {*} changedRecords - * @param {!boolean} lazyIndexing - * @returns */ - categoriesDataChanged(changedRecords, lazyIndexing) { + private categoriesDataChanged( + changedRecords: PolymerSpliceChange<EmojiGroupData>, + lazyIndexing: boolean): void { if (!changedRecords && lazyIndexing) { return; } // Indexing is needed if there are new changes. - this.needIndexing = this.needIndexing || changedRecords.indexSplices - .some((s) => s.removed.length + s.addedCount > 0); + this.needIndexing = this.needIndexing || + changedRecords.indexSplices.some( + (s) => s.removed.length + s.addedCount > 0); // Trigger indexing if mode is not lazy and indexing is needed. if (!lazyIndexing && this.needIndexing) { @@ -108,9 +112,8 @@ /** * Event handler for keydown anywhere in the search component. * Used to move the focused result up/down on arrow presses. - * @param {KeyboardEvent} ev */ - onKeyDown(ev) { + private onKeyDown(ev: KeyboardEvent): void { // TODO(b/233567886): Implement navigation by keyboard for V2. if (this.v2Enabled) { return; @@ -120,8 +123,8 @@ const isDown = ev.key === 'ArrowDown'; const isEnter = ev.key === 'Enter'; // get emoji-button which has focus. - /** @type {Element} */ - const focusedResult = this.shadowRoot.querySelector('.result:focus-within'); + const focusedResult = + this.shadowRoot!.querySelector<HTMLElement>('.result:focus-within'); if (isEnter && focusedResult) { focusedResult.click(); @@ -138,8 +141,8 @@ return; } - const prev = focusedResult.previousElementSibling; - const next = focusedResult.nextElementSibling; + const prev = focusedResult.previousElementSibling as HTMLElement | null; + const next = focusedResult.nextElementSibling as HTMLElement | null; // moving up from first result focuses search box. // need to check classList in case prev is sr-only. @@ -157,12 +160,11 @@ /** * Event handler for keydown on the search input. Used to switch focus to the * results list on down arrow or enter key presses. - * @param {KeyboardEvent} ev */ - onSearchKeyDown(ev) { + private onSearchKeyDown(ev: KeyboardEvent): void { const resultsCount = this.getNumSearchResults(); // if not searching or no results, do nothing. - if (!this.$['search'].getValue() || resultsCount === 0) { + if (!this.$.search.getValue() || resultsCount === 0) { return; } @@ -176,12 +178,16 @@ // TODO(b/234673356): Remove this block. if (!this.v2Enabled) { // focus first item in result list. - const firstButton = this.shadowRoot.querySelector('.result'); - firstButton.focus(); + const firstButton = + this.shadowRoot!.querySelector<HTMLElement>('.result'); + if (firstButton) { + firstButton.focus(); - // if there is only one result, select it on enter. - if (isEnter && resultsCount === 1) { - firstButton.querySelector('emoji-button').click(); + // if there is only one result, select it on enter. + if (isEnter && resultsCount === 1) { + // ! is safe here since we are getting the first result + firstButton.querySelector('emoji-button')!.click(); + } } } else { if (resultsCount === 0) { @@ -207,10 +213,9 @@ * Format the emoji data for search: * 1) Remove duplicates. * 2) Remove groupings. - * @param {!EmojiGroupData} emojiData - * @return {!Array<!EmojiVariants>} */ - preprocessDataForIndexing(emojiData) { + private preprocessDataForIndexing(emojiData: EmojiGroupData): + EmojiVariants[] { // TODO(b/235419647): Remove addition of extra space. return Array.from( new Map(emojiData.map(group => group.emoji).flat(1).map(emoji => { @@ -223,8 +228,8 @@ // infant". emoji.base.name = ' ' + emoji.base.name; if (emoji.base.keywords && emoji.base.keywords.length > 0) { - emoji.base.keywords = emoji.base.keywords.map( - keyword => ' ' + keyword); + emoji.base.keywords = + emoji.base.keywords.map(keyword => ' ' + keyword); } return [emoji.base.string, emoji]; })).values()); @@ -237,36 +242,36 @@ * to index only the new changes with the cost of increasing logic * complexity. */ - createSearchIndices() { + private createSearchIndices(): void { if (!this.categoriesData || this.categoriesData.length === 0) { return; } // Get the list of unique categories in the order they appeared // in the data. - const categories = [...new Set( - this.categoriesData.map(item => item.category))]; + const categories = + [...new Set(this.categoriesData.map(item => item.category))]; // Remove existing indices. this.fuseInstances.clear(); for (const category of categories) { // Filter records for the category and preprocess them. - const indexableEmojis = this.preprocessDataForIndexing( - this.categoriesData.filter( - emojiGroup => emojiGroup.category === category)); + const indexableEmojis = + this.preprocessDataForIndexing(this.categoriesData.filter( + emojiGroup => emojiGroup.category === category)); // Create a new index for the category. - this.fuseInstances.set(category, - new Fuse(indexableEmojis, this.fuseConfig)); + this.fuseInstances.set( + category, new Fuse(indexableEmojis, this.fuseConfig)); } this.needIndexing = false; } - onSearchScroll() { + private onSearchScroll(): void { if (!this.v2Enabled) { - this.$['search-shadow'].style.boxShadow = - this.shadowRoot.getElementById('results').scrollTop > 0 ? + this.$.searchShadow.style.boxShadow = + this.shadowRoot!.getElementById('results')?.scrollTop ?? 0 > 0 ? 'var(--cr-elevation-3)' : 'none'; } @@ -275,11 +280,8 @@ /** * Computes search results for a keyword. * - * @param {?string} search Search keyword - * @returns {EmojiGroupData} Search results for all categories that had - * matching items. */ - computeSearchResults(search) { + computeSearchResults(search: string|null): EmojiGroupData { if (!search) { return []; } @@ -293,12 +295,12 @@ // Add an initial space to force prefix matching only. const prefixSearchTerm = ` ${search}`; - const searchResults = []; + const searchResults: EmojiGroupData = []; // Search the keyword in the fuse instance of each category. for (const [category, fuseInstance] of this.fuseInstances.entries()) { - const categorySearchResult = (/** @type {Object} */ (fuseInstance)) - .search(prefixSearchTerm).map(item => item.item); + const categorySearchResult = + fuseInstance.search(prefixSearchTerm).map(item => item.item); // Add the category results if not empty. if (categorySearchResult.length !== 0) { @@ -306,6 +308,7 @@ 'category': category, 'group': '', 'emoji': categorySearchResult, + 'searchOnly': false, }); } } @@ -313,28 +316,30 @@ return searchResults; } - onResultClick(ev) { + private onResultClick(ev: MouseEvent): void { // If the click is on elements except emoji-button, trigger the click on // the emoji-button. - if (ev.target.nodeName !== 'EMOJI-BUTTON') { - ev.currentTarget.querySelector('emoji-button') - .shadowRoot.querySelector('button') - .click(); + if ((ev.target as HTMLElement | null)?.nodeName !== 'EMOJI-BUTTON') { + // Using ! here, since if we use ! we should at least get a crash (and + // nothing would happen if we fall through via ?. ) + (ev.currentTarget as HTMLElement | null)!.querySelector('emoji-button')! + .shadowRoot!.querySelector('button')!.click(); } } /** * Finds the first button in the search result page. * - * @returns {?HTMLElement} First button or null for no results. */ - findFirstResultButton() { - const results = this.shadowRoot.querySelector( - '#search-results').querySelectorAll('emoji-group'); - for (const result of results) { - const button = result.firstEmojiButton(); - if (button) { - return button; + private findFirstResultButton(): HTMLElement|null { + const results = this.shadowRoot!.querySelector('#search-results') + ?.querySelectorAll('emoji-group'); + if (results) { + for (const result of results) { + const button = result.firstEmojiButton(); + if (button) { + return button; + } } } return null; @@ -343,11 +348,9 @@ /** * Determines visibility of the search results for V1. * - * @param {!EmojiGroupData} searchResults Search results. - * @param {!boolean} v2Enabled V2 enablement status. - * @returns {boolean} True if V2 is not enabled and there are results items. */ - shouldShowV1Results(searchResults, v2Enabled) { + private shouldShowV1Results( + searchResults: EmojiGroupData, v2Enabled: boolean): boolean { // TODO(b/234673356): Remove this function. return !v2Enabled && searchResults.length > 0; } @@ -355,9 +358,8 @@ /** * Calculates the total number of items in the search results. * - * @returns {number} Number of search results. */ - getNumSearchResults() { + private getNumSearchResults(): number { return this.searchResults ? this.searchResults.reduce((acc, item) => acc + item.emoji.length, 0) : 0; @@ -366,22 +368,22 @@ /** * Checks if the search query is empty * - * @param {!EmojiGroupData} searchResults Search results is not used but - * function needs to be run when searchResults updated. - * @returns {boolean} True if the search is empty */ - searchNotEmpty(searchResults) { - return this.$['search'].getValue() !== ''; + searchNotEmpty(): boolean { + return this.$.search.getValue() !== ''; } /** * Sets the search query - * - * @param {!string} value for the search query */ - setSearchQuery(value) { - /** @type {{setValue: function(string)}} */ (this.$['search']) - .setValue(value); + setSearchQuery(value: string): void { + this.$.search.setValue(value); + } +} + +declare global { + interface HTMLElementTagNameMap { + [EmojiSearch.is]: EmojiSearch; } }
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.html b/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.html index be40a6c..d4e31d6 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.html +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.html
@@ -105,7 +105,7 @@ </div> <div id="grid-variants"> - <div id="fake-focus-target" tabindex="-1"></div> + <div id="fakeFocusTarget" tabindex="-1"></div> <template is="dom-repeat" items="[[variantRows]]" as="row"> <div class="variant-row"> <template is="dom-repeat" items="[[row]]" as="emoji">
diff --git a/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.js b/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.ts similarity index 72% rename from chrome/browser/resources/chromeos/emoji_picker/emoji_variants.js rename to chrome/browser/resources/chromeos/emoji_picker/emoji_variants.ts index 593cb44..a5a55c9 100644 --- a/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.js +++ b/chrome/browser/resources/chromeos/emoji_picker/emoji_variants.ts
@@ -9,16 +9,13 @@ import {Emoji} from './types.js'; const SKIN_TONE_MEDIUM = '🏽'; // U+1F3FD EMOJI MODIFIER FITZPATRICK TYPE-4 -const FAMILY = '👪'; // U+1F46A FAMILY +const FAMILY = '👪'; // U+1F46A FAMILY /** * Determines if the given list of variants has any variant which contains * the given codepoint. - * @param {!Array<!Emoji>} variants - * @param {!string} codepoint - * @return {boolean} */ -function hasVariation(variants, codepoint) { +function hasVariation(variants: Emoji[], codepoint: string): boolean { return variants.findIndex(x => x.string.includes(codepoint)) !== -1; } @@ -27,12 +24,8 @@ * Partitions source array into array of arrays, where each subarray's * length is determined by the corresponding value of subarrayLengths. * A negative length indicates skip that many items. - * @param {!Array<T>} array source array. - * @param {!Array<number>} subarrayLengths lengths to partition. - * @return {!Array<!Array<T>>} partitioned array. - * @template T array item type. */ -function partitionArray(array, subarrayLengths) { +function partitionArray<T>(array: T[], subarrayLengths: number[]): T[][] { const subarrays = []; let used = 0; for (const len of subarrayLengths) { @@ -46,9 +39,15 @@ return subarrays; } +export interface EmojiVariants { + $: { + fakeFocusTarget: HTMLElement, + }; +} + export class EmojiVariants extends PolymerElement { static get is() { - return 'emoji-variants'; + return 'emoji-variants' as const; } static get template() { @@ -57,36 +56,32 @@ static get properties() { return { - /** @type {!Array<Emoji>} */ variants: {type: Array, readonly: true}, - /** @private {!Array<!Array<Emoji>>} */ variantRows: {type: Array}, - /** @private {?string} */ baseEmoji: {type: Array}, - /** @private {boolean} */ showSkinTones: {type: Boolean}, - /** @private {boolean} */ showBaseEmoji: {type: Boolean}, - /** @private {!string} */ tooltip: {type: String}, }; } + variants: Emoji[]; + private variantRows: Emoji[][]; + private baseEmoji: string; + private showSkinTones: boolean; + private showBaseEmoji: boolean; + private tooltip: string; - constructor() { - super(); - } - - ready() { + override ready() { super.ready(); // family picker is basic 5x5 grid. const isFamily = - this.variants.length === 26 && this.variants[0].string === FAMILY; + this.variants.length === 26 && this.variants[0]?.string === FAMILY; // two people is 5x5 grid with 5 skin tones per person. const isTwoPeople = this.variants.length === 26 && hasVariation(this.variants, SKIN_TONE_MEDIUM); this.showBaseEmoji = isFamily || isTwoPeople; - this.baseEmoji = this.variants[0].string; + this.baseEmoji = this.variants[0]?.string ?? ''; this.showSkinTones = isTwoPeople; // if we are showing a base emoji separately, omit it from the main grid. @@ -95,15 +90,14 @@ const rowLengths = this.computeVariantRowLengths(gridEmoji); this.variantRows = partitionArray(gridEmoji, rowLengths); - this.addEventListener( - 'keydown', (ev) => this.onKeyDown(/** @type {!KeyboardEvent} */ (ev))); + this.addEventListener('keydown', (ev) => this.onKeyDown(ev)); } - connectedCallback() { - beforeNextRender(this, () => this.$['fake-focus-target'].focus()); + override connectedCallback() { + beforeNextRender(this, () => this.$.fakeFocusTarget.focus()); } - computeVariantRowLengths(variants) { + private computeVariantRowLengths(variants: Emoji[]): number[] { if (!variants.length) { return []; } @@ -122,10 +116,7 @@ return []; } - /** - * @param {!KeyboardEvent} ev - */ - onKeyDown(ev) { + private onKeyDown(ev: KeyboardEvent): void { if (ev.key !== 'Escape') { return; } @@ -141,4 +132,11 @@ } } +declare global { + interface HTMLElementTagNameMap { + [EmojiVariants.is]: EmojiVariants; + } +} + + customElements.define(EmojiVariants.is, EmojiVariants);
diff --git a/chrome/browser/resources/chromeos/internet_config_dialog/internet_config_dialog.html b/chrome/browser/resources/chromeos/internet_config_dialog/internet_config_dialog.html index 1393de22..375a94c2 100644 --- a/chrome/browser/resources/chromeos/internet_config_dialog/internet_config_dialog.html +++ b/chrome/browser/resources/chromeos/internet_config_dialog/internet_config_dialog.html
@@ -12,22 +12,13 @@ height: 480px; } - #title { - font-size: inherit; - font-weight: 400; - margin: 0; - padding: 0; - } - .error { color: red; font-weight: 500; } </style> <cr-dialog id="dialog" no-cancel> - <div slot="title"> - <h2 id="title">[[getDialogTitle_(type_)]]</h2> - </div> + <div slot="title">[[getDialogTitle_(type_)]]</div> <div slot="body"> <network-config id="networkConfig" class="flex" guid="[[guid_]]" type="{{type_}}"
diff --git a/chrome/browser/resources/chromeos/login/debug/debug.js b/chrome/browser/resources/chromeos/login/debug/debug.js index b388a75..77be651e 100644 --- a/chrome/browser/resources/chromeos/login/debug/debug.js +++ b/chrome/browser/resources/chromeos/login/debug/debug.js
@@ -10,6 +10,7 @@ // #import {loadTimeData} from '../i18n_setup.js'; // #import {Oobe} from '../cr_ui.m.js' // #import {$} from 'chrome://resources/js/util.js'; +// #import './debug_util.js'; // #import {AssistantNativeIconType} from '../../assistant_optin/utils.m.js'; // #import {MessageType, ProblemType} from 'chrome://resources/ash/common/quick_unlock/setup_pin_keyboard.js'; @@ -1329,26 +1330,35 @@ id: '2-apps', trigger: (screen) => { screen.reset(); + screen.setWebview(RECOMMENDED_APPS_CONTENT); screen.loadAppList([ { - title: 'gApp', - icon_url: 'https://www.google.com/favicon.ico', - category: 'Games', - in_app_purchases: true, - was_installed: false, - content_rating: '', + name: 'Test app 1', + package_name: 'test1.app', }, { - title: 'anotherGapp', - icon_url: 'https://www.google.com/favicon.ico', - category: 'Games', - in_app_purchases: true, - was_installed: false, - content_rating: '', + name: 'Test app 2 with some really long name', + package_name: 'test2.app', }, ]); }, }, + { + id: '21-apps', + trigger: (screen) => { + // There can be up to 21 apps: see recommend_apps_fetcher_impl + screen.reset(); + screen.setWebview(RECOMMENDED_APPS_CONTENT); + const apps = []; + for (let i = 1; i <= 21; i++) { + apps.push({ + name: 'Test app ' + i, + package_name: 'app.test' + i, + }); + } + screen.loadAppList(apps); + }, + }, ], }, {
diff --git a/chrome/browser/resources/chromeos/login/debug/debug_util.js b/chrome/browser/resources/chromeos/login/debug/debug_util.js new file mode 100644 index 0000000..acb833f --- /dev/null +++ b/chrome/browser/resources/chromeos/login/debug/debug_util.js
@@ -0,0 +1,9 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// TODO(crbug.com/1229130) - Remove this global namespace pollution. +// TODO(crbug.com/1261902): Remove once crbug.com/1229130 is tackled. +window.RECOMMENDED_APPS_CONTENT = ` +// <include src="../../arc_support/recommend_app_list_view.html"> + `;
diff --git a/chrome/browser/resources/chromeos/login/oobe_conditional_resources.grd b/chrome/browser/resources/chromeos/login/oobe_conditional_resources.grd index 0bf0a26..93703cf2 100644 --- a/chrome/browser/resources/chromeos/login/oobe_conditional_resources.grd +++ b/chrome/browser/resources/chromeos/login/oobe_conditional_resources.grd
@@ -9,6 +9,7 @@ <release seq="1"> <structures> <!-- Resources in this section still depend on flattenhtml --> + <structure name="IDR_OOBE_DEBUGGER_UTIL_JS" file="debug\debug_util.js" type="chrome_html" flattenhtml="true" /> <structure name="IDR_KEYBOARD_UTILS_FOR_INJECTION_M_JS" file="components/keyboard_utils_for_injection.m.js" flattenhtml="true" type="chrome_html" /> </structures>
diff --git a/chrome/browser/resources/chromeos/parent_access/parent_access_after.html b/chrome/browser/resources/chromeos/parent_access/parent_access_after.html index 6cc3c48a..e799c47 100644 --- a/chrome/browser/resources/chromeos/parent_access/parent_access_after.html +++ b/chrome/browser/resources/chromeos/parent_access/parent_access_after.html
@@ -28,9 +28,9 @@ <div id="after-screen"> <img class="google-logo" src="chrome://theme/IDR_LOGO_GOOGLE_COLOR_90" - alt="Google logo"> + alt=""> </img> - <div id="after-screen-body"></div> + <div id="after-screen-body" aria-live="polite"></div> <div id="after-screen-buttons"> <cr-button class="action-button" on-click="onParentApproved_"> $i18n{approveButtonText}
diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index dfff98b..6af2b99 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd
@@ -72,6 +72,10 @@ <include name="IDR_ARC_SUPPORT_ICON_192_PNG" file="chromeos/arc_support/icon/192.png" type="BINDATA" /> <include name="IDR_ARC_SUPPORT_ICON_ERROER_IMAGE" file="chromeos/arc_support/images/error_image.png" type="BINDATA" /> <include name="IDR_ARC_SUPPORT_ICON_HEADER" file="chromeos/arc_support/images/header.png" type="BINDATA" /> + <!-- TODO(crbug.com/1261902): Remove. --> + <include name="IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_JS" file="chromeos/arc_support/recommend_app_list_view.js" type="BINDATA" /> + <!-- TODO(crbug.com/1261902): Remove. --> + <include name="IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML" file="chromeos/arc_support/recommend_app_list_view.html" type="chrome_html" flattenhtml="true" /> <include name="IDR_ARC_SUPPORT_UI_JS" file="chromeos/arc_support/ui.js" type="chrome_html" /> <include name="IDS_ARC_INPUT_OVERLAY_ONBOARDING_ILLUSTRATION" file="chromeos/arc_input_overlay/onboarding_illustration.png" type="BINDATA" /> <include name="IDS_ARC_INPUT_OVERLAY_ONBOARDING_ILLUSTRATION_DARK" file="chromeos/arc_input_overlay/onboarding_illustration_dark.png" type="BINDATA" />
diff --git a/chrome/browser/resources/extensions/error_page.ts b/chrome/browser/resources/extensions/error_page.ts index b2be3476..85ca28b 100644 --- a/chrome/browser/resources/extensions/error_page.ts +++ b/chrome/browser/resources/extensions/error_page.ts
@@ -228,8 +228,15 @@ break; case chrome.developerPrivate.ErrorType.RUNTIME: const runtimeError = error as RuntimeError; - // slice(1) because pathname starts with a /. - args.pathSuffix = new URL(runtimeError.source).pathname.slice(1); + try { + // slice(1) because pathname starts with a /. + args.pathSuffix = new URL(runtimeError.source).pathname.slice(1); + } catch (e) { + // Swallow the invalid URL error and return early. This prevents the + // uncaught error from causing a runtime error as seen in + // crbug.com/1257170. + return; + } args.lineNumber = runtimeError.stackTrace && runtimeError.stackTrace[0] ? runtimeError.stackTrace[0].lineNumber :
diff --git a/chrome/browser/resources/extensions/host_permissions_toggle_list.html b/chrome/browser/resources/extensions/host_permissions_toggle_list.html index c09420b..0050815 100644 --- a/chrome/browser/resources/extensions/host_permissions_toggle_list.html +++ b/chrome/browser/resources/extensions/host_permissions_toggle_list.html
@@ -40,7 +40,7 @@ </style> <div id="section-heading" hidden$="[[enableEnhancedSiteControls]]"> <span>$i18n{hostPermissionsDescription}</span> - <a id="linkIconButton" aria-label="$i18n{learnMore}" + <a id="linkIconButton" aria-label="$i18n{permissionsLearnMoreLabel}" href="$i18n{hostPermissionsLearnMoreLink}" target="_blank" on-click="onLearnMoreClick_"> <iron-icon icon="cr:help-outline"></iron-icon> @@ -53,7 +53,7 @@ <span class="[[getAllHostsToggleLabelClass_(enableEnhancedSiteControls)]]"> $i18n{itemAllowOnFollowingSites} </span> - <a id="linkIconButton" aria-label="$i18n{learnMore}" + <a id="linkIconButton" aria-label="$i18n{permissionsLearnMoreLabel}" href="$i18n{hostPermissionsLearnMoreLink}" target="_blank" on-click="onLearnMoreClick_" hidden$="[[!enableEnhancedSiteControls]]">
diff --git a/chrome/browser/resources/extensions/runtime_host_permissions.html b/chrome/browser/resources/extensions/runtime_host_permissions.html index 66e4ae2..fa50f33 100644 --- a/chrome/browser/resources/extensions/runtime_host_permissions.html +++ b/chrome/browser/resources/extensions/runtime_host_permissions.html
@@ -102,7 +102,8 @@ <span id="section-heading-text"> $i18n{hostPermissionsHeading} </span> - <a class="link-icon-button" aria-label="$i18n{learnMore}" + <a class="link-icon-button" + aria-label="$i18n{permissionsLearnMoreLabel}" href="$i18n{hostPermissionsLearnMoreLink}" target="_blank" on-click="onLearnMoreClick_"> <iron-icon icon="cr:help-outline"></iron-icon> @@ -135,7 +136,8 @@ <span id="new-section-heading-text"> $i18n{newHostPermissionsHeading} </span> - <a class="link-icon-button" aria-label="$i18n{learnMore}" + <a class="link-icon-button" + aria-label="$i18n{permissionsLearnMoreLabel}" href="$i18n{hostPermissionsLearnMoreLink}" target="_blank" on-click="onLearnMoreClick_"> <iron-icon icon="cr:help-outline"></iron-icon>
diff --git a/chrome/browser/resources/settings/about_page/about_page.html b/chrome/browser/resources/settings/about_page/about_page.html index 078a5348..21a70fa 100644 --- a/chrome/browser/resources/settings/about_page/about_page.html +++ b/chrome/browser/resources/settings/about_page/about_page.html
@@ -75,7 +75,7 @@ <div class="flex cr-padded-text"> <if expr="not chromeos_ash"> <div id="updateStatusMessage" hidden="[[!showUpdateStatus_]]"> - <div + <div role="alert" aria-live="polite" inner-h-t-m-l="[[getUpdateStatusMessage_( currentUpdateStatusEvent_)]]"> </div>
diff --git a/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html b/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html index 1b08ca42..e4b55e7 100644 --- a/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html
@@ -51,7 +51,9 @@ } </style> <cr-dialog id="dialog" close-text="$i18n{close}" show-on-attach> - <h1 slot="title" id="title" class="dialog-title">[[getTitle_(dialogMode)]]</h1> + <div slot="title" id="title" class="dialog-title"> + [[getTitle_(dialogMode)]] + </div> <div slot="body"> <div hidden="[[!shouldShowStorageDetails_(isAccountStoreUser, dialogMode)]]" id="storageDetails">
diff --git a/chrome/browser/resources/settings/autofill_page/password_move_multiple_passwords_to_account_dialog.html b/chrome/browser/resources/settings/autofill_page/password_move_multiple_passwords_to_account_dialog.html index 522ac50c..51cefc7 100644 --- a/chrome/browser/resources/settings/autofill_page/password_move_multiple_passwords_to_account_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/password_move_multiple_passwords_to_account_dialog.html
@@ -17,8 +17,9 @@ </style> <cr-dialog id="dialog" close-text="$i18n{close}" show-on-attach> - <h1 slot="title" class="dialog-title">$i18n{passwordMovePasswordsToAccountDialogTitle}</h1> - + <div slot="title" class="dialog-title"> + $i18n{passwordMovePasswordsToAccountDialogTitle} + </div> <div slot="body"> <div>$i18n{passwordMovePasswordsToAccountDialogBodyText}</div> <dom-repeat id="devicePasswordList" items="[[passwordsToMove]]"
diff --git a/chrome/browser/resources/settings/autofill_page/password_move_to_account_dialog.html b/chrome/browser/resources/settings/autofill_page/password_move_to_account_dialog.html index 5ee81c10..d60258b 100644 --- a/chrome/browser/resources/settings/autofill_page/password_move_to_account_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/password_move_to_account_dialog.html
@@ -88,7 +88,9 @@ } </style> <cr-dialog id="dialog" close-text="$i18n{close}"> - <h1 slot="title" class="dialog-title">$i18n{passwordMoveToAccountDialogTitle}</h1> + <div slot="title" class="dialog-title"> + $i18n{passwordMoveToAccountDialogTitle} + </div> <div slot="body"> <div id="dialogMessage"> $i18n{passwordMoveToAccountDialogBody}
diff --git a/chrome/browser/resources/settings/autofill_page/password_remove_confirmation_dialog.html b/chrome/browser/resources/settings/autofill_page/password_remove_confirmation_dialog.html index 0260149..8d171b0 100644 --- a/chrome/browser/resources/settings/autofill_page/password_remove_confirmation_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/password_remove_confirmation_dialog.html
@@ -3,9 +3,9 @@ <style include="settings-shared passwords-shared"></style> <cr-dialog id="dialog" close-text="$i18n{close}" ignore-popstate ignore-enter-key> - <h1 slot="title" class="dialog-title"> + <div slot="title" class="dialog-title"> $i18n{removeCompromisedPasswordConfirmationTitle} - </h1> + </div> <div slot="body"> <span id="link" hidden="[[!hasSecureChangePasswordUrl_(item)]]" inner-h-t-m-l="[[getRemovePasswordDescriptionHtml_(item)]]">
diff --git a/chrome/browser/resources/settings/autofill_page/password_remove_dialog.html b/chrome/browser/resources/settings/autofill_page/password_remove_dialog.html index 499c019..b7fc82c 100644 --- a/chrome/browser/resources/settings/autofill_page/password_remove_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/password_remove_dialog.html
@@ -15,7 +15,7 @@ } </style> <cr-dialog id="dialog" close-text="$i18n{close}"> - <h1 slot="title" class="dialog-title">$i18n{passwordRemoveDialogTitle}</h1> + <div slot="title" class="dialog-title">$i18n{passwordRemoveDialogTitle}</div> <div slot="body"> <div inner-h-t-m-l="[[getDialogBodyMessage_()]]"></div> <cr-checkbox checked="{{removeFromAccountChecked_}}"
diff --git a/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html b/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html index b3491c7..67acd048 100644 --- a/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html
@@ -19,7 +19,7 @@ </style> <template is="dom-if" if="[[showStartDialog_]]" restamp> <cr-dialog id="dialog_start" close-text="$i18n{close}" show-on-attach> - <h1 slot="title" class="dialog-title">$i18n{exportPasswordsTitle}</h1> + <div slot="title" class="dialog-title">$i18n{exportPasswordsTitle}</div> <div slot="body"> <div class="layout horizontal center"> <div>$i18n{exportPasswordsDescription}</div> @@ -40,7 +40,7 @@ <template is="dom-if" if="[[showProgressDialog_]]" restamp> <cr-dialog id="dialog_progress" no-cancel="true" show-on-attach> - <h1 slot="title" class="dialog-title">$i18n{exportPasswordsTitle}</h1> + <div slot="title" class="dialog-title">$i18n{exportPasswordsTitle}</div> <div slot="body"> <paper-progress indeterminate class="blue"></paper-progress> </div> @@ -55,7 +55,7 @@ <template is="dom-if" if="[[showErrorDialog_]]" restamp> <cr-dialog id="dialog_error" close-text="$i18n{close}" show-on-attach> - <h1 slot="title" class="dialog-title">[[exportErrorMessage]]</h1> + <div slot="title" class="dialog-title">[[exportErrorMessage]]</div> <div slot="body"> $i18n{exportPasswordsFailTips} <ul>
diff --git a/chrome/browser/resources/settings/autofill_page/passwords_import_dialog.html b/chrome/browser/resources/settings/autofill_page/passwords_import_dialog.html index 8bc4e6af..ceedee4 100644 --- a/chrome/browser/resources/settings/autofill_page/passwords_import_dialog.html +++ b/chrome/browser/resources/settings/autofill_page/passwords_import_dialog.html
@@ -80,7 +80,7 @@ </style> <cr-dialog id="dialog" close-text="$i18n{close}" show-on-attach> - <h1 slot="title" class="dialog-title">$i18n{importPasswordsTitle}</h1> + <div slot="title" class="dialog-title">$i18n{importPasswordsTitle}</div> <div slot="body"> <select class="md-select" id="storePicker" aria-description="$i18n{importPasswordsStorePickerA11yDescription}" @@ -161,4 +161,4 @@ $i18n{importPasswordsChooseFile} </cr-button> </div> -</cr-dialog> \ No newline at end of file +</cr-dialog>
diff --git a/chrome/browser/resources/settings/autofill_page/passwords_section.html b/chrome/browser/resources/settings/autofill_page/passwords_section.html index 135ad2b..c27691f2 100644 --- a/chrome/browser/resources/settings/autofill_page/passwords_section.html +++ b/chrome/browser/resources/settings/autofill_page/passwords_section.html
@@ -343,7 +343,7 @@ </div> </div> <cr-dialog id="authTimeoutDialog"> - <h1 slot="title" class="dialog-title">$i18n{passwordsTimedOut}</h1> + <div slot="title" class="dialog-title">$i18n{passwordsTimedOut}</div> <div slot="body"> <div>$i18n{passwordsTimedOutDescription}</div> </div>
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index b9aea33..d9da2de1 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -337,7 +337,6 @@ ":os_route", ":os_settings", ":os_settings_routes", - ":pref_to_setting_metric_converter", ":prefs_behavior", ":route_observer_behavior", ":route_origin_behavior", @@ -409,13 +408,6 @@ externs_list = [ "$externs_path/settings_private.js" ] } -js_library("pref_to_setting_metric_converter") { - deps = [ - "//chrome/browser/ui/webui/settings/ash/search:mojo_bindings_webui_js", - "//chrome/browser/ui/webui/settings/chromeos/constants:mojom_webui_js", - ] -} - js_library("route_observer_behavior") { deps = [ "..:router",
diff --git a/chrome/browser/resources/settings/chromeos/internet_page/internet_config.html b/chrome/browser/resources/settings/chromeos/internet_page/internet_config.html index bdeb7a6..ccc5d87 100644 --- a/chrome/browser/resources/settings/chromeos/internet_page/internet_config.html +++ b/chrome/browser/resources/settings/chromeos/internet_page/internet_config.html
@@ -3,14 +3,6 @@ width: 460px; } - #title { - color: var(--cros-primary-text-color); - font-size: inherit; - font-weight: 400; - margin: 0; - padding: 0; - } - .error { color: var(--cros-text-color-alert); font-weight: 500; @@ -18,9 +10,7 @@ </style> <cr-dialog id="dialog" close-text="$i18n{close}"> - <div slot="title"> - <h2 id="title">[[getDialogTitle_(name, type, showConnect)]]</h2> - </div> + <div slot="title">[[getDialogTitle_(name, type, showConnect)]]</div> <div slot="body"> <network-config id="networkConfig" class="flex" guid="[[guid]]" name="{{name}}" type="{{type}}"
diff --git a/chrome/browser/resources/settings/chromeos/internet_page/internet_page.js b/chrome/browser/resources/settings/chromeos/internet_page/internet_page.js index 3897690e..c9426133 100644 --- a/chrome/browser/resources/settings/chromeos/internet_page/internet_page.js +++ b/chrome/browser/resources/settings/chromeos/internet_page/internet_page.js
@@ -1037,7 +1037,7 @@ // This shouldn't happen, the UI should prevent this, fall through and // show the error. case StartConnectResult.kUnknown: - console.error( + console.warn( 'startConnect failed for: ' + networkState.guid + ' Error: ' + response.message); return;
diff --git a/chrome/browser/resources/settings/chromeos/kerberos_page/kerberos_add_account_dialog.html b/chrome/browser/resources/settings/chromeos/kerberos_page/kerberos_add_account_dialog.html index 9f5a2a5..ae099c48 100644 --- a/chrome/browser/resources/settings/chromeos/kerberos_page/kerberos_add_account_dialog.html +++ b/chrome/browser/resources/settings/chromeos/kerberos_page/kerberos_add_account_dialog.html
@@ -52,15 +52,22 @@ padding-inline-end: 8px; white-space: nowrap; } + + h3 { + font-size: inherit; + font-weight: 500; + margin-block-end: 12px; + margin-block-start: 0; + } </style> <cr-dialog id="addDialog" hidden="[[showAdvancedConfig_]]"> <div slot="title">[[title_]]</div> <div slot="body" spellcheck="false"> - <h2 class="start first"> + <h3 class="start first"> $i18n{addKerberosAccountDescription} - </h2> + </h3> <div id="general-error-container" hidden="[[!showError_(generalErrorText_)]]"> @@ -120,14 +127,14 @@ <div slot="title">$i18n{kerberosAdvancedConfigTitle}</div> <div slot="body"> - <h2 class="first" id="advancedConfigDesc"> + <h3 class="first" id="advancedConfigDesc"> $i18n{kerberosAdvancedConfigDesc} <template is="dom-if" if="[[isManaged_]]"> <cr-policy-indicator id="advancedConfigPolicyIndicator" indicator-type="userPolicy"> </cr-policy-indicator> </template> - </h2> + </h3> <settings-textarea id="config" value="{{editableConfig_}}" rows=12 spellcheck="false" disabled="[[isManaged_]]">
diff --git a/chrome/browser/resources/settings/chromeos/metrics_utils.ts b/chrome/browser/resources/settings/chromeos/metrics_utils.ts new file mode 100644 index 0000000..067fb81 --- /dev/null +++ b/chrome/browser/resources/settings/chromeos/metrics_utils.ts
@@ -0,0 +1,56 @@ +/* Copyright 2020 The Chromium Authors + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +/** + * @fileoverview Utility functions for settings metrics + */ + +import {assert} from 'chrome://resources/js/assert_ts.js'; + +import {SettingChangeValue} from '../mojom-webui/search/user_action_recorder.mojom-webui.js'; +import {Setting} from '../mojom-webui/setting.mojom-webui.js'; + +interface SettingMetric { + setting: Setting; + value: SettingChangeValue; +} + +// Converts a given settings pref to a pair of setting ID and setting change +// value. Used to record metrics about changes to pref-based settings. +// The cast "as SettingChangeValue" addresses a known compile issue in TS where +// the autogenerated JS bindings for unions in Mojo does not allow optional +// properties, and rather makes all properties required but allowing undefined +// as the value. +export function convertPrefToSettingMetric( + prefKey: string, prefValue: unknown): SettingMetric|null { + switch (prefKey) { + // device_page/keyboard.js + case 'settings.language.send_function_keys': + assert(typeof prefValue === 'boolean'); + return { + setting: Setting.kKeyboardFunctionKeys, + value: {boolValue: prefValue} as SettingChangeValue, + }; + + // device_page/pointers.js + case 'settings.touchpad.sensitivity2': + assert(typeof prefValue === 'number'); + return { + setting: Setting.kTouchpadSpeed, + value: {intValue: prefValue} as SettingChangeValue, + }; + + // os_privacy_page/os_privacy_page.js + case 'cros.device.peripheral_data_access_enabled': + assert(typeof prefValue === 'boolean'); + return { + setting: Setting.kPeripheralDataAccessProtection, + value: {boolValue: prefValue} as SettingChangeValue, + }; + + // pref to setting metric not implemented. + default: + return null; + } +}
diff --git a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_contact_visibility_dialog.html b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_contact_visibility_dialog.html index dd94192..714a754 100644 --- a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_contact_visibility_dialog.html +++ b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_contact_visibility_dialog.html
@@ -1,5 +1,5 @@ <style> - h1.title { + .title { color: var(--cr-primary-text-color); font-family: 'Google Sans'; font-weight: normal; @@ -8,7 +8,7 @@ padding-block-start: 24px; } - h2.header { + h3.header { color: var(--cr-secondary-text-color); font-size: inherit; font-weight: inherit; @@ -27,12 +27,12 @@ } </style> <cr-dialog id="dialog" show-on-attach> - <h1 slot="title" class="title"> + <div slot="title" class="title"> $i18n{nearbyShareVisibilityDialogTitle} - </h1> - <h2 slot="header" class="header"> + </div> + <h3 slot="header" class="header"> $i18n{nearbyShareVisibilityPageSubtitle} - </h2> + </h3> <div slot="body"> <nearby-contact-visibility id="contactVisibility" settings="{{settings}}">
diff --git a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_data_usage_dialog.html b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_data_usage_dialog.html index f7aa759..05f0f8a 100644 --- a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_data_usage_dialog.html +++ b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_data_usage_dialog.html
@@ -48,9 +48,7 @@ } </style> <cr-dialog id="dialog"> - <h2 slot="title"> - $i18n{nearbyShareDataUsageDialogTitle} - </h2> + <div slot="title">$i18n{nearbyShareDataUsageDialogTitle}</div> <div slot="body"> <cr-radio-group selected="[[selectedDataUsage_( settings.dataUsage)]]">
diff --git a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_device_name_dialog.html b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_device_name_dialog.html index 7b1a2150..7dce630 100644 --- a/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_device_name_dialog.html +++ b/chrome/browser/resources/settings/chromeos/nearby_share_page/nearby_share_device_name_dialog.html
@@ -15,9 +15,7 @@ } </style> <cr-dialog id="dialog"> - <h2 slot="title"> - $i18n{nearbyShareDeviceNameDialogTitle} - </h2> + <div slot="title">$i18n{nearbyShareDeviceNameDialogTitle}</div> <div slot="body"> <cr-input value="[[settings.deviceName]]" on-input="onDeviceNameInput_"
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/change_dictation_locale_dialog.html b/chrome/browser/resources/settings/chromeos/os_a11y_page/change_dictation_locale_dialog.html index 8a6416f..17119ca 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/change_dictation_locale_dialog.html +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/change_dictation_locale_dialog.html
@@ -8,8 +8,10 @@ padding-inline-start: 0; } - h2 { + h3 { color: var(--cros-text-color-secondary); + font-size: inherit; + margin: 0; min-height: 36px; padding-bottom: 0; padding-top: 0; @@ -78,9 +80,9 @@ clear-label="$i18n{dictationChangeLanguageDialogSearchClear}" on-keydown="onKeydown_" autofocus> </cr-search-field> - <h2 class="padded" hidden$="[[recommendedLocalesEmpty_]]"> + <h3 class="padded" hidden$="[[recommendedLocalesEmpty_]]"> $i18n{dictationChangeLanguageDialogRecommended} - </h2> + </h3> <iron-list id="recommendedLocalesList" items="[[recommendedLocales_]]" selection-enabled selected-item="{{selectedRecommendedLocale_}}" @@ -105,9 +107,9 @@ </div> </template> </iron-list> - <h2 class="padded" hidden$="[[displayedLocalesEmpty_]]"> + <h3 class="padded" hidden$="[[displayedLocalesEmpty_]]"> $i18n{dictationChangeLanguageDialogAll} - </h2> + </h3> <iron-list id="allLocalesList" items="[[displayedLocales_]]" selection-enabled selected-item="{{selectedLocale_}}"
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.html b/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.html index 5e76876b..e08939b 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.html +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.html
@@ -17,35 +17,55 @@ padding-inline-start: var(--cr-section-indent-width); } - h2 ~ settings-toggle-button { - margin-inline-end: var(--cr-section-padding); - margin-inline-start: var(--cr-section-indent-padding); - padding-inline-end: 0; - padding-inline-start: 0; + .indented { + margin-inline-start: 32px; } .settings-box { padding-inline-start: 0; } + + settings-toggle-button { + padding-inline-end: var(--cr-section-padding); + padding-inline-start: var(--cr-section-padding); + } </style> <h2>$i18n{selectToSpeakOptionsHighlight}</h2> -<settings-toggle-button - id="wordHighlightToggle" - pref="{{prefs.settings.a11y.select_to_speak_word_highlight}}" - label="$i18n{selectToSpeakOptionsHighlightDescription}" - deep-link-focus-id$="[[Setting.kSelectToSpeakWordHighlight]]"> -</settings-toggle-button> - -<settings-toggle-button - id="backgroundShadingToggle" - pref="{{prefs.settings.a11y.select_to_speak_background_shading}}" - label="$i18n{selectToSpeakOptionsBackgroundShadingDescription}" - deep-link-focus-id$="[[Setting.kSelectToSpeakBackgroundShading]]"> -</settings-toggle-button> - +<div class="sub-item"> + <settings-toggle-button + id="wordHighlightToggle" + class="settings-box continuation" + pref="{{prefs.settings.a11y.select_to_speak_word_highlight}}" + label="$i18n{selectToSpeakOptionsHighlightDescription}" + deep-link-focus-id$="[[Setting.kSelectToSpeakWordHighlight]]"> + </settings-toggle-button> + <template is="dom-if" + if="[[prefs.settings.a11y.select_to_speak_word_highlight.value]]"> + <div class="indented"> + <div class="settings-box continuation"> + <div class="start settings-box-text" aria-hidden="true"> + $i18n{selectToSpeakOptionsHighlightColorDescription} + </div> + <settings-dropdown-menu id="highlightColorDropdown" + label="$i18n{selectToSpeakOptionsHighlightColorDescription}" + pref="{{prefs.settings.a11y.select_to_speak_highlight_color}}" + menu-options="[[highlightColorOptions_]]"> + </settings-dropdown-menu> + </div> + </div> + </template> + <settings-toggle-button + id="backgroundShadingToggle" + class="settings-box continuation" + pref="{{prefs.settings.a11y.select_to_speak_background_shading}}" + label="$i18n{selectToSpeakOptionsBackgroundShadingDescription}" + deep-link-focus-id$="[[Setting.kSelectToSpeakBackgroundShading]]"> + </settings-toggle-button> +</div> <settings-toggle-button id="navigationControlsToggle" + class="hr" pref="{{prefs.settings.a11y.select_to_speak_navigation_controls}}" label="$i18n{selectToSpeakOptionsNavigationControlsDescription}" sub-label="$i18n{selectToSpeakOptionsNavigationControlsSubtitle}"
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.ts b/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.ts index 56c187e..6324e25 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.ts +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/select_to_speak_subpage.ts
@@ -14,6 +14,7 @@ import {I18nMixin, I18nMixinInterface} from 'chrome://resources/cr_elements/i18n_mixin.js'; import {WebUiListenerMixin, WebUiListenerMixinInterface} from 'chrome://resources/cr_elements/web_ui_listener_mixin.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Setting} from '../../mojom-webui/setting.mojom-webui.js'; @@ -49,6 +50,44 @@ static get properties() { return { + + /** + * List of options for the text size drop-down menu. + */ + highlightColorOptions_: { + readOnly: true, + type: Array, + value() { + return [ + { + value: '#5e9bff', + name: loadTimeData.getString( + 'selectToSpeakOptionsHighlightColorBlue'), + }, + { + value: '#ffa13d', + name: loadTimeData.getString( + 'selectToSpeakOptionsHighlightColorOrange'), + }, + { + value: '#eeff41', + name: loadTimeData.getString( + 'selectToSpeakOptionsHighlightColorYellow'), + }, + { + value: '#64dd17', + name: loadTimeData.getString( + 'selectToSpeakOptionsHighlightColorGreen'), + }, + { + value: '#ff4081', + name: loadTimeData.getString( + 'selectToSpeakOptionsHighlightColorPink'), + }, + ]; + }, + }, + /** * Used by DeepLinkingBehavior to focus this page's deep links. */
diff --git a/chrome/browser/resources/settings/chromeos/os_about_page/channel_switcher_dialog.html b/chrome/browser/resources/settings/chromeos/os_about_page/channel_switcher_dialog.html index 348b21d..11f09fe7 100644 --- a/chrome/browser/resources/settings/chromeos/os_about_page/channel_switcher_dialog.html +++ b/chrome/browser/resources/settings/chromeos/os_about_page/channel_switcher_dialog.html
@@ -2,6 +2,10 @@ #warningSelector > :not(.iron-selected) { display: none; } + + h3 { + font-size: inherit; + } </style> <cr-dialog id="dialog" close-text="$i18n{close}"> <div slot="title">$i18n{aboutChangeChannel}</div> @@ -22,7 +26,7 @@ </cr-radio-group> <iron-selector id="warningSelector"> <div> - <h2>$i18n{aboutDelayedWarningTitle}</h2> + <h3>$i18n{aboutDelayedWarningTitle}</h3> <div>[[substituteString_( '$i18nPolymer{aboutDelayedWarningMessage}', '$i18nPolymer{aboutOsProductTitle}')]]</div>
diff --git a/chrome/browser/resources/settings/chromeos/os_settings.gni b/chrome/browser/resources/settings/chromeos/os_settings.gni index e1e0d98..5429813e 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings.gni +++ b/chrome/browser/resources/settings/chromeos/os_settings.gni
@@ -222,6 +222,7 @@ "chromeos/lazy_load.js", "chromeos/main_page_mixin.ts", "chromeos/metrics_recorder.js", + "chromeos/metrics_utils.ts", "chromeos/multidevice_page/multidevice_browser_proxy.js", "chromeos/multidevice_page/multidevice_constants.js", "chromeos/multidevice_page/multidevice_feature_behavior.js", @@ -285,7 +286,6 @@ "chromeos/os_settings_routes.js", "chromeos/parental_controls_page/parental_controls_browser_proxy.ts", "chromeos/personalization_page/personalization_hub_browser_proxy.ts", - "chromeos/pref_to_setting_metric_converter.js", "chromeos/prefs_behavior.js", "chromeos/route_observer_behavior.js", "chromeos/route_origin_behavior.js",
diff --git a/chrome/browser/resources/settings/chromeos/os_settings_ui/os_settings_ui.ts b/chrome/browser/resources/settings/chromeos/os_settings_ui/os_settings_ui.ts index 08ead04e..4e4bc1c 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings_ui/os_settings_ui.ts +++ b/chrome/browser/resources/settings/chromeos/os_settings_ui/os_settings_ui.ts
@@ -35,9 +35,9 @@ import {castExists} from '../assert_extras.js'; import {setGlobalScrollTarget} from '../global_scroll_target_behavior.js'; import {recordClick, recordNavigation, recordPageBlur, recordPageFocus, recordSettingChange} from '../metrics_recorder.js'; +import {convertPrefToSettingMetric} from '../metrics_utils.js'; import {OSPageVisibility, osPageVisibility} from '../os_page_visibility.js'; import {OsToolbarElement} from '../os_toolbar/os_toolbar.js'; -import {PrefToSettingMetricConverter} from '../pref_to_setting_metric_converter.js'; import {getTemplate} from './os_settings_ui.html.js'; @@ -181,7 +181,6 @@ private showKerberosSection_: boolean; private narrowThreshold_: number; private activeRoute_: Route|null; - private prefToSettingMetricConverter_: PrefToSettingMetricConverter; private scrollEndDebouncer_: Debouncer|null; constructor() { @@ -193,11 +192,6 @@ */ this.activeRoute_ = null; - /** - * Converts prefs to settings metrics to help record pref changes. - */ - this.prefToSettingMetricConverter_ = new PrefToSettingMetricConverter(); - this.scrollEndDebouncer_ = null; Router.getInstance().initializeRouteFromUrl(); @@ -391,9 +385,7 @@ private onSettingChange_(e: CustomEvent<{prefKey: string, prefValue: any}>) { const {prefKey, prefValue} = e.detail; - const settingMetric = - this.prefToSettingMetricConverter_.convertPrefToSettingMetric( - prefKey, prefValue); + const settingMetric = convertPrefToSettingMetric(prefKey, prefValue); // New metrics for this setting pref have not yet been implemented. if (!settingMetric) {
diff --git a/chrome/browser/resources/settings/chromeos/pref_to_setting_metric_converter.js b/chrome/browser/resources/settings/chromeos/pref_to_setting_metric_converter.js deleted file mode 100644 index d55dd53..0000000 --- a/chrome/browser/resources/settings/chromeos/pref_to_setting_metric_converter.js +++ /dev/null
@@ -1,48 +0,0 @@ -/* Copyright 2020 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/** - * @fileoverview Helper class for converting a given settings pref to a pair of - * setting ID and setting change value. Used to record metrics about changes - * to pref-based settings. - */ - -import {SettingChangeValue} from '../mojom-webui/search/user_action_recorder.mojom-webui.js'; -import {Setting} from '../mojom-webui/setting.mojom-webui.js'; - -export class PrefToSettingMetricConverter { - /** - * @param {string} prefKey - * @param {*} prefValue - * @return {?{setting: !Setting, value: !SettingChangeValue}} - */ - convertPrefToSettingMetric(prefKey, prefValue) { - switch (prefKey) { - // device_page/keyboard.js - case 'settings.language.send_function_keys': - return { - setting: Setting.kKeyboardFunctionKeys, - value: {boolValue: /** @type {boolean} */ (prefValue)}, - }; - - // device_page/pointers.js - case 'settings.touchpad.sensitivity2': - return { - setting: Setting.kTouchpadSpeed, - value: {intValue: /** @type {number} */ (prefValue)}, - }; - - // os_privacy_page/os_privacy_page.js - case 'cros.device.peripheral_data_access_enabled': - return { - setting: Setting.kPeripheralDataAccessProtection, - value: {boolValue: /** @type {boolean} */ (prefValue)}, - }; - - // pref to setting metric not implemented. - default: - return null; - } - } -}
diff --git a/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html b/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html index ee383570c..edd9705 100644 --- a/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html +++ b/chrome/browser/resources/settings/privacy_page/security_keys_bio_enroll_dialog.html
@@ -13,6 +13,14 @@ flex: auto; } + h3 { + font-size: inherit; + font-weight: 500; + margin: 0; + padding-bottom: 12px; + padding-top: 32px; + } + iron-icon { padding-inline-end: 12px; } @@ -63,8 +71,7 @@ <div id="enrollments"> <div id="header" class="list-item column-header"> - <h2 class="header-label">[[enrollmentsHeader_(enrollments_)]]</h2> - + <h3 class="header-label">[[enrollmentsHeader_(enrollments_)]]</h3> <cr-button id="addButton" on-click="addButtonClick_" class="secondary-button header-aligned-button"> $i18n{add}
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index 84a9b4d..e100446 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -118,6 +118,9 @@ report->mutable_download_warning_actions()->Add( DownloadItemWarningData::ConstructCsbrrDownloadWarningAction(event)); } + base::UmaHistogramCounts100( + "SafeBrowsing.ClientSafeBrowsingReport.DownloadWarningActionSize", + report->download_warning_actions_size()); } #endif
diff --git a/chrome/browser/search_engines/android/java/src/org/chromium/chrome/browser/search_engines/OWNERS b/chrome/browser/search_engines/android/java/src/org/chromium/chrome/browser/search_engines/OWNERS index bf7cd4e..e69de29 100644 --- a/chrome/browser/search_engines/android/java/src/org/chromium/chrome/browser/search_engines/OWNERS +++ b/chrome/browser/search_engines/android/java/src/org/chromium/chrome/browser/search_engines/OWNERS
@@ -1 +0,0 @@ -fgorski@chromium.org
diff --git a/chrome/browser/speech/chrome_speech_recognition_service.cc b/chrome/browser/speech/chrome_speech_recognition_service.cc index e7f1edd..2edcd2b6 100644 --- a/chrome/browser/speech/chrome_speech_recognition_service.cc +++ b/chrome/browser/speech/chrome_speech_recognition_service.cc
@@ -4,6 +4,9 @@ #include "chrome/browser/speech/chrome_speech_recognition_service.h" +#include <string> + +#include "base/containers/flat_map.h" #include "base/metrics/histogram_functions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/component_updater/soda_language_pack_component_installer.h" @@ -56,11 +59,25 @@ DCHECK(profile_prefs); DCHECK(global_prefs); - base::FilePath binary_path, config_path; + // TODO(crbug.com/1161569): Language pack path should be configurable per + // SpeechRecognitionRecognizer to allow multiple features to use Speech + // recognition. For now, only Live Caption uses SpeechRecognitionService on + // non-Chrome OS Chrome, so hard-coding to the Live Caption language code. + const std::string language_name = + prefs::GetLiveCaptionLanguageCode(profile_prefs); + + absl::optional<speech::SodaLanguagePackComponentConfig> language_config = + speech::GetLanguageComponentConfig(language_name); + CHECK(language_config); + base::UmaHistogramEnumeration("Accessibility.LiveCaption.SodaLanguage", + language_config.value().language_code); + + base::FilePath binary_path; binary_path = global_prefs->GetFilePath(prefs::kSodaBinaryPath); - config_path = - ChromeSpeechRecognitionService::GetSodaConfigPath(profile_prefs); - if (binary_path.empty() || config_path.empty()) { + base::flat_map<std::string, base::FilePath> config_paths = + ChromeSpeechRecognitionService::GetSodaConfigPaths(profile_prefs); + + if (binary_path.empty() || config_paths[language_name].empty()) { LOG(ERROR) << "Unable to find SODA files on the device."; return; } @@ -78,26 +95,23 @@ // terminated if it isn't already. speech_recognition_service_.reset_on_disconnect(); speech_recognition_service_.reset_on_idle_timeout(kIdleProcessTimeout); - speech_recognition_service_->SetSodaPath(binary_path, config_path); + speech_recognition_service_->SetSodaPaths(binary_path, config_paths, + language_name); } -base::FilePath ChromeSpeechRecognitionService::GetSodaConfigPath( - PrefService* prefs) { - // TODO(crbug.com/1161569): Language pack path should be configurable per - // SpeechRecognitionRecognizer to allow multiple features to use Speech - // recognition. For now, only Live Caption uses SpeechRecognitionService on - // non-Chrome OS Chrome, so hard-coding to the Live Caption language code. - absl::optional<speech::SodaLanguagePackComponentConfig> language_config = - speech::GetLanguageComponentConfig( - prefs::GetLiveCaptionLanguageCode(prefs)); +base::flat_map<std::string, base::FilePath> +ChromeSpeechRecognitionService::GetSodaConfigPaths(PrefService* prefs) { + base::flat_map<std::string, base::FilePath> config_file_paths; + for (const SodaLanguagePackComponentConfig& config : + kLanguageComponentConfigs) { + base::FilePath config_path = + g_browser_process->local_state()->GetFilePath(config.config_path_pref); - if (language_config) { - base::UmaHistogramEnumeration("Accessibility.LiveCaption.SodaLanguage", - language_config.value().language_code); - return g_browser_process->local_state()->GetFilePath( - language_config.value().config_path_pref); + if (!config_path.empty()) { + config_file_paths[config.language_name] = config_path; + } } - return base::FilePath(); + return config_file_paths; } } // namespace speech
diff --git a/chrome/browser/speech/chrome_speech_recognition_service.h b/chrome/browser/speech/chrome_speech_recognition_service.h index 1609398..c8cbc77f 100644 --- a/chrome/browser/speech/chrome_speech_recognition_service.h +++ b/chrome/browser/speech/chrome_speech_recognition_service.h
@@ -5,6 +5,9 @@ #ifndef CHROME_BROWSER_SPEECH_CHROME_SPEECH_RECOGNITION_SERVICE_H_ #define CHROME_BROWSER_SPEECH_CHROME_SPEECH_RECOGNITION_SERVICE_H_ +#include <string> + +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "chrome/browser/speech/speech_recognition_service.h" @@ -48,7 +51,8 @@ void LaunchIfNotRunning(); // Gets the path of the SODA configuration file for the selected language. - base::FilePath GetSodaConfigPath(PrefService* prefs); + base::flat_map<std::string, base::FilePath> GetSodaConfigPaths( + PrefService* prefs); // The browser context associated with the keyed service. raw_ptr<content::BrowserContext> context_;
diff --git a/chrome/browser/speech/cros_speech_recognition_service.cc b/chrome/browser/speech/cros_speech_recognition_service.cc index 7908e01..6351116 100644 --- a/chrome/browser/speech/cros_speech_recognition_service.cc +++ b/chrome/browser/speech/cros_speech_recognition_service.cc
@@ -4,7 +4,11 @@ #include "chrome/browser/speech/cros_speech_recognition_service.h" +#include <memory> +#include <string> + #include "ash/constants/ash_features.h" +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/types/optional_util.h" #include "chrome/services/speech/audio_source_fetcher_impl.h" @@ -32,9 +36,10 @@ constexpr char kInvalidSpeechRecogntionOptions[] = "Invalid SpeechRecognitionOptions provided"; -void PopulateFilePaths(const std::string* language, - base::FilePath& binary_path, - base::FilePath& languagepack_path) { +void PopulateFilePaths( + const std::string* language, + base::FilePath& binary_path, + base::flat_map<std::string, base::FilePath>& config_paths) { speech::SodaInstaller* soda_installer = speech::SodaInstaller::GetInstance(); // TODO(crbug.com/1161569): Language should not be optional in // PopulateFilePaths, as it will be required once we support multiple @@ -49,8 +54,11 @@ "already installed"; return; } + binary_path = soda_installer->GetSodaBinaryPath(); - languagepack_path = + // TODO(crbug.com/1161569): Populate config_paths with all language packs + // once the new language packs are available on ChromeOS. + config_paths[GetLanguageName(language_code)] = soda_installer->GetLanguagePath(GetLanguageName(language_code)); } @@ -87,13 +95,17 @@ return; } - base::FilePath binary_path, languagepack_path; + base::FilePath binary_path; + base::flat_map<std::string, base::FilePath> config_paths; + std::string language_name = options->language + ? options->language.value() + : GetLanguageName(LanguageCode::kEnUs); PopulateFilePaths(base::OptionalToPtr(options->language), binary_path, - languagepack_path); + config_paths); CrosSpeechRecognitionRecognizerImpl::Create( std::move(receiver), std::move(client), std::move(options), binary_path, - languagepack_path); + config_paths, language_name); std::move(callback).Run( CrosSpeechRecognitionRecognizerImpl::IsMultichannelSupported()); } @@ -104,10 +116,14 @@ media::mojom::SpeechRecognitionOptionsPtr options, BindRecognizerCallback callback) { if (!options->is_server_based) { - base::FilePath binary_path, languagepack_path; + base::FilePath binary_path; + base::flat_map<std::string, base::FilePath> config_paths; PopulateFilePaths(base::OptionalToPtr(options->language), binary_path, - languagepack_path); + config_paths); + std::string language_name = options->language + ? options->language.value() + : GetLanguageName(LanguageCode::kEnUs); // CrosSpeechRecognitionService runs on browser UI thread. // Create AudioSourceFetcher on browser IO thread to avoid UI jank. // Note that its CrosSpeechRecognitionRecognizer must also run @@ -119,8 +135,8 @@ &CrosSpeechRecognitionService:: CreateAudioSourceFetcherForOnDeviceRecognitionOnIOThread, weak_factory_.GetWeakPtr(), std::move(fetcher_receiver), - std::move(client), std::move(options), binary_path, - languagepack_path)); + std::move(client), std::move(options), binary_path, config_paths, + language_name)); std::move(callback).Run( CrosSpeechRecognitionRecognizerImpl::IsMultichannelSupported()); return; @@ -156,14 +172,15 @@ client, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& languagepack_path) { + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(!options->is_server_based); AudioSourceFetcherImpl::Create( std::move(fetcher_receiver), std::make_unique<CrosSpeechRecognitionRecognizerImpl>( - std::move(client), std::move(options), binary_path, - languagepack_path), + std::move(client), std::move(options), binary_path, config_paths, + primary_language_name), CrosSpeechRecognitionRecognizerImpl::IsMultichannelSupported(), /*is_server_based=*/false); }
diff --git a/chrome/browser/speech/cros_speech_recognition_service.h b/chrome/browser/speech/cros_speech_recognition_service.h index 5d9b73fb..ebc09e0 100644 --- a/chrome/browser/speech/cros_speech_recognition_service.h +++ b/chrome/browser/speech/cros_speech_recognition_service.h
@@ -6,8 +6,10 @@ #define CHROME_BROWSER_SPEECH_CROS_SPEECH_RECOGNITION_SERVICE_H_ #include <memory> +#include <string> #include "base/bind.h" +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "chrome/browser/speech/chrome_speech_recognition_service.h" #include "media/mojo/mojom/speech_recognition.mojom.h" @@ -70,7 +72,8 @@ client, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& languagepack_path); + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name); void CreateAudioSourceFetcherForServerBasedRecognitionOnIOThread( mojo::PendingReceiver<media::mojom::AudioSourceFetcher> fetcher_receiver,
diff --git a/chrome/browser/speech/crosapi_tts_engine_delegate_ash.cc b/chrome/browser/speech/crosapi_tts_engine_delegate_ash.cc index 9198f35..e78c1af 100644 --- a/chrome/browser/speech/crosapi_tts_engine_delegate_ash.cc +++ b/chrome/browser/speech/crosapi_tts_engine_delegate_ash.cc
@@ -37,3 +37,17 @@ out_voices); } } + +void CrosapiTtsEngineDelegateAsh::Speak(content::TtsUtterance* utterance, + const content::VoiceData& voice) { + DCHECK(voice.from_remote_tts_engine); + crosapi::CrosapiManager::Get() + ->crosapi_ash() + ->tts_ash() + ->SpeakWithLacrosVoice(utterance, voice); +} + +void CrosapiTtsEngineDelegateAsh::Stop(content::TtsUtterance* utterance) { + crosapi::CrosapiManager::Get()->crosapi_ash()->tts_ash()->StopRemoteEngine( + utterance); +}
diff --git a/chrome/browser/speech/crosapi_tts_engine_delegate_ash.h b/chrome/browser/speech/crosapi_tts_engine_delegate_ash.h index b71521e..7435e90 100644 --- a/chrome/browser/speech/crosapi_tts_engine_delegate_ash.h +++ b/chrome/browser/speech/crosapi_tts_engine_delegate_ash.h
@@ -21,6 +21,9 @@ // content::RemoteTtsEngineDelegate: void GetVoices(content::BrowserContext* browser_context, std::vector<content::VoiceData>* out_voices) override; + void Speak(content::TtsUtterance* utterance, + const content::VoiceData& voice) override; + void Stop(content::TtsUtterance* utterance) override; }; #endif // CHROME_BROWSER_SPEECH_CROSAPI_TTS_ENGINE_DELEGATE_ASH_H_
diff --git a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc index 83874e5..2a89797f 100644 --- a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc
@@ -23,6 +23,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/tts_controller.h" +#include "content/public/browser/tts_platform.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" @@ -169,6 +170,30 @@ return std::make_unique<std::vector<extensions::TtsVoice>>(); } +bool GetTtsEventType(const std::string event_type_string, + content::TtsEventType* event_type) { + if (event_type_string == constants::kEventTypeStart) { + *event_type = content::TTS_EVENT_START; + } else if (event_type_string == constants::kEventTypeEnd) { + *event_type = content::TTS_EVENT_END; + } else if (event_type_string == constants::kEventTypeWord) { + *event_type = content::TTS_EVENT_WORD; + } else if (event_type_string == constants::kEventTypeSentence) { + *event_type = content::TTS_EVENT_SENTENCE; + } else if (event_type_string == constants::kEventTypeMarker) { + *event_type = content::TTS_EVENT_MARKER; + } else if (event_type_string == constants::kEventTypeError) { + *event_type = content::TTS_EVENT_ERROR; + } else if (event_type_string == constants::kEventTypePause) { + *event_type = content::TTS_EVENT_PAUSE; + } else if (event_type_string == constants::kEventTypeResume) { + *event_type = content::TTS_EVENT_RESUME; + } else { + return false; + } + return true; +} + #if BUILDFLAG(IS_CHROMEOS_ASH) bool CanUseEnhancedNetworkVoices(const GURL& source_url, Profile* profile) { @@ -295,12 +320,16 @@ } void TtsExtensionEngine::Stop(content::TtsUtterance* utterance) { - Profile* profile = - Profile::FromBrowserContext(utterance->GetBrowserContext()); + Stop(utterance->GetBrowserContext(), utterance->GetEngineId()); +} + +void TtsExtensionEngine::Stop(content::BrowserContext* browser_context, + const std::string& engine_id) { + Profile* profile = Profile::FromBrowserContext(browser_context); auto event = std::make_unique<extensions::Event>( extensions::events::TTS_ENGINE_ON_STOP, tts_engine_events::kOnStop, base::Value::List(), profile); - EventRouter::Get(profile)->DispatchEventToExtension(utterance->GetEngineId(), + EventRouter::Get(profile)->DispatchEventToExtension(engine_id, std::move(event)); } @@ -458,41 +487,32 @@ break; } } + + std::string error_message; + if (*event_type == constants::kEventTypeError) { + const std::string* err_msg = event.FindString(constants::kErrorMessageKey); + error_message = err_msg != nullptr ? *err_msg : ""; + } + if (!event_type_allowed) return RespondNow(Error(constants::kErrorUndeclaredEventType)); - content::TtsController* controller = content::TtsController::GetInstance(); - if (*event_type == constants::kEventTypeStart) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_START, char_index, - length, std::string()); - } else if (*event_type == constants::kEventTypeEnd) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_END, char_index, - length, std::string()); - } else if (*event_type == constants::kEventTypeWord) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_WORD, char_index, - length, std::string()); - } else if (*event_type == constants::kEventTypeSentence) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_SENTENCE, - char_index, length, std::string()); - } else if (*event_type == constants::kEventTypeMarker) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_MARKER, char_index, - length, std::string()); - } else if (*event_type == constants::kEventTypeError) { - const std::string* error_message = - event.FindString(constants::kErrorMessageKey); - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_ERROR, char_index, - length, - error_message != nullptr ? *error_message : ""); - } else if (*event_type == constants::kEventTypePause) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_PAUSE, char_index, - length, std::string()); - } else if (*event_type == constants::kEventTypeResume) { - controller->OnTtsEvent(utterance_id, content::TTS_EVENT_RESUME, char_index, - length, std::string()); - } else { + content::TtsEventType tts_event_type; + if (!GetTtsEventType(*event_type, &tts_event_type)) { EXTENSION_FUNCTION_VALIDATE(false); + } else if (content::TtsPlatform::GetInstance() + ->GetExternalPlatformDelegate()) { + // If lacros_tts_support is enabled, TTS events routes to + // ExternalPlatformDelegate. + content::TtsPlatform::GetInstance() + ->GetExternalPlatformDelegate() + ->OnTtsEvent(browser_context(), utterance_id, tts_event_type, + char_index, length, error_message); + } else { + // If lacros_tts_support is not enabled, TTS events routes to TtsController. + content::TtsController::GetInstance()->OnTtsEvent( + utterance_id, tts_event_type, char_index, length, error_message); } - return RespondNow(NoArguments()); }
diff --git a/chrome/browser/speech/extension_api/tts_engine_extension_api.h b/chrome/browser/speech/extension_api/tts_engine_extension_api.h index 6b562673..cdd36bd 100644 --- a/chrome/browser/speech/extension_api/tts_engine_extension_api.h +++ b/chrome/browser/speech/extension_api/tts_engine_extension_api.h
@@ -44,6 +44,8 @@ void Speak(content::TtsUtterance* utterance, const content::VoiceData& voice) override; void Stop(content::TtsUtterance* utterance) override; + void Stop(content::BrowserContext* browser_context, + const std::string& engine_id) override; void Pause(content::TtsUtterance* utterance) override; void Resume(content::TtsUtterance* utterance) override; void LoadBuiltInTtsEngine(content::BrowserContext* browser_context) override;
diff --git a/chrome/browser/speech/tts_ash.cc b/chrome/browser/speech/tts_ash.cc index 276adc4..65aee2df 100644 --- a/chrome/browser/speech/tts_ash.cc +++ b/chrome/browser/speech/tts_ash.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/ash/crosapi/browser_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/crosapi_tts_engine_delegate_ash.h" +#include "chrome/browser/speech/extension_api/tts_engine_extension_api.h" #include "chrome/browser/speech/tts_crosapi_util.h" #include "chromeos/crosapi/mojom/tts.mojom.h" #include "content/public/browser/browser_context.h" @@ -29,21 +30,24 @@ // The lifetime of instance of this class is bound to the lifetime of the // associated TtsUtterance. It will be deleted when the associated TtsUtterance // receives the final event. -class CrosapiUtteranceEventDelegate : public content::UtteranceEventDelegate { +class LacrosUtteranceEventDelegate : public content::UtteranceEventDelegate { public: - CrosapiUtteranceEventDelegate( + LacrosUtteranceEventDelegate( int utterance_id, + int remote_utterance_id, mojo::PendingRemote<crosapi::mojom::TtsUtteranceClient> client) - : utterance_id_(utterance_id), client_(std::move(client)) { + : utterance_id_(utterance_id), + remote_utterance_id_(remote_utterance_id), + client_(std::move(client)) { client_.set_disconnect_handler(base::BindOnce( - &CrosapiUtteranceEventDelegate::OnTtsUtteranceClientDisconnected, + &LacrosUtteranceEventDelegate::OnTtsUtteranceClientDisconnected, weak_ptr_factory_.GetWeakPtr())); } - CrosapiUtteranceEventDelegate(const CrosapiUtteranceEventDelegate&) = delete; - CrosapiUtteranceEventDelegate& operator=( - const CrosapiUtteranceEventDelegate&) = delete; - ~CrosapiUtteranceEventDelegate() override = default; + LacrosUtteranceEventDelegate(const LacrosUtteranceEventDelegate&) = delete; + LacrosUtteranceEventDelegate& operator=(const LacrosUtteranceEventDelegate&) = + delete; + ~LacrosUtteranceEventDelegate() override = default; // content::UtteranceEventDelegate methods: void OnTtsEvent(content::TtsUtterance* utterance, @@ -59,6 +63,8 @@ delete this; } + int GetRemoteUtteranceId() const { return remote_utterance_id_; } + private: void OnTtsUtteranceClientDisconnected() { content::TtsController::GetInstance()->OnTtsUtteranceBecameInvalid( @@ -68,13 +74,30 @@ // Id of the TtsUtterance to be processed by Ash's TtsController. int utterance_id_; + // Id of the associate TtsUtterace living in Lacros. + int remote_utterance_id_; + // Can be used to forward the Tts events back to Lacros, or notify Ash // TtsController when the original utterance in Lacros becomes invalid. mojo::Remote<crosapi::mojom::TtsUtteranceClient> client_; - base::WeakPtrFactory<CrosapiUtteranceEventDelegate> weak_ptr_factory_{this}; + base::WeakPtrFactory<LacrosUtteranceEventDelegate> weak_ptr_factory_{this}; }; +// Returns id for the TtsUtterance living in Lacros associated with the given +// |utternace| (in Ash). +// Note: A Lacros utterance has a TtsUtterance object created in Lacros +// which forwards TTS events back to callback function in Lacros; it also +// has a TtsUtterance object created in Ash to be queued in the Ash +// TtsController's utterance queue. +int GetRemoteUtteranceId(content::TtsUtterance* utterance) { + DCHECK(utterance->ShouldAlwaysBeSpoken()); + LacrosUtteranceEventDelegate* lacros_utterance_event_delegate = + static_cast<LacrosUtteranceEventDelegate*>(utterance->GetEventDelegate()); + DCHECK(lacros_utterance_event_delegate); + return lacros_utterance_event_delegate->GetRemoteUtteranceId(); +} + } // namespace namespace crosapi { @@ -117,6 +140,10 @@ // This code path is only called when running lacros browser tests. content::TtsController::GetInstance()->SetRemoteTtsEngineDelegate( CrosapiTtsEngineDelegateAsh::GetInstance()); + // Disable the built-in TTS engine for testing. + // This will be used by the Lacros browser test running with Ash. + TtsExtensionEngine::GetInstance() + ->DisableBuiltInTTSEngineForTesting(); // IN-TEST } mojo::Remote<mojom::TtsClient> remote(std::move(client)); @@ -150,12 +177,50 @@ mojo::PendingRemote<mojom::TtsUtteranceClient> utterance_client) { std::unique_ptr<content::TtsUtterance> utterance = tts_crosapi_util::FromMojo(mojo_utterance); - utterance->SetEventDelegate(new CrosapiUtteranceEventDelegate( - utterance->GetId(), std::move(utterance_client))); + utterance->SetEventDelegate(new LacrosUtteranceEventDelegate( + utterance->GetId(), mojo_utterance->utterance_id, + std::move(utterance_client))); content::TtsController::GetInstance()->SpeakOrEnqueue(std::move(utterance)); } +void TtsAsh::SpeakWithLacrosVoice(content::TtsUtterance* utterance, + const content::VoiceData& voice) { + if (!HasTtsClient()) + return; + + DCHECK(voice.from_remote_tts_engine); + if (utterance->ShouldAlwaysBeSpoken()) { + // Speak Lacros utterance. + auto mojo_voice = tts_crosapi_util::ToMojo(voice); + auto mojo_utterance = tts_crosapi_util::ToMojo(utterance); + mojo_utterance->utterance_id = GetRemoteUtteranceId(utterance); + + // Don't need to pass utterance text back to Lacros via crosapi, since its + // associated TtsUtterance object living in Lacros already has it. + mojo_utterance->text = ""; + + // TODO(crbug.com/1251979): Support secondary profile of Lacros. + base::UnguessableToken browser_context_id = + GetPrimaryProfileBrowserContextId(); + mojo_utterance->browser_context_id = browser_context_id; + auto item = tts_clients_.find(browser_context_id); + DCHECK(item != tts_clients_.end()); + item->second->SpeakWithLacrosVoice(std::move(mojo_utterance), + std::move(mojo_voice), + /*ash_utterance_client=*/{}); + } else { + // TODO(crbug.com/1227543): Implement speaking Ash utterance with Lacros + // voice. Speak Ash utterance. + } +} + +void TtsAsh::StopRemoteEngine(content::TtsUtterance* utterance) { + auto item = tts_clients_.find(GetPrimaryProfileBrowserContextId()); + DCHECK(item != tts_clients_.end()); + item->second->Stop(utterance->GetEngineId()); +} + void TtsAsh::GetCrosapiVoices(base::UnguessableToken browser_context_id, std::vector<content::VoiceData>* out_voices) { // Returns the cached Lacros voices.
diff --git a/chrome/browser/speech/tts_ash.h b/chrome/browser/speech/tts_ash.h index 868aae39..beeac527 100644 --- a/chrome/browser/speech/tts_ash.h +++ b/chrome/browser/speech/tts_ash.h
@@ -45,6 +45,15 @@ void GetCrosapiVoices(base::UnguessableToken browser_context_id, std::vector<content::VoiceData>* out_voices); + // Requests to the associated Lacros speech engine to speak the given + // |utterance| with the given |voice|. + void SpeakWithLacrosVoice(content::TtsUtterance* utterance, + const content::VoiceData& voice); + + // Requests the associated Lacros speech engine to stop speaking the + // |utterance|. + void StopRemoteEngine(content::TtsUtterance* utterance); + // crosapi::mojom::Tts: void RegisterTtsClient(mojo::PendingRemote<mojom::TtsClient> client, const base::UnguessableToken& browser_context_id,
diff --git a/chrome/browser/speech/tts_client_lacros.cc b/chrome/browser/speech/tts_client_lacros.cc index 1f4fbf8c..01bfb981 100644 --- a/chrome/browser/speech/tts_client_lacros.cc +++ b/chrome/browser/speech/tts_client_lacros.cc
@@ -41,6 +41,8 @@ } // namespace // This class implements crosapi::mojom::TtsUtteranceClient. +// It is used to create a remote pending utterance client for a Lacros +// utterance sent to Ash's TtsController. // It observes the WebContent associated with the original utterance in Lacros. class TtsClientLacros::TtsUtteraneClient : public crosapi::mojom::TtsUtteranceClient, @@ -57,9 +59,10 @@ ~TtsUtteraneClient() override = default; // crosapi::mojom::TtsUtteranceClient: - // Called from Ash to forward the speech engine event back to the original + // Called from Ash to forward the Ash speech engine event back to the original // TtsUtterance in Lacros, which will forward the event to its - // UtteranceEventDelegate. + // UtteranceEventDelegate. This is used when the utterance is spoken by + // a Ash voice. void OnTtsEvent(crosapi::mojom::TtsEventType mojo_tts_event, uint32_t char_index, uint32_t char_length, @@ -75,6 +78,24 @@ } } + // Handle TtsEvent received from Lacros speech engine if the utterance is + // spoken by a Lacros TTS engine, forward the event to callback function and + // finishing the current utterance processing if receiving completion or error + // events. + void OnLacrosSpeechEngineTtsEvent(int utterance_id, + content::TtsEventType event_type, + int char_index, + int length, + const std::string& error_message) { + utterance_->OnTtsEvent(event_type, char_index, length, error_message); + + if (content::IsFinalTtsEventType(event_type)) { + utterance_->Finish(); + owner_->DeletePendingUtteranceClient(utterance_->GetId()); + // Note: |this| is deleted at this point. + } + } + // content::WebContentsObserver: void WebContentsDestroyed() override { // Clean up the utterance in Lacros. @@ -93,6 +114,8 @@ return receiver_.BindNewPipeAndPassRemoteWithVersion(); } + content::TtsUtterance* GetUttenrance() { return utterance_.get(); } + private: TtsClientLacros* owner_; // now owned // This is the original utterance in Lacros, owned. @@ -144,6 +167,31 @@ content::TtsController::GetInstance()->VoicesChanged(); } +void TtsClientLacros::SpeakWithLacrosVoice( + crosapi::mojom::TtsUtterancePtr mojo_utterance, + crosapi::mojom::TtsVoicePtr mojo_voice, + mojo::PendingRemote<crosapi::mojom::TtsUtteranceClient> + ash_pending_utterance_client) { + // Speak a Lacros utterance with a Lacros voice. + content::VoiceData voice = tts_crosapi_util::FromMojo(mojo_voice); + if (!ash_pending_utterance_client) { + auto item = pending_utterance_clients_.find(mojo_utterance->utterance_id); + if (item != pending_utterance_clients_.end()) { + // Speaking a Lacros utterance. + content::TtsUtterance* current_utterance_to_speak = + item->second->GetUttenrance(); + current_utterance_to_speak->SetEngineId(mojo_utterance->engine_id); + content::TtsController::GetInstance()->GetTtsEngineDelegate()->Speak( + current_utterance_to_speak, voice); + } + } +} + +void TtsClientLacros::Stop(const std::string& engine_id) { + content::TtsController::GetInstance()->GetTtsEngineDelegate()->Stop( + browser_context_, engine_id); +} + void TtsClientLacros::GetAllVoices( std::vector<content::VoiceData>* out_voices) { // Return the cached voices that should be available for the associated @@ -265,6 +313,20 @@ pending_utterance_clients_.emplace(utterance_id, std::move(pending_client)); } +void TtsClientLacros::OnLacrosSpeechEngineTtsEvent( + int utterance_id, + content::TtsEventType event_type, + int char_index, + int length, + const std::string& error_message) { + auto item = pending_utterance_clients_.find(utterance_id); + if (item != pending_utterance_clients_.end()) { + // Lacros utterance. + item->second->OnLacrosSpeechEngineTtsEvent( + utterance_id, event_type, char_index, length, error_message); + } +} + void TtsClientLacros::DeletePendingUtteranceClient(int utterance_id) { pending_utterance_clients_.erase(utterance_id); }
diff --git a/chrome/browser/speech/tts_client_lacros.h b/chrome/browser/speech/tts_client_lacros.h index bda84d8e..f4abab1 100644 --- a/chrome/browser/speech/tts_client_lacros.h +++ b/chrome/browser/speech/tts_client_lacros.h
@@ -39,6 +39,12 @@ // crosapi::mojom::TtsClient: void VoicesChanged( std::vector<crosapi::mojom::TtsVoicePtr> mojo_all_voices) override; + void SpeakWithLacrosVoice( + crosapi::mojom::TtsUtterancePtr utterance, + crosapi::mojom::TtsVoicePtr voice, + mojo::PendingRemote<crosapi::mojom::TtsUtteranceClient> + ash_utterance_client) override; + void Stop(const std::string& engine_id) override; const base::UnguessableToken& browser_context_id() const { return browser_context_id_; @@ -51,6 +57,13 @@ // Forwards the given utterance to Ash to be processed by Ash TtsController. void SpeakOrEnqueue(std::unique_ptr<content::TtsUtterance> utterance); + // Handle events received from the Lacros speech engine. + void OnLacrosSpeechEngineTtsEvent(int utterance_id, + content::TtsEventType event_type, + int char_index, + int length, + const std::string& error_message); + void DeletePendingUtteranceClient(int utterance_id); content::BrowserContext* browser_context() { return browser_context_; } @@ -88,7 +101,7 @@ bool is_offline_; - // Pending Tts Utterance clients by by utterance id. + // Pending Lacros Tts Utterance clients by by utterance id. std::map<int, std::unique_ptr<TtsUtteraneClient>> pending_utterance_clients_; base::WeakPtrFactory<TtsClientLacros> weak_ptr_factory_{this};
diff --git a/chrome/browser/speech/tts_crosapi_util.cc b/chrome/browser/speech/tts_crosapi_util.cc index 01b7643..b710bbc7 100644 --- a/chrome/browser/speech/tts_crosapi_util.cc +++ b/chrome/browser/speech/tts_crosapi_util.cc
@@ -74,7 +74,8 @@ content::VoiceData FromMojo(const crosapi::mojom::TtsVoicePtr& mojo_voice) { content::VoiceData voice_data; #if BUILDFLAG(IS_CHROMEOS_ASH) - voice_data.from_crosapi = true; + // The mojo_voice is from the remote TTS engine in Lacros. + voice_data.from_remote_tts_engine = true; #endif voice_data.name = mojo_voice->voice_name; voice_data.lang = mojo_voice->lang;
diff --git a/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.cc b/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.cc index 05903c3..af1b148 100644 --- a/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.cc +++ b/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.cc
@@ -5,6 +5,8 @@ #include "chrome/browser/speech/tts_external_platform_delegate_impl_lacros.h" #include "base/no_destructor.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/tts_client_lacros.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/tts_controller.h" @@ -38,3 +40,15 @@ TtsClientLacros::GetForBrowserContext(utterance->GetBrowserContext()) ->SpeakOrEnqueue(std::move(utterance)); } + +void ExternalPlatformDelegateImplLacros::OnTtsEvent( + content::BrowserContext* browser_context, + int utterance_id, + content::TtsEventType event_type, + int char_index, + int length, + const std::string& error_message) { + TtsClientLacros::GetForBrowserContext(browser_context) + ->OnLacrosSpeechEngineTtsEvent(utterance_id, event_type, char_index, + length, error_message); +}
diff --git a/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.h b/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.h index d4702e2..a3a29ec 100644 --- a/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.h +++ b/chrome/browser/speech/tts_external_platform_delegate_impl_lacros.h
@@ -25,6 +25,12 @@ const GURL& source_url, std::vector<content::VoiceData>* out_voices) override; void Enqueue(std::unique_ptr<content::TtsUtterance> utterance) override; + void OnTtsEvent(content::BrowserContext* browser_context, + int utterance_id, + content::TtsEventType event_type, + int char_index, + int length, + const std::string& error_message) override; private: friend class base::NoDestructor<ExternalPlatformDelegateImplLacros>;
diff --git a/chrome/browser/supervised_user/web_approvals_manager.cc b/chrome/browser/supervised_user/web_approvals_manager.cc index b29f3b4..30d1eb9 100644 --- a/chrome/browser/supervised_user/web_approvals_manager.cc +++ b/chrome/browser/supervised_user/web_approvals_manager.cc
@@ -14,7 +14,6 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_key.h" -#include "chrome/browser/supervised_user/android/website_parent_approval.h" #include "chrome/browser/supervised_user/permission_request_creator.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" @@ -24,9 +23,13 @@ #include "ui/gfx/codec/png_codec.h" #include "url/gurl.h" +#if BUILDFLAG(IS_ANDROID) +#include "chrome/browser/supervised_user/android/website_parent_approval.h" +#endif // BUILDFLAG(IS_ANDROID) + #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ui/webui/ash/parent_access/parent_access_ui.mojom.h" -#endif +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { @@ -42,88 +45,60 @@ creator->CreateURLAccessRequest(url, std::move(callback)); } -// Helper method for getting human readable outcome for a local web approval. -std::string EnumLocalWebApprovalFlowOutcomeToString( +#if BUILDFLAG(IS_ANDROID) +WebApprovalsManager::LocalApprovalResult AndroidOutcomeToLocalApprovalResult( AndroidLocalWebApprovalFlowOutcome outcome) { switch (outcome) { case AndroidLocalWebApprovalFlowOutcome::kApproved: - return "Approved"; + return WebApprovalsManager::LocalApprovalResult::kApproved; case AndroidLocalWebApprovalFlowOutcome::kRejected: - return "Rejected"; + return WebApprovalsManager::LocalApprovalResult::kDeclined; case AndroidLocalWebApprovalFlowOutcome::kIncomplete: - return "Incomplete"; + return WebApprovalsManager::LocalApprovalResult::kCanceled; } } - -void RecordLocalApprovalResultMetricForAndroidOutcome( - AndroidLocalWebApprovalFlowOutcome outcome) { - WebApprovalsManager::LocalApprovalResultMetric histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kError; - switch (outcome) { - case AndroidLocalWebApprovalFlowOutcome::kApproved: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kApproved; - break; - case AndroidLocalWebApprovalFlowOutcome::kRejected: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kDeclined; - break; - case AndroidLocalWebApprovalFlowOutcome::kIncomplete: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kCanceled; - break; - } - base::UmaHistogramEnumeration(kLocalWebApprovalResultHistogramName, - histogram_enum); -} +#endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) -// Helper method for getting human readable outcome for a local web approval. -std::string ParentAccessResultToLoggingStringChromeOS( - ash::ParentAccessDialog::Result::Status outcome) { - switch (outcome) { +WebApprovalsManager::LocalApprovalResult ChromeOSResultToLocalApprovalResult( + ash::ParentAccessDialog::Result::Status result) { + switch (result) { case ash::ParentAccessDialog::Result::Status::kApproved: - return "Approved"; + return WebApprovalsManager::LocalApprovalResult::kApproved; case ash::ParentAccessDialog::Result::Status::kDeclined: - return "Declined"; + return WebApprovalsManager::LocalApprovalResult::kDeclined; case ash::ParentAccessDialog::Result::Status::kCanceled: - return "Canceled"; + return WebApprovalsManager::LocalApprovalResult::kCanceled; case ash::ParentAccessDialog::Result::Status::kError: + return WebApprovalsManager::LocalApprovalResult::kError; + } +} +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + +std::string LocalApprovalResultToString( + WebApprovalsManager::LocalApprovalResult value) { + switch (value) { + case WebApprovalsManager::LocalApprovalResult::kApproved: + return "Approved"; + case WebApprovalsManager::LocalApprovalResult::kDeclined: + return "Rejected"; + case WebApprovalsManager::LocalApprovalResult::kCanceled: + return "Incomplete"; + case WebApprovalsManager::LocalApprovalResult::kError: return "Error"; } } -void RecordLocalApprovalResultMetricForChromeOSResult( - ash::ParentAccessDialog::Result::Status result) { - WebApprovalsManager::LocalApprovalResultMetric histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kError; - switch (result) { - case ash::ParentAccessDialog::Result::Status::kApproved: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kApproved; - break; - case ash::ParentAccessDialog::Result::Status::kDeclined: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kDeclined; - break; - case ash::ParentAccessDialog::Result::Status::kCanceled: - histogram_enum = - WebApprovalsManager::LocalApprovalResultMetric::kCanceled; - break; - case ash::ParentAccessDialog::Result::Status::kError: - histogram_enum = WebApprovalsManager::LocalApprovalResultMetric::kError; - break; - } - base::UmaHistogramEnumeration(kLocalWebApprovalResultHistogramName, - histogram_enum); -} -#endif - void RecordTimeToApprovalDurationMetric(base::TimeDelta durationMs) { base::UmaHistogramLongTimes(kLocalWebApprovalDurationHistogramName, durationMs); } +void RecordLocalWebApprovalResultMetric( + WebApprovalsManager::LocalApprovalResult result) { + base::UmaHistogramEnumeration(kLocalWebApprovalResultHistogramName, result); +} + } // namespace // static @@ -176,7 +151,7 @@ LOG(ERROR) << "Error showing ParentAccessDialog: " << static_cast<int>(result); base::UmaHistogramEnumeration(kLocalWebApprovalResultHistogramName, - LocalApprovalResultMetric::kError); + LocalApprovalResult::kError); std::move(callback).Run(false); return; } @@ -188,9 +163,10 @@ ->GetProfileKey()); WebsiteParentApproval::RequestLocalApproval( web_contents, NormalizeUrl(url), - base::BindOnce(&WebApprovalsManager::OnLocalApprovalRequestCompleted, - weak_ptr_factory_.GetWeakPtr(), settings_service, url, - base::TimeTicks::Now())); + base::BindOnce( + &WebApprovalsManager::OnLocalApprovalRequestCompletedAndroid, + weak_ptr_factory_.GetWeakPtr(), settings_service, url, + base::TimeTicks::Now())); std::move(callback).Run(true); #endif } @@ -264,26 +240,38 @@ index + 1); } -void WebApprovalsManager::OnLocalApprovalRequestCompleted( +void WebApprovalsManager::CompleteLocalApprovalRequest( + SupervisedUserSettingsService* settings_service, + const GURL& url, + base::TimeTicks start_time, + WebApprovalsManager::LocalApprovalResult approval_result) { + VLOG(0) << "Local URL approval final result: " + << LocalApprovalResultToString(approval_result); + + if (approval_result == LocalApprovalResult::kApproved) { + settings_service->RecordLocalWebsiteApproval(url.host()); + } + + RecordLocalWebApprovalResultMetric(approval_result); + + // Record duration metrics only for completed approval flows. + if (approval_result == LocalApprovalResult::kApproved || + approval_result == LocalApprovalResult::kDeclined) { + RecordTimeToApprovalDurationMetric(base::TimeTicks::Now() - start_time); + } +} + +#if BUILDFLAG(IS_ANDROID) +void WebApprovalsManager::OnLocalApprovalRequestCompletedAndroid( SupervisedUserSettingsService* settings_service, const GURL& url, base::TimeTicks start_time, AndroidLocalWebApprovalFlowOutcome request_outcome) { - VLOG(0) << "Local URL approval final result: " - << EnumLocalWebApprovalFlowOutcomeToString(request_outcome); - - // Record duration metrics only for completed approval flows. - if (request_outcome == AndroidLocalWebApprovalFlowOutcome::kApproved || - request_outcome == AndroidLocalWebApprovalFlowOutcome::kRejected) { - RecordTimeToApprovalDurationMetric(base::TimeTicks::Now() - start_time); - } - - RecordLocalApprovalResultMetricForAndroidOutcome(request_outcome); - - if (request_outcome == AndroidLocalWebApprovalFlowOutcome::kApproved) { - settings_service->RecordLocalWebsiteApproval(url.host()); - } + CompleteLocalApprovalRequest( + settings_service, url, start_time, + AndroidOutcomeToLocalApprovalResult(request_outcome)); } +#endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) void WebApprovalsManager::OnLocalApprovalRequestCompletedChromeOS( @@ -291,19 +279,8 @@ const GURL& url, base::TimeTicks start_time, std::unique_ptr<ash::ParentAccessDialog::Result> result) { - VLOG(0) << "Local URL approval final result: " - << ParentAccessResultToLoggingStringChromeOS(result->status); - - // Record duration metrics only for completed approval flows. - if (result->status == ash::ParentAccessDialog::Result::Status::kApproved || - result->status == ash::ParentAccessDialog::Result::Status::kDeclined) { - RecordTimeToApprovalDurationMetric(base::TimeTicks::Now() - start_time); - } - - RecordLocalApprovalResultMetricForChromeOSResult(result->status); - - if (result->status == ash::ParentAccessDialog::Result::Status::kApproved) { - settings_service->RecordLocalWebsiteApproval(url.host()); - } + CompleteLocalApprovalRequest( + settings_service, url, start_time, + ChromeOSResultToLocalApprovalResult(result->status)); } -#endif +#endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/supervised_user/web_approvals_manager.h b/chrome/browser/supervised_user/web_approvals_manager.h index ae2990b..37b2c58 100644 --- a/chrome/browser/supervised_user/web_approvals_manager.h +++ b/chrome/browser/supervised_user/web_approvals_manager.h
@@ -15,12 +15,17 @@ #include "base/gtest_prod_util.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "build/build_config.h" #include "ui/gfx/image/image_skia.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h" #endif +#if BUILDFLAG(IS_ANDROID) +enum class AndroidLocalWebApprovalFlowOutcome; +#endif // BUILDFLAG(IS_ANDROID) + class GURL; class PermissionRequestCreator; class SupervisedUserSettingsService; @@ -50,12 +55,12 @@ // successfully. using ApprovalRequestInitiatedCallback = base::OnceCallback<void(bool)>; - // The result of local web approval flow used for metrics. - // Those values are logged to UMA. Entries should not be renumbered and - // numeric values should never be reused. Please keep in sync with - // "FamilyLinkUserLocalWebApprovalResult" in + // The result of local web approval flow. + // Used for metrics. Those values are logged to UMA. Entries should not be + // renumbered and numeric values should never be reused. Please keep in sync + // with "FamilyLinkUserLocalWebApprovalResult" in // src/tools/metrics/histograms/enums.xml. - enum class LocalApprovalResultMetric { + enum class LocalApprovalResult { kApproved = 0, kDeclined = 1, kCanceled = 2, @@ -125,13 +130,25 @@ size_t index, bool success); - // Called to indicate that a URL access request has completed (either - // successfully or not). - void OnLocalApprovalRequestCompleted( + // Processes the outcome of the local approval request. + // Shared between the platforms. Should be called by platform specific + // completion callback. + void CompleteLocalApprovalRequest( + SupervisedUserSettingsService* settings_service, + const GURL& url, + base::TimeTicks start_time, + LocalApprovalResult approval_result); + + // Platform specific callbacks used to indicate approval request completion. + // Can implement platform specific operations needed to handle the result. + // Should call `CompleteLocalApprovalRequest` to complete the request. +#if BUILDFLAG(IS_ANDROID) + void OnLocalApprovalRequestCompletedAndroid( SupervisedUserSettingsService* settings_service, const GURL& url, base::TimeTicks start_time, AndroidLocalWebApprovalFlowOutcome request_outcome); +#endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) void OnLocalApprovalRequestCompletedChromeOS( @@ -139,7 +156,7 @@ const GURL& url, base::TimeTicks start_time, std::unique_ptr<ash::ParentAccessDialog::Result> result); -#endif +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // Helpers for private method testing. FRIEND_TEST_ALL_PREFIXES(WebApprovalsManagerTest,
diff --git a/chrome/browser/supervised_user/web_approvals_manager_unittest.cc b/chrome/browser/supervised_user/web_approvals_manager_unittest.cc index 5d2b53d..52b2e63f 100644 --- a/chrome/browser/supervised_user/web_approvals_manager_unittest.cc +++ b/chrome/browser/supervised_user/web_approvals_manager_unittest.cc
@@ -20,9 +20,13 @@ #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +#if BUILDFLAG(IS_ANDROID) +#include "chrome/browser/supervised_user/android/website_parent_approval.h" +#endif // BUILDFLAG(IS_ANDROID) + #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h" -#endif +#endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { @@ -210,6 +214,7 @@ } } +#if BUILDFLAG(IS_ANDROID) TEST_F(WebApprovalsManagerTest, LocalWebApprovalDurationHistogramTest) { base::HistogramTester histogram_tester; @@ -223,13 +228,13 @@ // Check that duration metric is recorded. base::TimeDelta elapsed_time = base::Minutes(1); task_environment().FastForwardBy(elapsed_time); - web_approvals_manager().OnLocalApprovalRequestCompleted( + web_approvals_manager().OnLocalApprovalRequestCompletedAndroid( &supervisedUserSettingsServiceMock, url, start_time, AndroidLocalWebApprovalFlowOutcome::kRejected); histogram_tester.ExpectBucketCount( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kDeclined, 1); + WebApprovalsManager::LocalApprovalResult::kDeclined, 1); histogram_tester.ExpectTotalCount( WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 1); histogram_tester.ExpectTimeBucketCount( @@ -238,12 +243,12 @@ // Receive a request canceled by the parent. // Check that no duration metric is recorded for incomplete requests. - web_approvals_manager().OnLocalApprovalRequestCompleted( + web_approvals_manager().OnLocalApprovalRequestCompletedAndroid( &supervisedUserSettingsServiceMock, url, start_time, AndroidLocalWebApprovalFlowOutcome::kIncomplete); histogram_tester.ExpectBucketCount( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kCanceled, 1); + WebApprovalsManager::LocalApprovalResult::kCanceled, 1); histogram_tester.ExpectTotalCount( WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 1); @@ -256,12 +261,12 @@ elapsed_time = elapsed_time + fast_forward_by; // Elapsed time since the start time. task_environment().FastForwardBy(fast_forward_by); - web_approvals_manager().OnLocalApprovalRequestCompleted( + web_approvals_manager().OnLocalApprovalRequestCompletedAndroid( &supervisedUserSettingsServiceMock, url, start_time, AndroidLocalWebApprovalFlowOutcome::kApproved); histogram_tester.ExpectBucketCount( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kApproved, 1); + WebApprovalsManager::LocalApprovalResult::kApproved, 1); histogram_tester.ExpectTotalCount( WebApprovalsManager::GetLocalApprovalResultHistogram(), 3); @@ -271,6 +276,7 @@ WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), elapsed_time, 1); } +#endif // BUILDFLAG(IS_ANDROID) #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(WebApprovalsManagerTest, LocalWebApprovalApprovedChromeOSTest) { @@ -297,7 +303,7 @@ histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kApproved, 1); + WebApprovalsManager::LocalApprovalResult::kApproved, 1); histogram_tester.ExpectTotalCount( WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 1); histogram_tester.ExpectTimeBucketCount( @@ -330,7 +336,7 @@ histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kDeclined, 1); + WebApprovalsManager::LocalApprovalResult::kDeclined, 1); histogram_tester.ExpectTotalCount( WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 1); histogram_tester.ExpectTimeBucketCount( @@ -366,7 +372,7 @@ WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 0); histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kCanceled, 1); + WebApprovalsManager::LocalApprovalResult::kCanceled, 1); } TEST_F(WebApprovalsManagerTest, LocalWebApprovalErrorChromeOSTest) { @@ -397,6 +403,6 @@ WebApprovalsManager::GetLocalApprovalDurationMillisecondsHistogram(), 0); histogram_tester.ExpectUniqueSample( WebApprovalsManager::GetLocalApprovalResultHistogram(), - WebApprovalsManager::LocalApprovalResultMetric::kError, 1); + WebApprovalsManager::LocalApprovalResult::kError, 1); } #endif
diff --git a/chrome/browser/tab_group/java/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupModelFilter.java b/chrome/browser/tab_group/java/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupModelFilter.java index b029316..8f232be 100644 --- a/chrome/browser/tab_group/java/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupModelFilter.java +++ b/chrome/browser/tab_group/java/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupModelFilter.java
@@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -615,12 +616,7 @@ return Collections.unmodifiableList(tabs); } - @Override - protected void addTab(Tab tab) { - if (tab.isIncognito() != isIncognito()) { - throw new IllegalStateException("Attempting to open tab in the wrong model"); - } - + private int getParentId(Tab tab) { if (isTabModelRestored() && !mIsResetting && (mGroupAutoCreation || (tab.getLaunchType() == TabLaunchType.FROM_TAB_GROUP_UI @@ -632,9 +628,22 @@ Tab parentTab = TabModelUtils.getTabById( getTabModel(), CriticalPersistedTabData.from(tab).getParentId()); if (parentTab != null) { - setRootId(tab, getRootId(parentTab)); + return getRootId(parentTab); } } + return Tab.INVALID_TAB_ID; + } + + @Override + protected void addTab(Tab tab) { + if (tab.isIncognito() != isIncognito()) { + throw new IllegalStateException("Attempting to open tab in the wrong model"); + } + + int parentId = getParentId(tab); + if (parentId != Tab.INVALID_TAB_ID) { + setRootId(tab, parentId); + } int groupId = getRootId(tab); if (mGroupIdToGroupMap.containsKey(groupId)) { @@ -804,6 +813,114 @@ } @Override + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public void markTabStateInitialized() { + super.markTabStateInitialized(); + boolean correctOrder = isOrderValid(); + RecordHistogram.recordBooleanHistogram("Tabs.Tasks.OrderValidOnStartup", correctOrder); + } + + /** + * Checks whether the order of the tabs in the {@link TabModel} respects the invariant of + * {@link TabGroupModelFilter} that tabs within a group must be contiguous. + * + * Valid order: + * Tab 1, Group A + * Tab 2, Group A + * Tab 3, Group B + * + * Invalid order: + * Tab 1, Group A + * Tab 2, Group B + * Tab 3, Group A + */ + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public boolean isOrderValid() { + HashSet<Integer> processedRootIds = new HashSet<>(); + int lastRootId = Tab.INVALID_TAB_ID; + // Iterate over tab model and check that all tabs with the same rootId are next to one + // another. If at any time a rootId is repeated without the prior tab having the same rootId + // then the invariant is violated. + for (int i = 0; i < getTabModel().getCount(); i++) { + int rootId = getRootId(getTabModel().getTabAt(i)); + if (rootId == lastRootId) continue; + + if (processedRootIds.contains(rootId)) return false; + + processedRootIds.add(lastRootId); + lastRootId = rootId; + } + return true; + } + + @Override + public int getValidPosition(Tab tab, int proposedPosition) { + final int parentId = getParentId(tab); + final int rootId = parentId == Tab.INVALID_TAB_ID ? getRootId(tab) : parentId; + int newPosition = proposedPosition; + // If the tab is not in the model and won't be part of a group ensure it is positioned + // outside any other groups. + if (rootId == Tab.INVALID_TAB_ID || !mGroupIdToGroupMap.containsKey(rootId)) { + newPosition = getValidPositionOfUngroupedTab(proposedPosition); + } else { + // The tab is or will be part of a group. Ensure it will be positioned with other + // members of its group. + TabGroup group = mGroupIdToGroupMap.get(rootId); + newPosition = getValidPositionOfGroupedTab(group, proposedPosition); + } + RecordHistogram.recordBooleanHistogram( + "Tabs.Tasks.TabAddedWithValidProposedPosition", newPosition == proposedPosition); + return newPosition; + } + + /** + * Gets a valid position of a tab that will be part of a group. If proposedPosition is within + * the range of the group's location it is used. Otherwise the tab is placed at the end of the + * group. + * @param group The group the tab belongs with. + * @param proposedPosition The requested position of the tab. + */ + private int getValidPositionOfGroupedTab(TabGroup group, int proposedPosition) { + List<Integer> ids = new ArrayList<>(); + ids.addAll(group.getTabIdList()); + assert ids.size() >= 1; + + int firstGroupIndex = TabModelUtils.getTabIndexById(getTabModel(), ids.get(0)); + int defaultDestinationIndex = firstGroupIndex + ids.size(); + if (proposedPosition < firstGroupIndex) { + return firstGroupIndex; + } + if (proposedPosition < defaultDestinationIndex) { + return proposedPosition; + } + return defaultDestinationIndex; + } + + /** + * Gets a valid position of a tab that is not part of a group. If proposedPosition is not inside + * any existing group it is used. Otherwise the tab is placed after the group it would have been + * placed inside of. + * @param proposedPosition The requested position of the tab. + */ + private int getValidPositionOfUngroupedTab(int proposedPosition) { + final int tabCount = getTabModel().getCount(); + if (proposedPosition <= 0 || proposedPosition >= tabCount) { + // Downstream should clamp this value appropriately. Adding at the ends will never be a + // problem. + return proposedPosition; + } + + int moveToIndex = proposedPosition; + // Find a spot where the tabs on either side of the new tab are not part of the same group. + while (moveToIndex != tabCount + && getRootId(getTabModel().getTabAt(moveToIndex - 1)) + == getRootId(getTabModel().getTabAt(moveToIndex))) { + moveToIndex++; + } + return moveToIndex; + } + + @Override public void didMoveTab(Tab tab, int newIndex, int curIndex) { // Ignore didMoveTab calls in tab restoring stage. if (!isTabModelRestored()) return;
diff --git a/chrome/browser/tab_group/javatests/DEPS b/chrome/browser/tab_group/javatests/DEPS new file mode 100644 index 0000000..990c5a0 --- /dev/null +++ b/chrome/browser/tab_group/javatests/DEPS
@@ -0,0 +1,9 @@ +include_rules = [ + "+base/test/android", + "+chrome/android", + "+chrome/browser/flags/android", + "+chrome/test/android", + "+content/public/android/java/src/org/chromium/content_public", + "+content/public/test/android", + "+ui/android", +]
diff --git a/chrome/browser/tab_group/javatests/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupsTest.java b/chrome/browser/tab_group/javatests/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupsTest.java new file mode 100644 index 0000000..a49b5de --- /dev/null +++ b/chrome/browser/tab_group/javatests/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupsTest.java
@@ -0,0 +1,254 @@ +// Copyright 2022 The Chromium Authors +// 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.tasks.tab_groups; + +import static org.junit.Assert.assertEquals; + +import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; + +import android.support.test.InstrumentationRegistry; + +import androidx.test.filters.SmallTest; + +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.test.util.Batch; +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.Restriction; +import org.chromium.chrome.browser.flags.ChromeFeatureList; +import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabLaunchType; +import org.chromium.chrome.browser.tabmodel.TabCreator; +import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.ChromeTabbedActivityTestRule; +import org.chromium.chrome.test.batch.BlankCTATabInitialStateRule; +import org.chromium.chrome.test.util.ChromeTabUtils; +import org.chromium.chrome.test.util.browser.Features.EnableFeatures; +import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.test.util.UiRestriction; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Integration tests for the Tab Groups feature on Android. + */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags. +Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeSwitches.DISABLE_STARTUP_PROMOS}) +@EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID}) +@Restriction({UiRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) +@Batch(Batch.PER_CLASS) +public class TabGroupsTest { + @ClassRule + public static ChromeTabbedActivityTestRule sActivityTestRule = + new ChromeTabbedActivityTestRule(); + + @Rule + public BlankCTATabInitialStateRule mBlankCTATabInitialStateRule = + new BlankCTATabInitialStateRule(sActivityTestRule, false); + + private TabModel mTabModel; + private TabGroupModelFilter mTabGroupModelFilter; + + @Before + public void setUp() { + mTabModel = sActivityTestRule.getActivity().getTabModelSelector().getModel(false); + mTabGroupModelFilter = (TabGroupModelFilter) sActivityTestRule.getActivity() + .getTabModelSelector() + .getTabModelFilterProvider() + .getTabModelFilter(false); + } + + private void prepareTabs(List<Integer> tabsPerGroup) { + for (int tabsToCreate : tabsPerGroup) { + List<Tab> tabs = new ArrayList<>(); + for (int i = 0; i < tabsToCreate; i++) { + Tab tab = ChromeTabUtils.fullyLoadUrlInNewTab( + InstrumentationRegistry.getInstrumentation(), + sActivityTestRule.getActivity(), "about:blank", /*incognito=*/false); + tabs.add(tab); + } + TestThreadUtils.runOnUiThreadBlocking(() -> { + mTabGroupModelFilter.mergeListOfTabsToGroup(tabs, tabs.get(0), false, false); + }); + } + } + + @Test + @SmallTest + public void testPreventAddingUngroupedTabInsideTabGroup() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab 1, 2, 3 + // Tab (tab added here) + // Tab 4 + Tab tab = addTabAt(/*index=*/3, /*parent=*/null); + tabs.add(4, tab); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(true); + } + + @Test + @SmallTest + public void testPreventAddingGroupedTabAwayFromGroup_BeforeGroup() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab (tab added here), 1, 2, 3 + // Tab 4 + Tab tab = addTabAt(/*index=*/0, /*parent=*/tabs.get(1)); + tabs.add(1, tab); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(true); + } + + @Test + @SmallTest + public void testPreventAddingGroupedTabAwayFromGroup_AfterGroup() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab 1, 2, 3, (tab added here) + // Tab 4 + Tab tab = addTabAt(/*index=*/mTabModel.getCount(), /*parent=*/tabs.get(1)); + tabs.add(4, tab); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(true); + } + + @Test + @SmallTest + public void testAllowAddingGroupedTabInsideGroup() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab 1, (tab added here), 2, 3 + // Tab 4 + Tab tab = addTabAt(/*index=*/2, /*parent=*/tabs.get(1)); + tabs.add(2, tab); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(true); + } + + @Test + @SmallTest + public void testOrderValid_WithIncorrectOrder() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab 1, 3 + // Tab 4 + // Move tab 2 here still grouped with tab 1 + Tab tab2 = tabs.get(2); + moveTab(tab2, 5); + tabs.remove(tab2); + tabs.add(tab2); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(false); + } + + @Test + @SmallTest + public void testOrderValid_WithIncorrectOrder_NestedGroup() { + prepareTabs(Arrays.asList(new Integer[] {3, 2, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 0 + // Tab 1, (group 4, 5), 2, 3 + // Tab 6 + Tab tab4 = tabs.get(4); + Tab tab5 = tabs.get(5); + moveTab(tab4, 2); + moveTab(tab5, 3); + tabs.remove(tab4); + tabs.remove(tab5); + tabs.add(2, tab4); + tabs.add(3, tab5); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(false); + } + + @Test + @SmallTest + public void testOrderValid_WithValidOrder() { + prepareTabs(Arrays.asList(new Integer[] {3, 1})); + List<Tab> tabs = getCurrentTabs(); + + // Tab 2, 3, 1 + // Tab 4 + // Move tab 0 here + Tab tab0 = tabs.get(0); + moveTab(tab0, 5); + tabs.remove(tab0); + tabs.add(tab0); + Tab tab1 = tabs.get(0); + moveTab(tab1, 3); + tabs.remove(tab1); + tabs.add(2, tab1); + assertEquals(tabs, getCurrentTabs()); + assertOrderValid(true); + } + + private void assertOrderValid(boolean expectedState) { + boolean isOrderValid = TestThreadUtils.runOnUiThreadBlockingNoException( + () -> { return mTabGroupModelFilter.isOrderValid(); }); + assertEquals(expectedState, isOrderValid); + } + + private void moveTab(Tab tab, int index) { + TestThreadUtils.runOnUiThreadBlocking(() -> { mTabModel.moveTab(tab.getId(), index); }); + } + + /** + * Create and add a tab at an explicit index. This bypasses {@link ChromeTabCreator} so that the + * index used can be directly specified. + */ + private Tab addTabAt(int index, Tab parent) { + Tab tab = TestThreadUtils.runOnUiThreadBlockingNoException(() -> { + @TabLaunchType + int type = + parent != null ? TabLaunchType.FROM_TAB_GROUP_UI : TabLaunchType.FROM_CHROME_UI; + TabCreator tabCreator = + sActivityTestRule.getActivity().getTabCreator(/*incognito=*/false); + return tabCreator.createNewTab(new LoadUrlParams("about:blank"), type, parent, index); + }); + return tab; + } + + private List<Tab> getCurrentTabs() { + List<Tab> tabs = new ArrayList<>(); + TestThreadUtils.runOnUiThreadBlocking(() -> { + for (int i = 0; i < mTabModel.getCount(); i++) { + tabs.add(mTabModel.getTabAt(i)); + } + }); + return tabs; + } + + private List<Integer> getCurrentTabIds() { + List<Integer> tabIds = new ArrayList<>(); + TestThreadUtils.runOnUiThreadBlocking(() -> { + for (int i = 0; i < mTabModel.getCount(); i++) { + tabIds.add(mTabModel.getTabAt(i).getId()); + } + }); + return tabIds; + } +}
diff --git a/chrome/browser/tab_group/javatests/tab_groups_test_java_sources.gni b/chrome/browser/tab_group/javatests/tab_groups_test_java_sources.gni new file mode 100644 index 0000000..d7476ec --- /dev/null +++ b/chrome/browser/tab_group/javatests/tab_groups_test_java_sources.gni
@@ -0,0 +1,5 @@ +# Copyright 2022 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +tab_groups_test_java_sources = [ "//chrome/browser/tab_group/javatests/src/org/chromium/chrome/browser/tasks/tab_groups/TabGroupsTest.java" ]
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelFilter.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelFilter.java index 547cf0f..7dc09be 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelFilter.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelFilter.java
@@ -17,6 +17,11 @@ // TabModelFilter implementation. @Override + public int getValidPosition(Tab tab, int proposedPosition) { + return proposedPosition; + } + + @Override protected void addTab(Tab tab) {} @Override
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabCreator.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabCreator.java index d20e5ad..71e6f2a 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabCreator.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabCreator.java
@@ -41,6 +41,18 @@ LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent); /** + * Creates a new tab and posts to UI. + * @param loadUrlParams parameters of the url load. + * @param type Information about how the tab was launched. + * @param parent the parent tab, if present. + * @param position the requested position (index in the tab model) + * @return The new tab or null if no tab was created. + */ + @Nullable + public abstract Tab createNewTab( + LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent, int position); + + /** * On restore, allows us to create a frozen version of a tab using saved tab state we read * from disk. * @param state The tab state that the tab can be restored from.
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilter.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilter.java index 53b57e4..2327fa3 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilter.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilter.java
@@ -153,6 +153,15 @@ } /** + * Returns a valid position to add or move a tab to this model in the context of any related + * tabs. + * @param tab The tab to be added/moved. + * @param proposedPosition The current or proposed position of the tab in the model. + * @return a valid position close to proposedPosition that respects related tab ordering rules. + */ + public abstract int getValidPosition(Tab tab, int proposedPosition); + + /** * Concrete class requires to define what's the behavior when {@link TabModel} added a * {@link Tab}. * @param tab {@link Tab} had added to {@link TabModel}.
diff --git a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelOrderControllerImpl.java b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelOrderControllerImpl.java index 5c7c69ad..8d90c1b 100644 --- a/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelOrderControllerImpl.java +++ b/chrome/browser/tabmodel/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelOrderControllerImpl.java
@@ -40,6 +40,13 @@ forgetAllOpeners(); } + // TODO(crbug/1383067): This is a bandaid fix to ensure tab groups are contiguous such that + // no tabs within a group are separate from one another and that no tab that is not part of + // a group can be added in-between members of a group. This doesn't address the issue of + // moving tabs to be between members of a group, however when a group is moved it is moved + // tab-by-tab so it is difficult to enforce anything there without significant refactoring. + position = getValidPositionConsideringRelatedTabs(newTab, position); + return position; } @@ -107,6 +114,12 @@ return NO_TAB; } + private int getValidPositionConsideringRelatedTabs(Tab newTab, int position) { + TabModelFilter filter = mTabModelSelector.getTabModelFilterProvider().getTabModelFilter( + newTab.isIncognito()); + return filter.getValidPosition(newTab, position); + } + /** * Clear the opener attribute on all tabs in the model. */
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index fbb37a48..806e59b91 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -57,10 +57,10 @@ "autofill/payments/autofill_progress_dialog_controller_impl.cc", "autofill/payments/autofill_progress_dialog_controller_impl.h", "autofill/payments/autofill_progress_dialog_view.h", + "autofill/payments/card_unmask_authentication_selection_dialog.h", "autofill/payments/card_unmask_authentication_selection_dialog_controller.h", "autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc", "autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h", - "autofill/payments/card_unmask_authentication_selection_dialog_view.h", "autofill/payments/card_unmask_otp_input_dialog_controller.h", "autofill/payments/card_unmask_otp_input_dialog_controller_impl.cc", "autofill/payments/card_unmask_otp_input_dialog_controller_impl.h", @@ -782,8 +782,6 @@ "android/infobars/autofill_virtual_card_enrollment_infobar.h", "android/infobars/duplicate_download_infobar.cc", "android/infobars/duplicate_download_infobar.h", - "android/infobars/generated_password_saved_infobar.cc", - "android/infobars/generated_password_saved_infobar.h", "android/infobars/infobar_container_android.cc", "android/infobars/infobar_container_android.h", "android/infobars/near_oom_infobar.cc", @@ -794,15 +792,11 @@ "android/infobars/permission_infobar.h", "android/infobars/reader_mode_infobar.cc", "android/infobars/reader_mode_infobar.h", - "android/infobars/save_password_infobar.cc", - "android/infobars/save_password_infobar.h", "android/infobars/simple_confirm_infobar_builder.cc", "android/infobars/survey_infobar.cc", "android/infobars/survey_infobar.h", "android/infobars/translate_compact_infobar.cc", "android/infobars/translate_compact_infobar.h", - "android/infobars/update_password_infobar.cc", - "android/infobars/update_password_infobar.h", "android/login_handler_android.cc", "android/logo/logo_bridge.cc", "android/logo/logo_bridge.h", @@ -1466,6 +1460,8 @@ "user_education/user_education_service.h", "user_education/user_education_service_factory.cc", "user_education/user_education_service_factory.h", + "user_notes/user_notes_controller.cc", + "user_notes/user_notes_controller.h", "views/eye_dropper/eye_dropper.cc", "views/eye_dropper/eye_dropper.h", "views/eye_dropper/eye_dropper_view.cc", @@ -2188,8 +2184,6 @@ "app_list/search/ranking/score_normalizing_ranker.h", "app_list/search/ranking/scoring.cc", "app_list/search/ranking/scoring.h", - "app_list/search/types.cc", - "app_list/search/types.h", "app_list/search/ranking/util.cc", "app_list/search/ranking/util.h", "app_list/search/search_controller.h", @@ -2203,6 +2197,8 @@ "app_list/search/search_metrics_manager.h", "app_list/search/search_provider.cc", "app_list/search/search_provider.h", + "app_list/search/types.cc", + "app_list/search/types.h", "app_list/search/util/ftrl_optimizer.cc", "app_list/search/util/ftrl_optimizer.h", "app_list/search/util/mrfu_cache.cc", @@ -3779,6 +3775,8 @@ "cocoa/javascript_app_modal_dialog_cocoa.mm", "cocoa/key_equivalent_constants.h", "cocoa/key_equivalent_constants.mm", + "cocoa/keystone_infobar_delegate.h", + "cocoa/keystone_infobar_delegate.mm", "cocoa/l10n_util.h", "cocoa/l10n_util.mm", "cocoa/last_active_browser_cocoa.cc", @@ -3865,13 +3863,6 @@ "window_sizer/window_sizer_mac.mm", ] - if (enable_updater) { - sources += [ - "cocoa/keystone_infobar_delegate.h", - "cocoa/keystone_infobar_delegate.mm", - ] - } - allow_circular_includes_from += [ "//chrome/browser/apps/app_shim" ] deps += [ @@ -4275,8 +4266,8 @@ "views/autofill/payments/autofill_error_dialog_view_native_views.h", "views/autofill/payments/autofill_progress_dialog_views.cc", "views/autofill/payments/autofill_progress_dialog_views.h", - "views/autofill/payments/card_unmask_authentication_selection_dialog_views.cc", - "views/autofill/payments/card_unmask_authentication_selection_dialog_views.h", + "views/autofill/payments/card_unmask_authentication_selection_dialog_view.cc", + "views/autofill/payments/card_unmask_authentication_selection_dialog_view.h", "views/autofill/payments/card_unmask_otp_input_dialog_views.cc", "views/autofill/payments/card_unmask_otp_input_dialog_views.h", "views/autofill/payments/card_unmask_prompt_views.cc",
diff --git a/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.cc b/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.cc index 8ec5a56..508506b 100644 --- a/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.cc +++ b/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.cc
@@ -36,8 +36,8 @@ ~AuthenticatorSelectionDialogViewAndroid() = default; // static -CardUnmaskAuthenticationSelectionDialogView* -CardUnmaskAuthenticationSelectionDialogView::CreateAndShow( +CardUnmaskAuthenticationSelectionDialog* +CardUnmaskAuthenticationSelectionDialog::CreateAndShow( CardUnmaskAuthenticationSelectionDialogController* controller, content::WebContents* web_contents) { ui::ViewAndroid* view_android = web_contents->GetNativeView();
diff --git a/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.h b/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.h index fd5fe75c..c9c0376 100644 --- a/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.h +++ b/chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.h
@@ -11,19 +11,19 @@ #include "base/android/scoped_java_ref.h" #include "base/memory/raw_ptr.h" -#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h" +#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h" #include "ui/android/window_android.h" namespace autofill { class CardUnmaskAuthenticationSelectionDialogController; struct CardUnmaskChallengeOption; -// Android implementation of the CardUnmaskAuthenticationSelectionDialogView. +// Android implementation of the CardUnmaskAuthenticationSelectionDialog. // `CardUnmaskAuthenticationSelectionDialogControllerImpl` holds a pointer to // this View. The View is expected to call "delete this" on itself upon // dismissal. class AuthenticatorSelectionDialogViewAndroid - : public CardUnmaskAuthenticationSelectionDialogView { + : public CardUnmaskAuthenticationSelectionDialog { public: explicit AuthenticatorSelectionDialogViewAndroid( CardUnmaskAuthenticationSelectionDialogController* controller); @@ -34,7 +34,7 @@ AuthenticatorSelectionDialogViewAndroid& operator=( const AuthenticatorSelectionDialogViewAndroid&) = delete; - // CardUnmaskAuthenticationSelectionDialogView. + // CardUnmaskAuthenticationSelectionDialog. void Dismiss(bool user_closed_dialog, bool server_success) override; void UpdateContent() override;
diff --git a/chrome/browser/ui/android/infobars/generated_password_saved_infobar.cc b/chrome/browser/ui/android/infobars/generated_password_saved_infobar.cc deleted file mode 100644 index 75d2810..0000000 --- a/chrome/browser/ui/android/infobars/generated_password_saved_infobar.cc +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/android/infobars/generated_password_saved_infobar.h" - -#include <memory> -#include <utility> - -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "chrome/android/chrome_jni_headers/GeneratedPasswordSavedInfoBarDelegate_jni.h" -#include "components/infobars/content/content_infobar_manager.h" -#include "content/public/browser/web_contents.h" - -using base::android::JavaParamRef; - -// static -void GeneratedPasswordSavedInfoBarDelegateAndroid::Create( - content::WebContents* web_contents) { - infobars::ContentInfoBarManager::FromWebContents(web_contents) - ->AddInfoBar( - std::make_unique<GeneratedPasswordSavedInfoBar>(base::WrapUnique( - new GeneratedPasswordSavedInfoBarDelegateAndroid()))); -} - -GeneratedPasswordSavedInfoBar::GeneratedPasswordSavedInfoBar( - std::unique_ptr<GeneratedPasswordSavedInfoBarDelegateAndroid> delegate) - : infobars::InfoBarAndroid(std::move(delegate)) {} - -GeneratedPasswordSavedInfoBar::~GeneratedPasswordSavedInfoBar() { -} - -base::android::ScopedJavaLocalRef<jobject> -GeneratedPasswordSavedInfoBar::CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) { - GeneratedPasswordSavedInfoBarDelegateAndroid* infobar_delegate = - static_cast<GeneratedPasswordSavedInfoBarDelegateAndroid*>(delegate()); - - return Java_GeneratedPasswordSavedInfoBarDelegate_show( - env, resource_id_mapper.Run(delegate()->GetIconId()), - base::android::ConvertUTF16ToJavaString(env, - infobar_delegate->message_text()), - base::android::ConvertUTF16ToJavaString( - env, infobar_delegate->details_message_text()), - infobar_delegate->inline_link_range().start(), - infobar_delegate->inline_link_range().end(), - base::android::ConvertUTF16ToJavaString( - env, infobar_delegate->button_label())); -} - -void GeneratedPasswordSavedInfoBar::OnLinkClicked( - JNIEnv* env, - const JavaParamRef<jobject>& obj) { - if (!owner()) - return; - - static_cast<GeneratedPasswordSavedInfoBarDelegateAndroid*>(delegate()) - ->OnInlineLinkClicked(); - RemoveSelf(); -} - -void GeneratedPasswordSavedInfoBar::ProcessButton(int action) { - if (!owner()) - return; - - RemoveSelf(); -}
diff --git a/chrome/browser/ui/android/infobars/generated_password_saved_infobar.h b/chrome/browser/ui/android/infobars/generated_password_saved_infobar.h deleted file mode 100644 index 1194587..0000000 --- a/chrome/browser/ui/android/infobars/generated_password_saved_infobar.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_ANDROID_INFOBARS_GENERATED_PASSWORD_SAVED_INFOBAR_H_ -#define CHROME_BROWSER_UI_ANDROID_INFOBARS_GENERATED_PASSWORD_SAVED_INFOBAR_H_ - -#include <jni.h> - -#include "base/android/scoped_java_ref.h" -#include "chrome/browser/password_manager/android/generated_password_saved_infobar_delegate_android.h" -#include "components/infobars/android/infobar_android.h" - -// The Android infobar that notifies that the generated password was saved. -class GeneratedPasswordSavedInfoBar : public infobars::InfoBarAndroid { - public: - explicit GeneratedPasswordSavedInfoBar( - std::unique_ptr<GeneratedPasswordSavedInfoBarDelegateAndroid> delegate); - - GeneratedPasswordSavedInfoBar(const GeneratedPasswordSavedInfoBar&) = delete; - GeneratedPasswordSavedInfoBar& operator=( - const GeneratedPasswordSavedInfoBar&) = delete; - - ~GeneratedPasswordSavedInfoBar() override; - - private: - // infobars::InfoBarAndroid implementation: - base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) override; - void OnLinkClicked(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) override; - void ProcessButton(int action) override; -}; - -#endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_GENERATED_PASSWORD_SAVED_INFOBAR_H_
diff --git a/chrome/browser/ui/android/infobars/save_password_infobar.cc b/chrome/browser/ui/android/infobars/save_password_infobar.cc deleted file mode 100644 index e6619af4..0000000 --- a/chrome/browser/ui/android/infobars/save_password_infobar.cc +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/android/infobars/save_password_infobar.h" - -#include <vector> - -#include "base/android/jni_android.h" -#include "base/android/jni_array.h" -#include "base/android/jni_string.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/android/chrome_jni_headers/SavePasswordInfoBar_jni.h" -#include "chrome/browser/password_manager/android/save_password_infobar_delegate_android.h" -#include "components/password_manager/core/common/credential_manager_types.h" - -using base::android::JavaParamRef; - -SavePasswordInfoBar::SavePasswordInfoBar( - std::unique_ptr<SavePasswordInfoBarDelegate> delegate, - const AccountInfo& account_info) - : infobars::ConfirmInfoBar(std::move(delegate)), - account_info_(account_info) {} - -SavePasswordInfoBar::~SavePasswordInfoBar() = default; - -base::android::ScopedJavaLocalRef<jobject> -SavePasswordInfoBar::CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) { - using base::android::ConvertUTF16ToJavaString; - using base::android::ScopedJavaLocalRef; - SavePasswordInfoBarDelegate* save_password_delegate = - static_cast<SavePasswordInfoBarDelegate*>(delegate()); - ScopedJavaLocalRef<jstring> ok_button_text = ConvertUTF16ToJavaString( - env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_OK)); - ScopedJavaLocalRef<jstring> cancel_button_text = - base::android::ConvertUTF16ToJavaString( - env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_CANCEL)); - ScopedJavaLocalRef<jstring> message_text = - ConvertUTF16ToJavaString(env, save_password_delegate->GetMessageText()); - ScopedJavaLocalRef<jstring> details_message_text = ConvertUTF16ToJavaString( - env, save_password_delegate->GetDetailsMessageText()); - ScopedJavaLocalRef<jobject> account_info = - !account_info_.IsEmpty() ? ConvertToJavaAccountInfo(env, account_info_) - : nullptr; - - base::android::ScopedJavaLocalRef<jobject> infobar; - infobar.Reset(Java_SavePasswordInfoBar_show( - env, resource_id_mapper.Run(delegate()->GetIconId()), message_text, - details_message_text, ok_button_text, cancel_button_text, account_info)); - - java_infobar_.Reset(env, infobar.obj()); - return infobar; -} - -void SavePasswordInfoBar::OnLinkClicked(JNIEnv* env, - const JavaParamRef<jobject>& obj) { - delegate()->LinkClicked(WindowOpenDisposition::NEW_FOREGROUND_TAB); -}
diff --git a/chrome/browser/ui/android/infobars/save_password_infobar.h b/chrome/browser/ui/android/infobars/save_password_infobar.h deleted file mode 100644 index dde0546..0000000 --- a/chrome/browser/ui/android/infobars/save_password_infobar.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_ANDROID_INFOBARS_SAVE_PASSWORD_INFOBAR_H_ -#define CHROME_BROWSER_UI_ANDROID_INFOBARS_SAVE_PASSWORD_INFOBAR_H_ - -#include "base/android/scoped_java_ref.h" -#include "chrome/browser/profiles/profile.h" -#include "components/infobars/android/confirm_infobar.h" -#include "components/signin/public/identity_manager/account_info.h" - -class SavePasswordInfoBarDelegate; - -// The infobar to be used with SavePasswordInfoBarDelegate. -class SavePasswordInfoBar : public infobars::ConfirmInfoBar { - public: - explicit SavePasswordInfoBar( - std::unique_ptr<SavePasswordInfoBarDelegate> delegate, - const AccountInfo& account_info); - - SavePasswordInfoBar(const SavePasswordInfoBar&) = delete; - SavePasswordInfoBar& operator=(const SavePasswordInfoBar&) = delete; - - ~SavePasswordInfoBar() override; - - private: - // ConfirmInfoBar: - base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) override; - void OnLinkClicked(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) override; - - base::android::ScopedJavaGlobalRef<jobject> java_infobar_; - - AccountInfo account_info_; -}; - -#endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_SAVE_PASSWORD_INFOBAR_H_
diff --git a/chrome/browser/ui/android/infobars/update_password_infobar.cc b/chrome/browser/ui/android/infobars/update_password_infobar.cc deleted file mode 100644 index 18c1185..0000000 --- a/chrome/browser/ui/android/infobars/update_password_infobar.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/android/infobars/update_password_infobar.h" - -#include <vector> - -#include "base/android/jni_android.h" -#include "base/android/jni_array.h" -#include "base/android/jni_string.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/android/chrome_jni_headers/UpdatePasswordInfoBar_jni.h" -#include "chrome/browser/password_manager/android/update_password_infobar_delegate_android.h" -#include "chrome/browser/ui/passwords/ui_utils.h" -#include "components/password_manager/core/common/credential_manager_types.h" -#include "ui/base/l10n/l10n_util.h" - -using base::android::JavaParamRef; - -UpdatePasswordInfoBar::UpdatePasswordInfoBar( - std::unique_ptr<UpdatePasswordInfoBarDelegate> delegate, - const AccountInfo& account_info) - : infobars::ConfirmInfoBar(std::move(delegate)), - account_info_(account_info) {} - -UpdatePasswordInfoBar::~UpdatePasswordInfoBar() {} - -int UpdatePasswordInfoBar::GetIdOfSelectedUsername() const { - return Java_UpdatePasswordInfoBar_getSelectedUsername( - base::android::AttachCurrentThread(), java_infobar_); -} - -base::android::ScopedJavaLocalRef<jobject> -UpdatePasswordInfoBar::CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) { - using base::android::ConvertUTF16ToJavaString; - using base::android::ScopedJavaLocalRef; - UpdatePasswordInfoBarDelegate* update_password_delegate = - static_cast<UpdatePasswordInfoBarDelegate*>(delegate()); - ScopedJavaLocalRef<jstring> ok_button_text = ConvertUTF16ToJavaString( - env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_OK)); - ScopedJavaLocalRef<jstring> message_text = - ConvertUTF16ToJavaString(env, update_password_delegate->GetMessageText()); - ScopedJavaLocalRef<jstring> details_message_text = ConvertUTF16ToJavaString( - env, update_password_delegate->GetDetailsMessageText()); - ScopedJavaLocalRef<jobject> account_info = - !account_info_.IsEmpty() ? ConvertToJavaAccountInfo(env, account_info_) - : nullptr; - std::vector<std::u16string> usernames; - unsigned int selected_username = - update_password_delegate->GetDisplayUsernames(&usernames); - ScopedJavaLocalRef<jobjectArray> display_usernames = - base::android::ToJavaArrayOfStrings(env, usernames); - - base::android::ScopedJavaLocalRef<jobject> infobar; - infobar.Reset(Java_UpdatePasswordInfoBar_show( - env, resource_id_mapper.Run(delegate()->GetIconId()), display_usernames, - selected_username, message_text, details_message_text, ok_button_text, - account_info)); - - java_infobar_.Reset(env, infobar.obj()); - return infobar; -} - -void UpdatePasswordInfoBar::OnLinkClicked(JNIEnv* env, - const JavaParamRef<jobject>& obj) { - delegate()->LinkClicked(WindowOpenDisposition::NEW_FOREGROUND_TAB); -}
diff --git a/chrome/browser/ui/android/infobars/update_password_infobar.h b/chrome/browser/ui/android/infobars/update_password_infobar.h deleted file mode 100644 index fa12a12..0000000 --- a/chrome/browser/ui/android/infobars/update_password_infobar.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2016 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_ANDROID_INFOBARS_UPDATE_PASSWORD_INFOBAR_H_ -#define CHROME_BROWSER_UI_ANDROID_INFOBARS_UPDATE_PASSWORD_INFOBAR_H_ - -#include "base/android/scoped_java_ref.h" -#include "components/infobars/android/confirm_infobar.h" -#include "components/signin/public/identity_manager/account_info.h" - -class UpdatePasswordInfoBarDelegate; - -// The infobar to be used with UpdatePasswordInfoBarDelegate. -class UpdatePasswordInfoBar : public infobars::ConfirmInfoBar { - public: - UpdatePasswordInfoBar(std::unique_ptr<UpdatePasswordInfoBarDelegate> delegate, - const AccountInfo& account_info); - - UpdatePasswordInfoBar(const UpdatePasswordInfoBar&) = delete; - UpdatePasswordInfoBar& operator=(const UpdatePasswordInfoBar&) = delete; - - ~UpdatePasswordInfoBar() override; - - int GetIdOfSelectedUsername() const; - - private: - // ConfirmInfoBar: - base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar( - JNIEnv* env, - const ResourceIdMapper& resource_id_mapper) override; - void OnLinkClicked(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) override; - - base::android::ScopedJavaGlobalRef<jobject> java_infobar_; - - AccountInfo account_info_; -}; - -#endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_UPDATE_PASSWORD_INFOBAR_H_
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl.cc b/chrome/browser/ui/app_list/search/search_controller_impl.cc index df70ee1..ab036ac 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl.cc +++ b/chrome/browser/ui/app_list/search/search_controller_impl.cc
@@ -11,8 +11,6 @@ #include "ash/public/cpp/app_list/app_list_metrics.h" #include "ash/public/cpp/app_list/app_list_types.h" #include "ash/public/cpp/tablet_mode.h" -#include "base/bind.h" -#include "base/containers/cxx20_erase.h" #include "base/metrics/metrics_hashes.h" #include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" @@ -68,7 +66,7 @@ model_updater_(model_updater), list_controller_(list_controller) {} -SearchControllerImpl::~SearchControllerImpl() {} +SearchControllerImpl::~SearchControllerImpl() = default; void SearchControllerImpl::StartSearch(const std::u16string& query) { DCHECK(!query.empty());
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl.h b/chrome/browser/ui/app_list/search/search_controller_impl.h index 72ea67a..c17f49d7 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl.h +++ b/chrome/browser/ui/app_list/search/search_controller_impl.h
@@ -12,7 +12,6 @@ #include <utility> #include <vector> -#include "base/callback.h" #include "base/callback_list.h" #include "base/observer_list.h" #include "base/time/time.h" @@ -21,7 +20,6 @@ #include "chrome/browser/ui/app_list/search/ranking/launch_data.h" #include "chrome/browser/ui/app_list/search/ranking/ranker_manager.h" #include "chrome/browser/ui/app_list/search/search_controller.h" -#include "third_party/abseil-cpp/absl/types/optional.h" class AppListControllerDelegate; class AppListModelUpdater;
diff --git a/chrome/browser/ui/app_list/search/search_controller_impl_unittest.cc b/chrome/browser/ui/app_list/search/search_controller_impl_unittest.cc index 98798aae..ee60cec 100644 --- a/chrome/browser/ui/app_list/search/search_controller_impl_unittest.cc +++ b/chrome/browser/ui/app_list/search/search_controller_impl_unittest.cc
@@ -11,14 +11,15 @@ #include "base/test/bind.h" #include "base/time/time.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" +#include "chrome/browser/ui/app_list/search/ranking/launch_data.h" #include "chrome/browser/ui/app_list/search/ranking/ranker_manager.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/app_list/search/search_provider.h" #include "chrome/browser/ui/app_list/search/test/search_controller_test_util.h" #include "chrome/browser/ui/app_list/search/test/test_ranker_manager.h" -#include "chrome/browser/ui/app_list/search/test/test_result.h" #include "chrome/browser/ui/app_list/search/test/test_search_provider.h" #include "chrome/browser/ui/app_list/test/fake_app_list_model_updater.h" +#include "chrome/browser/ui/app_list/test/test_app_list_controller_delegate.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" @@ -33,6 +34,32 @@ using DisplayType = ash::SearchResultDisplayType; using Result = ash::AppListSearchResultType; +LaunchData CreateFakeLaunchData(const std::string& id) { + app_list::LaunchData launch; + launch.id = id; + launch.result_type = ash::AppListSearchResultType::kPlayStoreApp; + launch.score = 0.0; + + return launch; +} + +class FakeObserver : public SearchController::Observer { + public: + FakeObserver() = default; + ~FakeObserver() override = default; + + void OnResultsAdded( + const std::u16string& query, + const std::vector<const ChromeSearchResult*>& results) override { + results_added_ = true; + } + + bool results_added() const { return results_added_; } + + private: + bool results_added_ = false; +}; + } // namespace class SearchControllerImplTest : public testing::Test { @@ -45,7 +72,8 @@ void SetUp() override { search_controller_ = std::make_unique<SearchControllerImpl>( - /*model_updater=*/&model_updater_, /*list_controller=*/nullptr, + /*model_updater=*/&model_updater_, + /*list_controller=*/&list_controller_, /*notifier=*/nullptr, &profile_); auto ranker_manager = std::make_unique<TestRankerManager>(&profile_); @@ -76,8 +104,8 @@ for (const auto& category : actual_categories_list) { if (category.burnin_iteration != -1) { - actual_categories_to_burnin_iteration.push_back( - {category.category, category.burnin_iteration}); + actual_categories_to_burnin_iteration.emplace_back( + category.category, category.burnin_iteration); } } @@ -104,8 +132,10 @@ void Wait() { task_environment_.RunUntilIdle(); } - void ElapseBurnInPeriod() { - task_environment_.FastForwardBy(base::Seconds(1)); + // Add a wait period in milliseconds to allow results collected from search + // providers. The default period is 1000 milliseconds (i.e., 1 second). + void WaitInMilliseconds(int n = 1000) { + task_environment_.FastForwardBy(base::Milliseconds(n)); } protected: @@ -113,6 +143,7 @@ TestingProfile profile_; FakeAppListModelUpdater model_updater_{&profile_, /*order_delegate=*/nullptr}; std::unique_ptr<SearchControllerImpl> search_controller_; + test::TestAppListControllerDelegate list_controller_{}; // Owned by |search_controller_|. TestRankerManager* ranker_manager_{nullptr}; }; @@ -133,7 +164,7 @@ // unimportant for the test. search_controller_->SetResults(SimpleProvider(Result::kOmnibox), std::move(results_1)); - ElapseBurnInPeriod(); + WaitInMilliseconds(); // Expect that: // - best matches are ordered first, // - best matches are ordered by best match rank, @@ -181,7 +212,7 @@ ExpectIdsToBurnInIterations({{"a", 0}, {"b", 0}}); // Simulate a provider returning results after the burn-in period. - ElapseBurnInPeriod(); + WaitInMilliseconds(); search_controller_->SetResults(SimpleProvider(Result::kOmnibox), std::move(web_results_first_arrival)); ExpectIdsToBurnInIterations({{"a", 0}, {"b", 0}, {"c", 1}, {"d", 1}}); @@ -231,7 +262,7 @@ {{Category::kFiles, 0}, {Category::kApps, 0}}); // Simulate a third provider returning results after the burn-in period. - ElapseBurnInPeriod(); + WaitInMilliseconds(); search_controller_->SetResults(SimpleProvider(Result::kOmnibox), std::move(web_results_first_arrival)); ExpectCategoriesToBurnInIterations( @@ -273,7 +304,7 @@ std::move(app_results)); search_controller_->SetResults(SimpleProvider(Result::kFileSearch), std::move(file_results)); - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"a", "b", "c", "d", "e"}); } @@ -293,7 +324,7 @@ // Simulate starting a search. search_controller_->StartSearch(u"abc"); // Simulate several providers returning results post-burn-in. - ElapseBurnInPeriod(); + WaitInMilliseconds(); search_controller_->SetResults(SimpleProvider(Result::kOmnibox), std::move(web_results)); ExpectIdOrder({"a", "b", "c"}); @@ -328,7 +359,7 @@ ExpectIdOrder({}); // Expect results to appear after burn-in period has elapsed. - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"b", "c", "d"}); // Simulate several providers returning results after the burn-in period. @@ -373,7 +404,7 @@ // Expect results to appear after burn-in period has elapsed. Expect the // Search and Assistant category to appear at the bottom. - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"d", "b", "c", "a"}); // Simulate a provider returning results after the burn-in period. Expect the @@ -414,7 +445,7 @@ ExpectIdOrder({}); // Expect results to appear after burn-in period has elapsed. - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"a", "b", "c"}); // When a single provider returns multiple times for a category, sorting by @@ -457,7 +488,7 @@ ExpectIdOrder({}); // Expect results to appear after burn-in period has elapsed. - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"a", "b", "c"}); // When there are multiple providers returning for a category, sorting by @@ -487,7 +518,7 @@ ExpectIdOrder({}); // Provider has returned and the A result should be published. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"AAA"}); provider_ptr->SetNextResults({}); @@ -502,7 +533,7 @@ ExpectIdOrder({}); // Provider has returned and the B result should be published. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"BBB"}); } @@ -531,14 +562,14 @@ // Fast-forward time so zero state provider returns results, and zero state // timeout fires. - task_environment_.FastForwardBy(base::Milliseconds(50)); + WaitInMilliseconds(50); // The burn-in period has not elapsed, so no results should have been // published. ExpectIdOrder({}); // Expect results to appear after burn-in period has elapsed. - ElapseBurnInPeriod(); + WaitInMilliseconds(); ExpectIdOrder({"zero", "a", "b", "c"}); } @@ -589,23 +620,23 @@ base::Seconds(3)); // The fast provider has returned but shouldn't have published. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({}); // Verify results are not published if a non-zero state provider (provider_c) // returns results. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({}); // Fast forward time enough for the zero state callback to run. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"a", "b", "c"}); // At this point, provider "d" finished, but the results are not published // because d provider supplies non-zero state results, and zero state search // is in progress - in practice, non-zero state providers should not start // during zero state search, but test provider runs either way. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"a", "b", "c"}); // The latecomer should still be added when it arrives - note that the list @@ -613,7 +644,7 @@ // published. // Note that results "c" and "d" are trailing due to their later burn-in // iteration. - task_environment_.FastForwardBy(base::Seconds(2)); + WaitInMilliseconds(2000); ExpectIdOrder({"e", "f", "a", "b", "c", "d"}); } @@ -638,15 +669,15 @@ base::Seconds(2)); // The fast provider has returned but shouldn't have published. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({}); // The timeout finished, the fast provider's result should be published. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"a"}); // The slow provider should still publish when it returns. - task_environment_.FastForwardBy(base::Seconds(1)); + WaitInMilliseconds(); ExpectIdOrder({"a", "b"}); } @@ -676,4 +707,99 @@ ExpectIdOrder({"drive_a", "drive_b", "local_a", "local_b"}); } +TEST_F(SearchControllerImplTest, FindSearchResultByIdAndOpenIt) { + auto results_1 = MakeListResults( + {"a", "b", "c", "d"}, + {Category::kWeb, Category::kGames, Category::kApps, Category::kWeb}, + {0, -1, 1, -1}, {0.4, 0.7, 0.2, 0.8}); + + search_controller_->StartSearch(u"abc"); + search_controller_->SetResults(SimpleProvider(Result::kOmnibox), + std::move(results_1)); + WaitInMilliseconds(); + + // Return nullptr if result cannot be found. + ChromeSearchResult* result = search_controller_->FindSearchResult("e"); + EXPECT_EQ(result, nullptr); + + // Return the result with the target id. + result = search_controller_->FindSearchResult("b"); + EXPECT_EQ(result->id(), "b"); + EXPECT_EQ(result->category(), Category::kGames); + + search_controller_->OpenResult(result, ui::EF_NONE); + + // We expect that |DismissView()| in |list_controller_| to be called. + EXPECT_TRUE(list_controller_.did_dismiss_view()); +} + +TEST_F(SearchControllerImplTest, InvokeResult) { + auto results_1 = MakeListResults( + {"a", "b", "c", "d"}, + {Category::kWeb, Category::kGames, Category::kApps, Category::kWeb}, + {0, -1, 1, -1}, {0.4, 0.7, 0.2, 0.8}); + + search_controller_->StartSearch(u"abc"); + search_controller_->SetResults(SimpleProvider(Result::kOmnibox), + std::move(results_1)); + WaitInMilliseconds(); + ExpectIdOrder({"a", "c", "d", "b"}); + + // Return the result with the target id. + ChromeSearchResult* result = search_controller_->FindSearchResult("b"); + EXPECT_EQ(result->id(), "b"); + EXPECT_EQ(result->category(), Category::kGames); + + // The results should not change if the invoke action is |kAppend|. + search_controller_->InvokeResultAction(result, + ash::SearchResultActionType::kAppend); + WaitInMilliseconds(); + ExpectIdOrder({"a", "c", "d", "b"}); + + // The result should be removed if the invoke action is |kRemove|. + search_controller_->InvokeResultAction(result, + ash::SearchResultActionType::kRemove); + WaitInMilliseconds(); + ExpectIdOrder({"a", "c", "d"}); +} + +TEST_F(SearchControllerImplTest, Train) { + auto results_1 = MakeListResults( + {"a", "b", "c", "d"}, + {Category::kWeb, Category::kGames, Category::kApps, Category::kWeb}, + {0, -1, 1, -1}, {0.4, 0.7, 0.2, 0.8}); + + search_controller_->StartSearch(u"abc"); + search_controller_->SetResults(SimpleProvider(Result::kOmnibox), + std::move(results_1)); + WaitInMilliseconds(); + + search_controller_->Train(CreateFakeLaunchData("e")); + // We expect that |Train()| in |ranker_manager_| to be called. + EXPECT_TRUE(ranker_manager_->did_train()); +} + +TEST_F(SearchControllerImplTest, NotifyObserverWhenPublished) { + // Create two fake observers. + FakeObserver observer1; + FakeObserver observer2; + + search_controller_->Publish(); + WaitInMilliseconds(); + // Do not observe if the observers are not added. + EXPECT_FALSE(observer1.results_added()); + EXPECT_FALSE(observer2.results_added()); + + // Add two observers and remove observer2. + search_controller_->AddObserver(&observer1); + search_controller_->AddObserver(&observer2); + search_controller_->RemoveObserver(&observer2); + + search_controller_->Publish(); + WaitInMilliseconds(); + // We expect observer1 to observe while observer2 is not. + EXPECT_TRUE(observer1.results_added()); + EXPECT_FALSE(observer2.results_added()); +} + } // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/test/test_ranker_manager.cc b/chrome/browser/ui/app_list/search/test/test_ranker_manager.cc index a5e71f8..407b6aa8 100644 --- a/chrome/browser/ui/app_list/search/test/test_ranker_manager.cc +++ b/chrome/browser/ui/app_list/search/test/test_ranker_manager.cc
@@ -40,4 +40,8 @@ } } +void TestRankerManager::Train(const LaunchData& launch) { + did_train_ = true; +} + } // namespace app_list
diff --git a/chrome/browser/ui/app_list/search/test/test_ranker_manager.h b/chrome/browser/ui/app_list/search/test/test_ranker_manager.h index bbcb110a..1bfeff7 100644 --- a/chrome/browser/ui/app_list/search/test/test_ranker_manager.h +++ b/chrome/browser/ui/app_list/search/test/test_ranker_manager.h
@@ -40,11 +40,15 @@ void Start(const std::u16string& query, ResultsMap& results, CategoriesList& categories) override {} - void Train(const LaunchData& launch) override {} + void Train(const LaunchData& launch) override; void Remove(ChromeSearchResult* result) override {} + // Return true if |Train()| has been called. Otherwise, return false; + bool did_train() const { return did_train_; } + private: base::flat_map<Category, double> category_ranks_; + bool did_train_ = false; }; } // namespace app_list
diff --git a/chrome/browser/ui/ash/device_scheduled_reboot/scheduled_reboot_dialog.cc b/chrome/browser/ui/ash/device_scheduled_reboot/scheduled_reboot_dialog.cc index 0161fea1..27dc97e4e 100644 --- a/chrome/browser/ui/ash/device_scheduled_reboot/scheduled_reboot_dialog.cc +++ b/chrome/browser/ui/ash/device_scheduled_reboot/scheduled_reboot_dialog.cc
@@ -43,8 +43,10 @@ ui::DialogModel::Builder(std::make_unique<ui::DialogModelDelegate>()) .SetTitle(BuildTitle()) .AddOkButton(base::OnceClosure()) - .AddCancelButton(std::move(reboot_callback), - l10n_util::GetStringUTF16(IDS_POLICY_REBOOT_BUTTON)) + .AddCancelButton( + std::move(reboot_callback), + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_POLICY_REBOOT_BUTTON))) .AddParagraph( ui::DialogModelLabel( l10n_util::GetStringFUTF16(
diff --git a/chrome/browser/ui/ash/keyboard_shortcut_viewer_metadata_unittest.cc b/chrome/browser/ui/ash/keyboard_shortcut_viewer_metadata_unittest.cc index 6b80bcb..918d0bf 100644 --- a/chrome/browser/ui/ash/keyboard_shortcut_viewer_metadata_unittest.cc +++ b/chrome/browser/ui/ash/keyboard_shortcut_viewer_metadata_unittest.cc
@@ -44,11 +44,6 @@ return value ? "true" : "false"; } -bool ShouldDesksKeyboardShortcutsBeEnabled() { - return ::features::IsImprovedKeyboardShortcutsEnabled() && - ash::features::IsImprovedDesksKeyboardShortcutsEnabled(); -} - std::string ModifiersToString(int modifiers) { return base::StringPrintf("shift=%s control=%s alt=%s search=%s", BooleanToString(modifiers & ui::EF_SHIFT_DOWN), @@ -142,7 +137,7 @@ ash_accelerator_ids_.insert({accel_data.keycode, accel_data.modifiers}); } - if (ShouldDesksKeyboardShortcutsBeEnabled()) { + if (::features::IsImprovedKeyboardShortcutsEnabled()) { for (size_t i = 0; i < ash::kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorDataLength; @@ -258,7 +253,7 @@ for (const auto& accel_mapping : GetAcceleratorList()) chrome_accelerators.emplace_back(accel_mapping); - if (ShouldDesksKeyboardShortcutsBeEnabled()) { + if (::features::IsImprovedKeyboardShortcutsEnabled()) { for (size_t i = 0; i < ash::kEnabledWithImprovedDesksKeyboardShortcutsAcceleratorDataLength;
diff --git a/chrome/browser/ui/ash/shelf/app_shortcut_shelf_item_controller.cc b/chrome/browser/ui/ash/shelf/app_shortcut_shelf_item_controller.cc index db03cd7..cb3bd5f 100644 --- a/chrome/browser/ui/ash/shelf/app_shortcut_shelf_item_controller.cc +++ b/chrome/browser/ui/ash/shelf/app_shortcut_shelf_item_controller.cc
@@ -35,6 +35,7 @@ #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" +#include "components/app_constants/constants.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/app_window/native_app_window.h" @@ -148,6 +149,8 @@ : WebContentMatchesWebApp(web_contents, browser); } + bool IsAshBrowser() const { return app_id_ == app_constants::kChromeAppId; } + private: bool WebContentMatchesHostedApp(content::WebContents* web_contents, Browser* browser) const { @@ -458,8 +461,10 @@ TabStripModel* tab_strip = browser->tab_strip_model(); for (int index = 0; index < tab_strip->count(); index++) { content::WebContents* web_contents = tab_strip->GetWebContentsAt(index); - if (matcher.WebContentMatchesApp(web_contents, browser)) + if (matcher.IsAshBrowser() || + matcher.WebContentMatchesApp(web_contents, browser)) { items.push_back(web_contents); + } } } return items;
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h similarity index 78% rename from chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h rename to chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h index 6a6a4c51..0759d751b 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ -#define CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ +#ifndef CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_H_ +#define CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_H_ namespace content { class WebContents; @@ -13,15 +13,13 @@ class CardUnmaskAuthenticationSelectionDialogController; -// TODO(crbug.com/1382856): Rename CardUnmaskAuthenticationSelectionDialogView -// to CardUnmaskAuthenticationSelectionDialog -// Interface that exposes the view to +// Interface that exposes the dialog to // CardUnmaskAuthenticationSelectionDialogControllerImpl. -class CardUnmaskAuthenticationSelectionDialogView { +class CardUnmaskAuthenticationSelectionDialog { public: // Creates a dialog and displays it as a modal on top of the web contents of // CardUnmaskAuthenticationSelectionDialogController. - static CardUnmaskAuthenticationSelectionDialogView* CreateAndShow( + static CardUnmaskAuthenticationSelectionDialog* CreateAndShow( CardUnmaskAuthenticationSelectionDialogController* controller, content::WebContents* web_contents); @@ -39,4 +37,4 @@ } // namespace autofill -#endif // CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ +#endif // CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_H_
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller.h b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller.h index c15a80d9..268ba61 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller.h +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller.h
@@ -17,7 +17,7 @@ struct CardUnmaskChallengeOption; // Interface that exposes controller functionality to -// CardUnmaskAuthenticationSelectionDialogView. +// CardUnmaskAuthenticationSelectionDialog. class CardUnmaskAuthenticationSelectionDialogController { public: CardUnmaskAuthenticationSelectionDialogController() = default;
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc index 3e5605e..0de6c7b78 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.cc
@@ -7,7 +7,7 @@ #include <string> #include "base/check_is_test.h" -#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h" +#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/payments/card_unmask_challenge_option.h" #include "components/autofill/core/common/autofill_payments_features.h" @@ -63,7 +63,7 @@ std::move(confirm_unmasking_method_callback); cancel_unmasking_closure_ = std::move(cancel_unmasking_closure); - dialog_view_ = CardUnmaskAuthenticationSelectionDialogView::CreateAndShow( + dialog_view_ = CardUnmaskAuthenticationSelectionDialog::CreateAndShow( this, &GetWebContents()); DCHECK(dialog_view_);
diff --git a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h index f227cdb..15904c8 100644 --- a/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h +++ b/chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller_impl.h
@@ -15,7 +15,7 @@ namespace autofill { -class CardUnmaskAuthenticationSelectionDialogView; +class CardUnmaskAuthenticationSelectionDialog; class CardUnmaskAuthenticationSelectionDialogControllerImpl : public CardUnmaskAuthenticationSelectionDialogController, @@ -62,7 +62,7 @@ void SetSelectedChallengeOptionId( const std::string& selected_challenge_option_id) override; - CardUnmaskAuthenticationSelectionDialogView* GetDialogViewForTesting() { + CardUnmaskAuthenticationSelectionDialog* GetDialogViewForTesting() { return dialog_view_; } @@ -91,7 +91,7 @@ // Contains all of the challenge options an issuer has for the user. std::vector<CardUnmaskChallengeOption> challenge_options_; - raw_ptr<CardUnmaskAuthenticationSelectionDialogView> dialog_view_ = nullptr; + raw_ptr<CardUnmaskAuthenticationSelectionDialog> dialog_view_ = nullptr; // Callback invoked when the user confirmed an authentication method to use. base::OnceCallback<void(const std::string&)>
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index ccfa84f..7cbabbcd 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -1285,14 +1285,6 @@ return window_->DoBrowserControlsShrinkRendererSize(contents); } -int Browser::GetVirtualKeyboardHeight(content::WebContents* contents) { - // This API is currently only used by View Transitions when the virtual - // keyboard resizes content. On desktop platforms, the virtual keyboard can - // only inset the visual viewport so it shouldn't ever be called. - NOTIMPLEMENTED(); - return 0; -} - void Browser::SetTopControlsGestureScrollInProgress(bool in_progress) { window_->SetTopControlsGestureScrollInProgress(in_progress); }
diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h index b50337f..201e468d 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h
@@ -660,7 +660,6 @@ int GetTopControlsHeight() override; bool DoBrowserControlsShrinkRendererSize( content::WebContents* contents) override; - int GetVirtualKeyboardHeight(content::WebContents* contents) override; void SetTopControlsGestureScrollInProgress(bool in_progress) override; bool CanOverscrollContent() override; bool ShouldPreserveAbortedURLs(content::WebContents* source) override;
diff --git a/chrome/browser/ui/dialogs/outdated_upgrade_bubble.cc b/chrome/browser/ui/dialogs/outdated_upgrade_bubble.cc index c28befc..8f5afec 100644 --- a/chrome/browser/ui/dialogs/outdated_upgrade_bubble.cc +++ b/chrome/browser/ui/dialogs/outdated_upgrade_bubble.cc
@@ -122,9 +122,10 @@ .AddOkButton( base::BindOnce(&OnDialogAccepted, browser, auto_update_enabled, kUpdateBrowserRedirectUrl), - l10n_util::GetStringUTF16(auto_update_enabled - ? IDS_REINSTALL_APP - : IDS_REENABLE_UPDATES)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(auto_update_enabled + ? IDS_REINSTALL_APP + : IDS_REENABLE_UPDATES))) .AddParagraph( ui::DialogModelLabel(IDS_UPGRADE_BUBBLE_TEXT).set_is_secondary()) .SetDialogDestroyingCallback(base::BindOnce(&OnWindowClosing))
diff --git a/chrome/browser/ui/intent_picker_tab_helper.cc b/chrome/browser/ui/intent_picker_tab_helper.cc index d2c22d7..152b1f74 100644 --- a/chrome/browser/ui/intent_picker_tab_helper.cc +++ b/chrome/browser/ui/intent_picker_tab_helper.cc
@@ -311,7 +311,10 @@ if (!web_contents()) { return; } + if (IsNavigatingToNewSite(navigation_handle)) { + ++commit_count_; + bool is_valid_page = navigation_handle->GetURL().SchemeIsHTTPOrHTTPS() && !navigation_handle->IsErrorPage(); if (is_valid_page) {
diff --git a/chrome/browser/ui/intent_picker_tab_helper.h b/chrome/browser/ui/intent_picker_tab_helper.h index b294de1..771fe85 100644 --- a/chrome/browser/ui/intent_picker_tab_helper.h +++ b/chrome/browser/ui/intent_picker_tab_helper.h
@@ -62,6 +62,8 @@ std::vector<apps::IntentPickerAppInfo> apps, IntentPickerIconLoaderCallback callback); + int commit_count() { return commit_count_; } + // Sets a OnceClosure callback which will be called next time the icon is // updated. If include_latest_navigation is true, and the latest navigation // was finished, the callback is called immediately. @@ -111,6 +113,10 @@ // on this origin. bool show_expanded_chip_from_usage_ = false; + // Tracks the number of commits on this page, to allow for checking to make + // sure that asynchronous invocations do not cause a stale intent picker. + int commit_count_ = 0; + // Contains the app ID of an app which can be opened through the intent // picker. This is only set when ShowIconForApps() is called with a single // app. Will be set to the empty string in all other cases (e.g. when there
diff --git a/chrome/browser/ui/startup/startup_browser_creator_impl.cc b/chrome/browser/ui/startup/startup_browser_creator_impl.cc index 6d143c95..8cae23d 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_impl.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_impl.cc
@@ -73,10 +73,8 @@ #if BUILDFLAG(IS_MAC) #include "base/mac/mac_util.h" -#if BUILDFLAG(ENABLE_UPDATER) #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h" #endif -#endif // BUILDFLAG(IS_MAC) #if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) #include "chrome/browser/win/conflicts/incompatible_applications_updater.h" @@ -206,7 +204,7 @@ web_app::MaybeInstallAppFromCommandLine(*command_line_, *profile); -#if BUILDFLAG(IS_MAC) && BUILDFLAG(ENABLE_UPDATER) +#if BUILDFLAG(IS_MAC) if (process_startup == chrome::startup::IsProcessStartup::kYes) { // Check whether the auto-update system needs to be promoted from user // to system.
diff --git a/chrome/browser/ui/tab_helpers.cc b/chrome/browser/ui/tab_helpers.cc index bbaac11c..76d68bd 100644 --- a/chrome/browser/ui/tab_helpers.cc +++ b/chrome/browser/ui/tab_helpers.cc
@@ -26,7 +26,6 @@ #include "chrome/browser/content_settings/page_specific_content_settings_delegate.h" #include "chrome/browser/content_settings/sound_content_setting_observer.h" #include "chrome/browser/dips/dips_bounce_detector.h" -#include "chrome/browser/dips/dips_helper.h" #include "chrome/browser/dips/dips_service.h" #include "chrome/browser/external_protocol/external_protocol_observer.h" #include "chrome/browser/favicon/favicon_utils.h" @@ -342,9 +341,6 @@ ConnectionHelpTabHelper::CreateForWebContents(web_contents); CoreTabHelper::CreateForWebContents(web_contents); DIPSWebContentsObserver::CreateForWebContents(web_contents); - if (DIPSService* dips_service = DIPSService::Get(profile)) { - DIPSTabHelper::CreateForWebContents(web_contents, dips_service); - } ExternalProtocolObserver::CreateForWebContents(web_contents); favicon::CreateContentFaviconDriverForWebContents(web_contents); FileSystemAccessPermissionRequestManager::CreateForWebContents(web_contents);
diff --git a/chrome/browser/ui/tabs/tab_group.cc b/chrome/browser/ui/tabs/tab_group.cc index 96ab5ef..c15e97a 100644 --- a/chrome/browser/ui/tabs/tab_group.cc +++ b/chrome/browser/ui/tabs/tab_group.cc
@@ -10,6 +10,7 @@ #include <utility> #include <vector> +#include "base/feature_list.h" #include "base/guid.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/ui/tab_ui_helper.h" @@ -17,6 +18,7 @@ #include "chrome/browser/ui/tabs/saved_tab_groups/saved_tab_group_service_factory.h" #include "chrome/browser/ui/tabs/tab_group_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/grit/generated_resources.h" #include "components/saved_tab_groups/saved_tab_group_model.h" #include "components/saved_tab_groups/saved_tab_group_tab.h" @@ -31,7 +33,13 @@ TabGroup::TabGroup(TabGroupController* controller, const tab_groups::TabGroupId& id, const tab_groups::TabGroupVisualData& visual_data) - : controller_(controller), id_(id) { + : controller_(controller), + saved_tab_group_model_([](Profile* profile) -> SavedTabGroupModel* { + SavedTabGroupKeyedService* const service = + SavedTabGroupServiceFactory::GetForProfile(profile); + return service ? service->model() : nullptr; + }(controller->GetProfile())), + id_(id) { visual_data_ = std::make_unique<tab_groups::TabGroupVisualData>(visual_data); } @@ -95,12 +103,7 @@ } bool TabGroup::IsSaved() const { - // TODO(dljames): Retrieving the service factory each time we want to check - // the saved status of a tab group is expensive computationally. Find a way to - // simplify this. - SavedTabGroupKeyedService* backend = - SavedTabGroupServiceFactory::GetForProfile(controller_->GetProfile()); - return backend && backend->model() && backend->model()->Contains(id()); + return saved_tab_group_model_ && saved_tab_group_model_->Contains(id()); } absl::optional<int> TabGroup::GetFirstTab() const {
diff --git a/chrome/browser/ui/tabs/tab_group.h b/chrome/browser/ui/tabs/tab_group.h index 4d55a47..f316d144 100644 --- a/chrome/browser/ui/tabs/tab_group.h +++ b/chrome/browser/ui/tabs/tab_group.h
@@ -19,6 +19,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/range/range.h" +class SavedTabGroupModel; class TabGroupController; // The metadata and state of a tab group. This handles state changes that are @@ -112,6 +113,10 @@ private: raw_ptr<TabGroupController> controller_; + // Used to check if `id_` is saved in the `SavedTabGroupModel`. + // `SavedTabGroupModel` is tied to the Profile and should outlive this. + const raw_ptr<SavedTabGroupModel> saved_tab_group_model_; + tab_groups::TabGroupId id_; std::unique_ptr<tab_groups::TabGroupVisualData> visual_data_;
diff --git a/chrome/browser/ui/tabs/tab_menu_model.cc b/chrome/browser/ui/tabs/tab_menu_model.cc index 3e59c6d..65cd303 100644 --- a/chrome/browser/ui/tabs/tab_menu_model.cc +++ b/chrome/browser/ui/tabs/tab_menu_model.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ui/tabs/tab_menu_model.h" #include "base/command_line.h" +#include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/metrics/user_metrics.h" #include "build/build_config.h" @@ -18,6 +19,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" #include "chrome/browser/ui/tabs/tab_utils.h" #include "chrome/browser/ui/ui_features.h" +#include "chrome/browser/ui/user_notes/user_notes_controller.h" #include "chrome/browser/ui/web_applications/web_app_tabbed_utils.h" #include "chrome/common/chrome_features.h" #include "chrome/grit/chromium_strings.h" @@ -143,6 +145,10 @@ IDS_TAB_CXMENU_UNFOLLOW_SITE); } } + if (UserNotesController::IsUserNotesSupported(tab_strip->profile())) { + AddItemWithStringId(TabStripModel::CommandAddNote, + IDS_CONTENT_CONTEXT_ADD_A_NOTE); + } if (send_tab_to_self::ShouldDisplayEntryPoint( tab_strip->GetWebContentsAt(index))) { AddSeparator(ui::NORMAL_SEPARATOR);
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index 13799904..57b2d98f 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -47,6 +47,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/browser/ui/tabs/tab_utils.h" +#include "chrome/browser/ui/user_notes/user_notes_controller.h" #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h" #include "chrome/browser/ui/web_applications/web_app_launch_utils.h" #include "chrome/common/url_constants.h" @@ -1297,6 +1298,11 @@ case CommandSendTabToSelf: return true; + case CommandAddNote: { + DCHECK(UserNotesController::IsUserNotesSupported(profile())); + return GetIndicesForCommand(context_index).size() == 1; + } + case CommandAddToReadLater: return true; @@ -1463,6 +1469,13 @@ break; } + case CommandAddNote: { + std::vector<int> indices = GetIndicesForCommand(context_index); + DCHECK(indices.size() == 1); + UserNotesController::SwitchTabsAndAddNote(this, indices.front()); + break; + } + case CommandAddToReadLater: { base::RecordAction( UserMetricsAction("DesktopReadingList.AddItem.FromTabContextMenu"));
diff --git a/chrome/browser/ui/tabs/tab_strip_model.h b/chrome/browser/ui/tabs/tab_strip_model.h index 6788ae30..7a302f3 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.h +++ b/chrome/browser/ui/tabs/tab_strip_model.h
@@ -499,6 +499,7 @@ CommandToggleGrouped, CommandToggleSiteMuted, CommandSendTabToSelf, + CommandAddNote, CommandAddToReadLater, CommandAddToNewGroup, CommandAddToExistingGroup,
diff --git a/chrome/browser/ui/user_notes/user_notes_controller.cc b/chrome/browser/ui/user_notes/user_notes_controller.cc new file mode 100644 index 0000000..04ac964c --- /dev/null +++ b/chrome/browser/ui/user_notes/user_notes_controller.cc
@@ -0,0 +1,35 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/user_notes/user_notes_controller.h" + +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/tabs/tab_strip_user_gesture_details.h" +#include "chrome/browser/ui/ui_features.h" +#include "components/user_notes/browser/user_note_manager.h" +#include "components/user_notes/user_notes_features.h" +#include "content/public/browser/web_contents.h" + +// static +bool UserNotesController::IsUserNotesSupported(Profile* profile) { + return user_notes::IsUserNotesEnabled() && + base::FeatureList::IsEnabled(features::kUnifiedSidePanel) && + !profile->IsGuestSession(); +} + +// static +void UserNotesController::SwitchTabsAndAddNote(TabStripModel* tab_strip, + int tab_index) { + auto* notes_manager = user_notes::UserNoteManager::GetForPage( + tab_strip->GetWebContentsAt(tab_index)->GetPrimaryPage()); + if (!notes_manager) + return; + tab_strip->ActivateTabAt( + tab_index, TabStripUserGestureDetails( + TabStripUserGestureDetails::GestureType::kOther)); + notes_manager->OnAddNoteRequested( + tab_strip->GetWebContentsAt(tab_index)->GetPrimaryMainFrame(), + /*has_selected_text=*/false); +}
diff --git a/chrome/browser/ui/user_notes/user_notes_controller.h b/chrome/browser/ui/user_notes/user_notes_controller.h new file mode 100644 index 0000000..3433b95 --- /dev/null +++ b/chrome/browser/ui/user_notes/user_notes_controller.h
@@ -0,0 +1,20 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_USER_NOTES_USER_NOTES_CONTROLLER_H_ +#define CHROME_BROWSER_UI_USER_NOTES_USER_NOTES_CONTROLLER_H_ + +class TabStripModel; +class Profile; + +class UserNotesController { + public: + // Returns true if the user notes feature is available for the given profile. + static bool IsUserNotesSupported(Profile* profile); + + // Switches to the tab, opens notes ui, and starts the note creation flow. + static void SwitchTabsAndAddNote(TabStripModel* tab_strip, int tab_index); +}; + +#endif // CHROME_BROWSER_UI_USER_NOTES_USER_NOTES_CONTROLLER_H_
diff --git a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc index 38cdfe7f..c4331ad 100644 --- a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_browsertest.cc
@@ -8,7 +8,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/test/test_browser_dialog.h" -#include "chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.h" +#include "chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" @@ -41,16 +41,16 @@ /*cancel_unmasking_closure=*/base::DoNothing()); } - CardUnmaskAuthenticationSelectionDialogViews* GetDialog() { + CardUnmaskAuthenticationSelectionDialogView* GetDialog() { if (!controller()) return nullptr; - CardUnmaskAuthenticationSelectionDialogView* dialog_view = + CardUnmaskAuthenticationSelectionDialog* dialog_view = controller()->GetDialogViewForTesting(); if (!dialog_view) return nullptr; - return static_cast<CardUnmaskAuthenticationSelectionDialogViews*>( + return static_cast<CardUnmaskAuthenticationSelectionDialogView*>( dialog_view); }
diff --git a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.cc b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.cc similarity index 86% rename from chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.cc rename to chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.cc index ffb815b..13d65778 100644 --- a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.cc +++ b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.h" +#include "chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.h" #include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_controller.h" #include "chrome/browser/ui/views/autofill/payments/payments_view_util.h" @@ -22,8 +22,8 @@ namespace autofill { -CardUnmaskAuthenticationSelectionDialogViews:: - CardUnmaskAuthenticationSelectionDialogViews( +CardUnmaskAuthenticationSelectionDialogView:: + CardUnmaskAuthenticationSelectionDialogView( CardUnmaskAuthenticationSelectionDialogController* controller) : controller_(controller) { SetShowTitle(true); @@ -39,8 +39,8 @@ InitViews(); } -CardUnmaskAuthenticationSelectionDialogViews:: - ~CardUnmaskAuthenticationSelectionDialogViews() { +CardUnmaskAuthenticationSelectionDialogView:: + ~CardUnmaskAuthenticationSelectionDialogView() { // Inform |controller_| of the dialog's destruction. By the time this is // called, the |controller_| will not be nullptr only if the dialog is closed // by the user. For other cases, the |controller_| should already be reset. @@ -52,17 +52,17 @@ } // static -CardUnmaskAuthenticationSelectionDialogView* -CardUnmaskAuthenticationSelectionDialogView::CreateAndShow( +CardUnmaskAuthenticationSelectionDialog* +CardUnmaskAuthenticationSelectionDialog::CreateAndShow( CardUnmaskAuthenticationSelectionDialogController* controller, content::WebContents* web_contents) { - CardUnmaskAuthenticationSelectionDialogViews* dialog_view = - new CardUnmaskAuthenticationSelectionDialogViews(controller); + CardUnmaskAuthenticationSelectionDialogView* dialog_view = + new CardUnmaskAuthenticationSelectionDialogView(controller); constrained_window::ShowWebModalDialogViews(dialog_view, web_contents); return dialog_view; } -void CardUnmaskAuthenticationSelectionDialogViews::Dismiss( +void CardUnmaskAuthenticationSelectionDialogView::Dismiss( bool user_closed_dialog, bool server_success) { if (controller_) { @@ -72,29 +72,29 @@ GetWidget()->Close(); } -void CardUnmaskAuthenticationSelectionDialogViews::UpdateContent() { +void CardUnmaskAuthenticationSelectionDialogView::UpdateContent() { ReplaceContentWithProgressThrobber(); SetButtonEnabled(ui::DIALOG_BUTTON_OK, false); } -bool CardUnmaskAuthenticationSelectionDialogViews::Accept() { +bool CardUnmaskAuthenticationSelectionDialogView::Accept() { DCHECK(!controller_->GetChallengeOptions().empty()); controller_->OnOkButtonClicked(); return false; } -std::u16string CardUnmaskAuthenticationSelectionDialogViews::GetWindowTitle() +std::u16string CardUnmaskAuthenticationSelectionDialogView::GetWindowTitle() const { return controller_->GetWindowTitle(); } -void CardUnmaskAuthenticationSelectionDialogViews::AddedToWidget() { +void CardUnmaskAuthenticationSelectionDialogView::AddedToWidget() { GetBubbleFrameView()->SetTitleView( std::make_unique<TitleWithIconAndSeparatorView>( GetWindowTitle(), TitleWithIconAndSeparatorView::Icon::GOOGLE_PAY)); } -void CardUnmaskAuthenticationSelectionDialogViews::InitViews() { +void CardUnmaskAuthenticationSelectionDialogView::InitViews() { DCHECK(children().empty()); // Sets the layout manager for the top level view. auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( @@ -110,7 +110,7 @@ AddFooterText(); } -void CardUnmaskAuthenticationSelectionDialogViews::AddHeaderText() { +void CardUnmaskAuthenticationSelectionDialogView::AddHeaderText() { auto* content = AddChildView(std::make_unique<views::Label>( controller_->GetContentHeaderText(), views::style::CONTEXT_DIALOG_BODY_TEXT, views::style::STYLE_SECONDARY)); @@ -118,7 +118,7 @@ content->SetHorizontalAlignment(gfx::ALIGN_LEFT); } -void CardUnmaskAuthenticationSelectionDialogViews::AddChallengeOptionsViews() { +void CardUnmaskAuthenticationSelectionDialogView::AddChallengeOptionsViews() { auto* challenge_options_section = AddChildView(std::make_unique<views::View>()); int horizontal_column_padding = @@ -188,7 +188,7 @@ } } -void CardUnmaskAuthenticationSelectionDialogViews::AddChallengeOptionDetails( +void CardUnmaskAuthenticationSelectionDialogView::AddChallengeOptionDetails( const CardUnmaskChallengeOption& challenge_option, views::View* challenge_options_section) { // Creates the right side of the challenge option (label and information @@ -210,7 +210,7 @@ views::style::STYLE_SECONDARY)); } -void CardUnmaskAuthenticationSelectionDialogViews::AddFooterText() { +void CardUnmaskAuthenticationSelectionDialogView::AddFooterText() { auto* content = AddChildView(std::make_unique<views::Label>( controller_->GetContentFooterText(), ChromeTextContext::CONTEXT_DIALOG_BODY_TEXT_SMALL, @@ -219,7 +219,7 @@ content->SetHorizontalAlignment(gfx::ALIGN_LEFT); } -void CardUnmaskAuthenticationSelectionDialogViews:: +void CardUnmaskAuthenticationSelectionDialogView:: ReplaceContentWithProgressThrobber() { RemoveAllChildViews(); AddChildView(std::make_unique<ProgressBarWithTextView>( @@ -227,7 +227,7 @@ } std::unique_ptr<views::RadioButton> -CardUnmaskAuthenticationSelectionDialogViews::CreateChallengeOptionRadioButton( +CardUnmaskAuthenticationSelectionDialogView::CreateChallengeOptionRadioButton( CardUnmaskChallengeOption challenge_option) { auto radio_button = std::make_unique<views::RadioButton>(); radio_button->SetCallback(
diff --git a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.h b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.h similarity index 73% rename from chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.h rename to chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.h index 7897df9..e0e2d6cd 100644 --- a/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_views.h +++ b/chrome/browser/ui/views/autofill/payments/card_unmask_authentication_selection_dialog_view.h
@@ -2,13 +2,13 @@ // 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_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEWS_H_ -#define CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEWS_H_ +#ifndef CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ #include <string> #include "base/memory/raw_ptr.h" -#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h" +#include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog.h" #include "components/autofill/core/browser/payments/card_unmask_challenge_option.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/button/radio_button.h" @@ -18,21 +18,19 @@ class CardUnmaskAuthenticationSelectionDialogController; -// TODO(crbug.com/1382856): Rename CardUnmaskAuthenticationSelectionDialogViews -// to CardUnmaskAuthenticationSelectionDialogView -class CardUnmaskAuthenticationSelectionDialogViews - : public CardUnmaskAuthenticationSelectionDialogView, +class CardUnmaskAuthenticationSelectionDialogView + : public CardUnmaskAuthenticationSelectionDialog, public views::BubbleDialogDelegateView { public: - explicit CardUnmaskAuthenticationSelectionDialogViews( + explicit CardUnmaskAuthenticationSelectionDialogView( CardUnmaskAuthenticationSelectionDialogController* controller); - CardUnmaskAuthenticationSelectionDialogViews( - const CardUnmaskAuthenticationSelectionDialogViews&) = delete; - CardUnmaskAuthenticationSelectionDialogViews& operator=( - const CardUnmaskAuthenticationSelectionDialogViews&) = delete; - ~CardUnmaskAuthenticationSelectionDialogViews() override; + CardUnmaskAuthenticationSelectionDialogView( + const CardUnmaskAuthenticationSelectionDialogView&) = delete; + CardUnmaskAuthenticationSelectionDialogView& operator=( + const CardUnmaskAuthenticationSelectionDialogView&) = delete; + ~CardUnmaskAuthenticationSelectionDialogView() override; - // CardUnmaskAuthenticationSelectionDialogView: + // CardUnmaskAuthenticationSelectionDialog: void Dismiss(bool user_closed_dialog, bool server_success) override; void UpdateContent() override; @@ -71,11 +69,11 @@ CardUnmaskChallengeOption challenge_option); // Controller that owns functionality of the - // CardUnmaskAuthenticationSelectionDialogView. + // CardUnmaskAuthenticationSelectionDialog. raw_ptr<CardUnmaskAuthenticationSelectionDialogController> controller_ = nullptr; }; } // namespace autofill -#endif // CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEWS_H_ +#endif // CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc index 8b3bb9a..9e653a8 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc
@@ -203,18 +203,21 @@ base::Unretained(bubble_delegate))) .AddOkButton(base::BindOnce(&BookmarkBubbleDelegate::ApplyEdits, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16(IDS_DONE)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_DONE))) .AddCancelButton( base::BindOnce(&BookmarkBubbleDelegate::RemoveBookmark, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_REMOVE_BOOKMARK), - ui::DialogModelButton::Params().AddAccelerator( - ui::Accelerator(ui::VKEY_R, ui::EF_ALT_DOWN))) - .AddExtraButton(base::BindRepeating(&BookmarkBubbleDelegate::OnEditButton, - base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_OPTIONS), - ui::DialogModelButton::Params().AddAccelerator( - ui::Accelerator(ui::VKEY_E, ui::EF_ALT_DOWN))) + ui::DialogModelButton::Params() + .SetLabel(l10n_util::GetStringUTF16( + IDS_BOOKMARK_BUBBLE_REMOVE_BOOKMARK)) + .AddAccelerator(ui::Accelerator(ui::VKEY_R, ui::EF_ALT_DOWN))) + .AddExtraButton( + base::BindRepeating(&BookmarkBubbleDelegate::OnEditButton, + base::Unretained(bubble_delegate)), + ui::DialogModelButton::Params() + .SetLabel(l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_OPTIONS)) + .AddAccelerator(ui::Accelerator(ui::VKEY_E, ui::EF_ALT_DOWN))) .AddTextfield( kBookmarkName, l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_NAME_LABEL),
diff --git a/chrome/browser/ui/views/extensions/extension_install_blocked_dialog_view.cc b/chrome/browser/ui/views/extensions/extension_install_blocked_dialog_view.cc index 4c2db66e..11d0e4f 100644 --- a/chrome/browser/ui/views/extensions/extension_install_blocked_dialog_view.cc +++ b/chrome/browser/ui/views/extensions/extension_install_blocked_dialog_view.cc
@@ -34,7 +34,8 @@ icon, skia::ImageOperations::ResizeMethod::RESIZE_BEST, gfx::Size(extension_misc::EXTENSION_ICON_SMALL, extension_misc::EXTENSION_ICON_SMALL)))) - .AddOkButton(base::DoNothing(), l10n_util::GetStringUTF16(IDS_CLOSE)) + .AddOkButton(base::DoNothing(), ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_CLOSE))) .SetDialogDestroyingCallback(std::move(done_callback)); if (!custom_error_message.empty()) {
diff --git a/chrome/browser/ui/views/extensions/extension_uninstall_dialog_view.cc b/chrome/browser/ui/views/extensions/extension_uninstall_dialog_view.cc index c4e16eb4..64047589 100644 --- a/chrome/browser/ui/views/extensions/extension_uninstall_dialog_view.cc +++ b/chrome/browser/ui/views/extensions/extension_uninstall_dialog_view.cc
@@ -84,7 +84,8 @@ .AddOkButton( base::BindOnce(&ExtensionUninstallDialogViews::DialogAccepted, weak_ptr_factory_.GetWeakPtr()), - l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON))) .AddCancelButton( base::OnceClosure() /* Cancel is covered by WindowClosingCallback */);
diff --git a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc index 9c1ec75bb..afbc647c 100644 --- a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc +++ b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc
@@ -56,14 +56,16 @@ base::BindOnce( &PrintJobConfirmationDialogDelegate::OnDialogAccepted, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_ALLOW)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_ALLOW))) .AddCancelButton( base::BindOnce( &PrintJobConfirmationDialogDelegate::OnDialogClosed, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_DENY)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_DENY))) .AddParagraph( ui::DialogModelLabel( l10n_util::GetStringFUTF16(
diff --git a/chrome/browser/ui/views/extensions/reload_page_dialog.cc b/chrome/browser/ui/views/extensions/reload_page_dialog.cc index e0563ce..42b3bc2 100644 --- a/chrome/browser/ui/views/extensions/reload_page_dialog.cc +++ b/chrome/browser/ui/views/extensions/reload_page_dialog.cc
@@ -52,9 +52,10 @@ } dialog_builder.SetTitle(GetTitle(actions)) - .AddOkButton(base::BindOnce(std::move(callback)), - l10n_util::GetStringUTF16( - IDS_EXTENSION_RELOAD_PAGE_BUBBLE_OK_BUTTON)); + .AddOkButton( + base::BindOnce(std::move(callback)), + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_EXTENSION_RELOAD_PAGE_BUBBLE_OK_BUTTON))); content::WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); @@ -72,9 +73,10 @@ dialog_builder .SetTitle( l10n_util::GetStringUTF16(IDS_EXTENSION_RELOAD_PAGE_BUBBLE_HEADING)) - .AddOkButton(base::BindOnce(std::move(callback)), - l10n_util::GetStringUTF16( - IDS_EXTENSION_RELOAD_PAGE_BUBBLE_OK_BUTTON)); + .AddOkButton( + base::BindOnce(std::move(callback)), + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_EXTENSION_RELOAD_PAGE_BUBBLE_OK_BUTTON))); } ShowDialog(container, extension_ids, dialog_builder.Build());
diff --git a/chrome/browser/ui/views/extensions/settings_overridden_dialog.cc b/chrome/browser/ui/views/extensions/settings_overridden_dialog.cc index b57b2ec..1ec216a 100644 --- a/chrome/browser/ui/views/extensions/settings_overridden_dialog.cc +++ b/chrome/browser/ui/views/extensions/settings_overridden_dialog.cc
@@ -82,13 +82,13 @@ .AddOkButton( base::BindOnce(&SettingsOverriddenDialogDelegate::OnDialogAccepted, base::Unretained(dialog_delegate)), - l10n_util::GetStringUTF16( - IDS_EXTENSION_SETTINGS_OVERRIDDEN_DIALOG_CHANGE_IT_BACK)) + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_EXTENSION_SETTINGS_OVERRIDDEN_DIALOG_CHANGE_IT_BACK))) .AddCancelButton( base::BindOnce(&SettingsOverriddenDialogDelegate::OnDialogCancelled, base::Unretained(dialog_delegate)), - l10n_util::GetStringUTF16( - IDS_EXTENSION_SETTINGS_OVERRIDDEN_DIALOG_KEEP_IT)) + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_EXTENSION_SETTINGS_OVERRIDDEN_DIALOG_KEEP_IT))) .SetCloseActionCallback( base::BindOnce(&SettingsOverriddenDialogDelegate::OnDialogClosed, base::Unretained(dialog_delegate)))
diff --git a/chrome/browser/ui/views/file_system_access/file_system_access_dangerous_file_dialog.cc b/chrome/browser/ui/views/file_system_access/file_system_access_dangerous_file_dialog.cc index 2018128..6ecf5130 100644 --- a/chrome/browser/ui/views/file_system_access/file_system_access_dangerous_file_dialog.cc +++ b/chrome/browser/ui/views/file_system_access/file_system_access_dangerous_file_dialog.cc
@@ -47,10 +47,12 @@ ui::DialogModelLabel::CreateEmphasizedText(origin_or_short_name))) .AddOkButton( std::move(accept_callback), - l10n_util::GetStringUTF16(IDS_FILE_SYSTEM_ACCESS_DANGEROUS_FILE_SAVE)) - .AddCancelButton(std::move(cancel_callbacks.first), - l10n_util::GetStringUTF16( - IDS_FILE_SYSTEM_ACCESS_DANGEROUS_FILE_DONT_SAVE)) + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_FILE_SYSTEM_ACCESS_DANGEROUS_FILE_SAVE))) + .AddCancelButton( + std::move(cancel_callbacks.first), + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + IDS_FILE_SYSTEM_ACCESS_DANGEROUS_FILE_DONT_SAVE))) .SetCloseActionCallback(std::move(cancel_callbacks.second)) .OverrideDefaultButton(ui::DialogButton::DIALOG_BUTTON_CANCEL); return dialog_builder.Build();
diff --git a/chrome/browser/ui/views/file_system_access/file_system_access_permission_dialog.cc b/chrome/browser/ui/views/file_system_access/file_system_access_permission_dialog.cc index f8b2e89..a6da7f6 100644 --- a/chrome/browser/ui/views/file_system_access/file_system_access_permission_dialog.cc +++ b/chrome/browser/ui/views/file_system_access/file_system_access_permission_dialog.cc
@@ -125,9 +125,9 @@ ui::DialogModelLabel::CreateEmphasizedText( file_system_access_ui_helper::GetPathForDisplay(request.path))})) .AddOkButton(std::move(accept_callback), - l10n_util::GetStringUTF16(GetButtonLabel(request))) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(GetButtonLabel(request)))) .AddCancelButton(std::move(cancel_callbacks.first), - /*label=*/std::u16string(), ui::DialogModelButton::Params().SetId(kCancelButtonId)) .SetCloseActionCallback(std::move(cancel_callbacks.second)) .SetInitiallyFocusedField(kCancelButtonId);
diff --git a/chrome/browser/ui/views/file_system_access/file_system_access_restricted_directory_dialog.cc b/chrome/browser/ui/views/file_system_access/file_system_access_restricted_directory_dialog.cc index c737bec..b32408b1 100644 --- a/chrome/browser/ui/views/file_system_access/file_system_access_restricted_directory_dialog.cc +++ b/chrome/browser/ui/views/file_system_access/file_system_access_restricted_directory_dialog.cc
@@ -48,11 +48,12 @@ ? IDS_FILE_SYSTEM_ACCESS_RESTRICTED_DIRECTORY_TEXT : IDS_FILE_SYSTEM_ACCESS_RESTRICTED_FILE_TEXT, ui::DialogModelLabel::CreateEmphasizedText(origin_or_short_name))) - .AddOkButton(std::move(accept_callback), - l10n_util::GetStringUTF16( - handle_type == HandleType::kDirectory - ? IDS_FILE_SYSTEM_ACCESS_RESTRICTED_DIRECTORY_BUTTON - : IDS_FILE_SYSTEM_ACCESS_RESTRICTED_FILE_BUTTON)) + .AddOkButton( + std::move(accept_callback), + ui::DialogModelButton::Params().SetLabel(l10n_util::GetStringUTF16( + handle_type == HandleType::kDirectory + ? IDS_FILE_SYSTEM_ACCESS_RESTRICTED_DIRECTORY_BUTTON + : IDS_FILE_SYSTEM_ACCESS_RESTRICTED_FILE_BUTTON))) .AddCancelButton(std::move(cancel_callbacks.first)) .SetCloseActionCallback(std::move(cancel_callbacks.second)); return dialog_builder.Build();
diff --git a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc index 29ca536..7336181 100644 --- a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc
@@ -319,6 +319,19 @@ BrowserNonClientFrameView::AddedToWidget(); } +void PictureInPictureBrowserFrameView::RemovedFromWidget() { + if (GetWidget()->IsClosed()) + return; + + widget_observation_.Reset(); + +#if !BUILDFLAG(IS_MAC) + GetWidget()->GetNativeWindow()->RemovePreTargetHandler(this); +#endif + + BrowserNonClientFrameView::RemovedFromWidget(); +} + #if BUILDFLAG(IS_LINUX) gfx::Insets PictureInPictureBrowserFrameView::MirroredFrameBorderInsets() const {
diff --git a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h index 57408db..637dda72 100644 --- a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h +++ b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h
@@ -70,6 +70,7 @@ void OnThemeChanged() override; void Layout() override; void AddedToWidget() override; + void RemovedFromWidget() override; #if BUILDFLAG(IS_LINUX) gfx::Insets MirroredFrameBorderInsets() const override; gfx::Insets GetInputInsets() const override;
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc index 35cafd9b..033a806 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest.cc
@@ -5,12 +5,14 @@ #include <string> #include "base/bind.h" +#include "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/apps/intent_helper/intent_picker_features.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/intent_picker_tab_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/toolbar_button_provider.h" @@ -41,14 +43,29 @@ scoped_feature_list_.InitWithFeatures({}, disabled_features); } - void OpenNewTab(const GURL& url) { + template <typename Action> + void DoAndWaitForIntentPickerIconUpdate(Action action) { + base::RunLoop run_loop; + auto* tab_helper = IntentPickerTabHelper::FromWebContents(GetWebContents()); + tab_helper->SetIconUpdateCallbackForTesting(run_loop.QuitClosure()); + action(); + run_loop.Run(); + } + + content::WebContents* OpenNewTab(const GURL& url) { chrome::NewTab(browser()); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - NavigateToLaunchingPage(browser()); - TestTabActionDoesNotOpenAppWindow( - url, base::BindOnce(&ClickLinkAndWait, web_contents, url, - LinkTarget::SELF, GetParam())); + + DoAndWaitForIntentPickerIconUpdate( + [this] { NavigateToLaunchingPage(browser()); }); + DoAndWaitForIntentPickerIconUpdate([this, url, web_contents] { + TestTabActionDoesNotOpenAppWindow( + url, base::BindOnce(&ClickLinkAndWait, web_contents, url, + LinkTarget::SELF, GetParam())); + }); + + return web_contents; } // Inserts an iframe in the main frame of |web_contents|. @@ -66,6 +83,10 @@ ->GetPageActionIconView(PageActionIconType::kIntentPicker); } + content::WebContents* GetWebContents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + IntentPickerBubbleView* intent_picker_bubble() { return IntentPickerBubbleView::intent_picker_bubble(); } @@ -91,7 +112,7 @@ // Tests that clicking a link from a tabbed browser to outside the scope of an // installed app does not show the intent picker. IN_PROC_BROWSER_TEST_P(IntentPickerBubbleViewBrowserTest, - NavigationToOutofScopeLinkDoesNotShowIntentPicker) { + NavigationToOutOfScopeLinkDoesNotShowIntentPicker) { InstallTestWebApp(); const GURL out_of_scope_url = @@ -99,9 +120,8 @@ NavigateToLaunchingPage(browser()); TestTabActionDoesNotOpenAppWindow( out_of_scope_url, - base::BindOnce(&ClickLinkAndWait, - browser()->tab_strip_model()->GetActiveWebContents(), - out_of_scope_url, LinkTarget::SELF, GetParam())); + base::BindOnce(&ClickLinkAndWait, GetWebContents(), out_of_scope_url, + LinkTarget::SELF, GetParam())); EXPECT_EQ(nullptr, intent_picker_bubble()); } @@ -116,23 +136,25 @@ const GURL in_scope_url = https_server().GetURL(GetAppUrlHost(), GetInScopeUrlPath()); - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); + auto* tab_helper = IntentPickerTabHelper::FromWebContents(GetWebContents()); NavigateToLaunchingPage(browser()); views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{}, "IntentPickerBubbleView"); + base::RunLoop run_loop; + tab_helper->SetIconUpdateCallbackForTesting(run_loop.QuitClosure()); TestTabActionDoesNotOpenAppWindow( - in_scope_url, base::BindOnce(&ClickLinkAndWait, web_contents, + in_scope_url, base::BindOnce(&ClickLinkAndWait, GetWebContents(), in_scope_url, LinkTarget::SELF, GetParam())); + run_loop.Run(); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); - EXPECT_TRUE(intent_picker_view->GetVisible()); + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); + EXPECT_TRUE(intent_picker_icon->GetVisible()); #if !BUILDFLAG(IS_CHROMEOS) - // On Chrome OS, the picker bubble will appear automatically. + // On ChromeOS, the picker bubble will appear automatically. EXPECT_FALSE(intent_picker_bubble()); - GetIntentPickerIcon()->ExecuteForTesting(); + intent_picker_icon->ExecuteForTesting(); #endif waiter.WaitIfNeededAndGet(); @@ -188,7 +210,7 @@ #endif // BUILDFLAG(IS_CHROMEOS) #endif // !BUILDFLAG(IS_CHROMEOS_LACROS) -// Tests that the intent icon updates its visibiliy when switching between +// Tests that the intent icon updates its visibility when switching between // tabs. IN_PROC_BROWSER_TEST_P(IntentPickerBubbleViewBrowserTest, IconVisibilityAfterTabSwitching) { @@ -199,19 +221,18 @@ const GURL out_of_scope_url = https_server().GetURL(GetAppUrlHost(), GetOutOfScopeUrlPath()); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); // OpenNewTab opens a new tab and focus on the new tab. OpenNewTab(in_scope_url); - EXPECT_TRUE(intent_picker_view->GetVisible()); + EXPECT_TRUE(intent_picker_icon->GetVisible()); OpenNewTab(out_of_scope_url); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); chrome::SelectPreviousTab(browser()); - EXPECT_TRUE(intent_picker_view->GetVisible()); - + EXPECT_TRUE(intent_picker_icon->GetVisible()); chrome::SelectNextTab(browser()); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); } // Tests that the navigation in iframe doesn't affect intent picker icon @@ -224,29 +245,25 @@ const GURL out_of_scope_url = https_server().GetURL(GetAppUrlHost(), GetOutOfScopeUrlPath()); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); - OpenNewTab(out_of_scope_url); - content::WebContents* initial_tab = - browser()->tab_strip_model()->GetActiveWebContents(); + content::WebContents* initial_tab = OpenNewTab(out_of_scope_url); ASSERT_TRUE(InsertIFrame(initial_tab)); EXPECT_TRUE( content::NavigateIframeToURL(initial_tab, "iframe", in_scope_url)); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); - OpenNewTab(in_scope_url); - content::WebContents* new_tab = - browser()->tab_strip_model()->GetActiveWebContents(); + content::WebContents* new_tab = OpenNewTab(in_scope_url); ASSERT_TRUE(InsertIFrame(new_tab)); EXPECT_TRUE( content::NavigateIframeToURL(initial_tab, "iframe", out_of_scope_url)); - EXPECT_TRUE(intent_picker_view->GetVisible()); + EXPECT_TRUE(intent_picker_icon->GetVisible()); } -// Tests that the intent picker icon is not visible if the navigatation -// redirects to a URL that doesn't have an installed PWA. +// Tests that the intent picker icon is not visible if the navigation redirects +// to a URL that doesn't have an installed PWA. IN_PROC_BROWSER_TEST_P(IntentPickerBubbleViewBrowserTest, DoesNotShowIntentPickerWhenRedirectedOutOfScope) { InstallTestWebApp(GetOtherAppUrlHost(), /*app_scope=*/"/"); @@ -257,15 +274,16 @@ const GURL redirect_url = https_server().GetURL( GetOtherAppUrlHost(), CreateServerRedirect(out_of_scope_url)); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); OpenNewTab(in_scope_url); - EXPECT_TRUE(intent_picker_view->GetVisible()); + EXPECT_TRUE(intent_picker_icon->GetVisible()); - ClickLinkAndWaitForURL(browser()->tab_strip_model()->GetActiveWebContents(), - redirect_url, out_of_scope_url, LinkTarget::SELF, - GetParam()); - EXPECT_FALSE(intent_picker_view->GetVisible()); + DoAndWaitForIntentPickerIconUpdate([this, redirect_url, out_of_scope_url] { + ClickLinkAndWaitForURL(GetWebContents(), redirect_url, out_of_scope_url, + LinkTarget::SELF, GetParam()); + }); + EXPECT_FALSE(intent_picker_icon->GetVisible()); } INSTANTIATE_TEST_SUITE_P( @@ -302,10 +320,6 @@ return prerender_helper_; } - content::WebContents* GetWebContents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - private: content::test::PrerenderTestHelper prerender_helper_; }; @@ -314,12 +328,12 @@ PrerenderingShouldNotShowIntentPicker) { InstallTestWebApp(); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); - const GURL initial_url = https_server().GetURL(GetAppUrlHost(), "/empty.html"); OpenNewTab(initial_url); - EXPECT_FALSE(intent_picker_view->GetVisible()); + + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); + EXPECT_FALSE(intent_picker_icon->GetVisible()); // Load a prerender page and prerendering should not try to show the // intent picker. @@ -329,15 +343,17 @@ content::test::PrerenderHostObserver host_observer(*GetWebContents(), host_id); EXPECT_FALSE(host_observer.was_activated()); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); // Activate the prerender page. - prerender_test_helper().NavigatePrimaryPage(prerender_url); + DoAndWaitForIntentPickerIconUpdate([this, prerender_url] { + prerender_test_helper().NavigatePrimaryPage(prerender_url); + }); EXPECT_TRUE(host_observer.was_activated()); // After activation, IntentPickerTabHelper should show the // intent picker. - EXPECT_TRUE(intent_picker_view->GetVisible()); + EXPECT_TRUE(intent_picker_icon->GetVisible()); } INSTANTIATE_TEST_SUITE_P( @@ -368,24 +384,20 @@ ShouldShowIntentPickerInFencedFrame) { InstallTestWebApp(); - PageActionIconView* intent_picker_view = GetIntentPickerIcon(); + PageActionIconView* intent_picker_icon = GetIntentPickerIcon(); const GURL initial_url = https_server().GetURL(GetAppUrlHost(), "/empty.html"); OpenNewTab(initial_url); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); const GURL fenced_frame_url = https_server().GetURL( GetAppUrlHost(), std::string(GetAppScopePath()) + "index1.html"); // Create a fenced frame. - ASSERT_TRUE( - fenced_frame_test_helper().CreateFencedFrame(browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->GetPrimaryMainFrame(), - fenced_frame_url)); + ASSERT_TRUE(fenced_frame_test_helper().CreateFencedFrame( + GetWebContents()->GetPrimaryMainFrame(), fenced_frame_url)); - EXPECT_FALSE(intent_picker_view->GetVisible()); + EXPECT_FALSE(intent_picker_icon->GetVisible()); } INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc index befdd18..b48f72c 100644 --- a/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc +++ b/chrome/browser/ui/views/intent_picker_bubble_view_browsertest_chromeos.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" +#include "chrome/browser/ui/intent_picker_tab_helper.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/location_bar/intent_picker_view.h" @@ -347,6 +348,19 @@ return embedded_test_server()->GetURL("/web_apps/minimal_ui/basic.html"); } + content::WebContents* GetWebContents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + + template <typename Action> + void DoAndWaitForIntentPickerIconUpdate(Action action) { + base::RunLoop run_loop; + auto* tab_helper = IntentPickerTabHelper::FromWebContents(GetWebContents()); + tab_helper->SetIconUpdateCallbackForTesting(run_loop.QuitClosure()); + action(); + run_loop.Run(); + } + private: base::test::ScopedFeatureList feature_list_; apps::AppServiceProxy* app_service_proxy_ = nullptr; @@ -404,14 +418,10 @@ // Launch the default selected app. EXPECT_EQ(0U, launched_arc_apps().size()); - content::TestNavigationObserver observer( - browser()->tab_strip_model()->GetActiveWebContents()); - - intent_picker_bubble()->AcceptDialog(); - ASSERT_NO_FATAL_FAILURE(VerifyArcAppLaunched(app_name, test_url)); - - // The page should go back to blank state after launching the app. - observer.WaitForNavigationFinished(); + DoAndWaitForIntentPickerIconUpdate([this, app_name, test_url] { + intent_picker_bubble()->AcceptDialog(); + ASSERT_NO_FATAL_FAILURE(VerifyArcAppLaunched(app_name, test_url)); + }); // Make sure that the intent picker icon is no longer visible. ASSERT_TRUE(intent_picker_view); @@ -744,12 +754,12 @@ NavigateParams params(browser(), test_url, ui::PageTransition::PAGE_TRANSITION_LINK); + // Navigates and waits for loading to finish. views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{}, IntentPickerBubbleView::kViewClassName); - // Navigates and waits for loading to finish. ui_test_utils::NavigateToURL(¶ms); - waiter.WaitIfNeededAndGet(); + EXPECT_TRUE(intent_picker_view->GetVisible()); ASSERT_TRUE(intent_picker_bubble()); EXPECT_TRUE(intent_picker_bubble()->GetVisible()); @@ -762,11 +772,12 @@ content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - content::TestNavigationObserver observer(web_contents); - ASSERT_TRUE(content::ExecuteScript( - web_contents, - "document.getElementById('push_to_new_url_button').click();")); - observer.WaitForNavigationFinished(); + DoAndWaitForIntentPickerIconUpdate([web_contents] { + ASSERT_TRUE(content::ExecuteScript( + web_contents, + "document.getElementById('push_to_new_url_button').click();")); + }); + EXPECT_FALSE(intent_picker_view->GetVisible()); } @@ -794,11 +805,9 @@ auto app_id = AddArcAppWithIntentFilter(app_name, test_url); // Reload the page and the intent picker should show up. - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - content::TestNavigationObserver observer(web_contents); - chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB); - observer.WaitForNavigationFinished(); + DoAndWaitForIntentPickerIconUpdate([this] { + chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB); + }); EXPECT_TRUE(intent_picker_view->GetVisible());
diff --git a/chrome/browser/ui/views/location_bar/intent_chip_button_browsertest.cc b/chrome/browser/ui/views/location_bar/intent_chip_button_browsertest.cc index 776b8d13..1ed56289a 100644 --- a/chrome/browser/ui/views/location_bar/intent_chip_button_browsertest.cc +++ b/chrome/browser/ui/views/location_bar/intent_chip_button_browsertest.cc
@@ -100,12 +100,23 @@ web_app::WebAppNavigationBrowserTest::TearDownOnMainThread(); } - void OpenNewTab(const GURL& url) { - chrome::NewTab(browser()); + template <typename Action> + void DoAndWaitForIntentPickerIconUpdate(Action action) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - NavigateToLaunchingPage(browser()); - ClickLinkAndWait(web_contents, url, LinkTarget::SELF, ""); + base::RunLoop run_loop; + auto* tab_helper = IntentPickerTabHelper::FromWebContents(web_contents); + tab_helper->SetIconUpdateCallbackForTesting(run_loop.QuitClosure()); + action(); + run_loop.Run(); + } + + void OpenNewTab(const GURL& url) { + chrome::NewTab(browser()); + DoAndWaitForIntentPickerIconUpdate( + [this] { NavigateToLaunchingPage(browser()); }); + ClickLinkAndWaitForIconUpdate( + browser()->tab_strip_model()->GetActiveWebContents(), url); } IntentChipButton* GetIntentChip() { @@ -114,11 +125,33 @@ ->GetIntentChipButton(); } - void ClickIntentChip() { + // Clicks the intent chip, and optionally waits for a browser app window to + // appear if `wait_for_browser` is true. If waiting is specified, the new + // browser window is returned; if waiting is not specified, null is returned. + Browser* ClickIntentChip(bool wait_for_browser) { + ui_test_utils::BrowserChangeObserver browser_opened( + nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded); + views::test::ButtonTestApi test_api(GetIntentChip()); ui::MouseEvent e(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), 0, 0); test_api.NotifyClick(e); + + if (wait_for_browser) { + return browser_opened.Wait(); + } + + return nullptr; + } + + void ClickLinkAndWaitForIconUpdate(content::WebContents* web_contents, + const GURL& link_url) { + auto* tab_helper = IntentPickerTabHelper::FromWebContents(web_contents); + + base::RunLoop run_loop; + tab_helper->SetIconUpdateCallbackForTesting(run_loop.QuitClosure()); + ClickLinkAndWait(web_contents, link_url, LinkTarget::SELF, ""); + run_loop.Run(); } // Installs a web app on the same host as InstallTestWebApp(), but with "/" as @@ -153,7 +186,7 @@ views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{}, "IntentPickerBubbleView"); - ClickIntentChip(); + ClickIntentChip(/*wait_for_browser=*/false); waiter.WaitIfNeededAndGet(); ASSERT_TRUE(IntentPickerBubbleView::intent_picker_bubble()); @@ -184,7 +217,6 @@ chrome::SelectPreviousTab(browser()); EXPECT_TRUE(intent_chip_button->GetVisible()); - chrome::SelectNextTab(browser()); EXPECT_FALSE(intent_chip_button->GetVisible()); } @@ -199,9 +231,8 @@ https_server().GetURL(GetAppUrlHost(), GetInScopeUrlPath()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), in_scope_url)); - ClickIntentChip(); + Browser* app_browser = ClickIntentChip(/*wait_for_browser=*/true); - Browser* app_browser = BrowserList::GetInstance()->GetLastActive(); EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, test_web_app_id())); } @@ -247,9 +278,8 @@ https_server().GetURL(GetAppUrlHost(), GetInScopeUrlPath()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), in_scope_url)); - ClickIntentChip(); + Browser* app_browser = ClickIntentChip(/*wait_for_browser=*/true); - Browser* app_browser = BrowserList::GetInstance()->GetLastActive(); EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, test_web_app_id())); } @@ -278,7 +308,7 @@ views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{}, "IntentPickerBubbleView"); - ClickIntentChip(); + ClickIntentChip(/*wait_for_browser=*/false); waiter.WaitIfNeededAndGet(); ASSERT_TRUE(IntentPickerBubbleView::intent_picker_bubble()); @@ -298,43 +328,44 @@ browser()->tab_strip_model()->GetActiveWebContents(); // 1st appearance: Expanded. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); EXPECT_FALSE(GetIntentChip()->is_fully_collapsed()); - ClickLinkAndWait(web_contents, separate_host_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, separate_host_url); EXPECT_FALSE(GetIntentChip()->GetVisible()); // 2nd appearance: Expanded. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); EXPECT_FALSE(GetIntentChip()->is_fully_collapsed()); - ClickLinkAndWait(web_contents, out_of_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, out_of_scope_url); EXPECT_FALSE(GetIntentChip()->GetVisible()); // 3rd appearance: Expanded. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); EXPECT_FALSE(GetIntentChip()->is_fully_collapsed()); - ClickLinkAndWait(web_contents, out_of_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, out_of_scope_url); EXPECT_FALSE(GetIntentChip()->GetVisible()); // 4th appearance: Collapsed. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); EXPECT_TRUE(GetIntentChip()->is_fully_collapsed()); // Click to open app and reset the counter. - ClickIntentChip(); + ClickIntentChip(/*wait_for_browser=*/true); // Open another browser- we should be able to see the expanded chip again. - NavigateToLaunchingPage(browser()); - web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + DoAndWaitForIntentPickerIconUpdate( + [this] { NavigateToLaunchingPage(browser()); }); // 1st appearance since intent chip counter reset: Expanded. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); EXPECT_FALSE(GetIntentChip()->is_fully_collapsed()); } @@ -380,7 +411,7 @@ browser()->tab_strip_model()->GetActiveWebContents(); // Navigate to an in-scope page to see the intent chip and the IPH. - ClickLinkAndWait(web_contents, in_scope_url, LinkTarget::SELF, ""); + ClickLinkAndWaitForIconUpdate(web_contents, in_scope_url); EXPECT_TRUE(GetIntentChip()->GetVisible()); // Wait for the chip to actually be laid out. This will result in the IPH @@ -394,7 +425,7 @@ feature_engagement::kIPHIntentChipFeature)); // When we click on the intent chip, the IPH should disappear. - ClickIntentChip(); + ClickIntentChip(/*wait_for_browser=*/false); // Check the IPH is no longer showing. EXPECT_FALSE(browser_view->IsFeaturePromoActive( @@ -407,18 +438,6 @@ feature_list_.InitAndEnableFeature(apps::features::kIntentChipAppIcon); } - void ClickLinkAndWaitForIconUpdate(content::WebContents* web_contents, - const GURL& link_url) { - auto* tab_helper = IntentPickerTabHelper::FromWebContents(web_contents); - base::RunLoop run_loop; - tab_helper->SetIconUpdateCallbackForTesting( - base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); })); - - ClickLinkAndWait(web_contents, link_url, LinkTarget::SELF, ""); - - run_loop.Run(); - } - private: base::test::ScopedFeatureList feature_list_; }; @@ -481,13 +500,14 @@ ShowsInfoBarOnAppOpen) { const GURL in_scope_url = https_server().GetURL(GetAppUrlHost(), GetInScopeUrlPath()); - ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), in_scope_url)); + DoAndWaitForIntentPickerIconUpdate([this, in_scope_url] { + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), in_scope_url)); + }); EXPECT_TRUE(GetIntentChip()->GetVisible()); - ClickIntentChip(); + Browser* app_browser = ClickIntentChip(/*wait_for_browser=*/true); - Browser* app_browser = BrowserList::GetInstance()->GetLastActive(); EXPECT_TRUE(web_app::AppBrowserController::IsForWebApp(app_browser, test_web_app_id())); auto* infobar_manager = infobars::ContentInfoBarManager::FromWebContents(
diff --git a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc index 6c98e631..a81b4ac0 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc
@@ -181,6 +181,9 @@ OmniboxMatchCellView::OmniboxMatchCellView(OmniboxResultView* result_view) { icon_view_ = AddChildView(std::make_unique<views::ImageView>()); answer_image_view_ = AddChildView(std::make_unique<RoundedCornerImageView>()); + tail_suggest_ellipse_view_ = + AddChildView(std::make_unique<OmniboxTextView>(result_view)); + tail_suggest_ellipse_view_->SetText(AutocompleteMatch::kEllipsis); content_view_ = AddChildView(std::make_unique<OmniboxTextView>(result_view)); description_view_ = AddChildView(std::make_unique<OmniboxTextView>(result_view)); @@ -212,6 +215,9 @@ ? LayoutStyle::TWO_LINE_SUGGESTION : LayoutStyle::ONE_LINE_SUGGESTION; + tail_suggest_ellipse_view_->SetVisible( + !match.tail_suggest_common_prefix.empty()); + // Set up the separator. separator_view_->SetSize(layout_style_ == LayoutStyle::TWO_LINE_SUGGESTION || match.description.empty() @@ -337,6 +343,13 @@ description_width, text_width, /*description_on_separate_line=*/false, !is_search_type_, &content_width, &description_width); + if (tail_suggest_ellipse_view_->GetVisible()) { + const int tail_suggest_ellipse_width = + tail_suggest_ellipse_view_->GetPreferredSize().width(); + tail_suggest_ellipse_view_->SetBounds(x - tail_suggest_ellipse_width, y, + tail_suggest_ellipse_width, + row_height); + } content_view_->SetBounds(x, y, content_width, row_height); if (description_width) { x += content_view_->width(); @@ -373,13 +386,6 @@ std::unique_ptr<gfx::RenderText> render_text = content_view_->CreateRenderText(common_prefix); tail_suggest_common_prefix_width_ = render_text->GetStringSize().width(); - // Only calculate fixed string width once. - if (!ellipsis_width_) { - render_text->SetText(AutocompleteMatch::kEllipsis); - ellipsis_width_ = render_text->GetStringSize().width(); - } - // Indent text by prefix, but come back by width of ellipsis. - tail_suggest_common_prefix_width_ -= ellipsis_width_; } BEGIN_METADATA(OmniboxMatchCellView, views::View)
diff --git a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h index c9fa448b..a28d4179 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h +++ b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h
@@ -96,15 +96,11 @@ raw_ptr<views::ImageView> icon_view_; // The image for answers in suggest and rich entity suggestions. raw_ptr<views::ImageView> answer_image_view_; + raw_ptr<OmniboxTextView> tail_suggest_ellipse_view_; raw_ptr<OmniboxTextView> content_view_; raw_ptr<OmniboxTextView> description_view_; raw_ptr<OmniboxTextView> separator_view_; - // This (permanently) holds the rendered width of - // AutocompleteMatch::kEllipsis so that we don't have to keep calculating - // it. - int ellipsis_width_ = 0; - // This holds the rendered width of the common prefix of a set of tail // suggestions so that it doesn't have to be re-calculated if the prefix // doesn't change.
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc index a2f392fb..93949fd 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc
@@ -333,9 +333,6 @@ popup_created = true; } - // Fix-up any matches due to tail suggestions, before display below. - edit_model_->autocomplete_controller()->SetTailSuggestContentPrefixes(); - // Update the match cached by each row, in the process of doing so make sure // we have enough row views. const size_t result_size = edit_model_->result().size();
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_view.cc b/chrome/browser/ui/views/passwords/manage_passwords_view.cc index bb35dc3..1d66109 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_view.cc +++ b/chrome/browser/ui/views/passwords/manage_passwords_view.cc
@@ -10,6 +10,7 @@ #include "base/functional/bind.h" #include "base/notreached.h" +#include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/browser/ui/passwords/ui_utils.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" @@ -20,8 +21,12 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/password_manager/core/browser/password_manager_client.h" +#include "components/password_manager/core/browser/password_ui_utils.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/vector_icons/vector_icons.h" +#include "ui/views/controls/button/image_button.h" +#include "ui/views/controls/button/image_button_factory.h" +#include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/box_layout_view.h" @@ -95,6 +100,43 @@ return header; } +std::unique_ptr<views::View> +ManagePasswordsView::CreatePasswordDetailsTitleView( + const password_manager::PasswordForm& password_form) { + ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); + auto header = std::make_unique<views::BoxLayoutView>(); + // Set the space between the icons and title similar to the default behavior + // in BubbleFrameView::Layout(). + header->SetBetweenChildSpacing( + layout_provider->GetInsetsMetric(views::INSETS_DIALOG_TITLE).left()); + + auto back_button = views::CreateVectorImageButtonWithNativeTheme( + base::BindRepeating( + [](ManagePasswordsView* view) { + view->GetBubbleFrameView()->SetTitleView( + view->CreatePasswordListTitleView()); + view->page_container_->SwitchToPage(view->CreatePasswordListView()); + }, + base::Unretained(this)), + vector_icons::kArrowBackIcon); + back_button->SetTooltipText(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK)); + views::InstallCircleHighlightPathGenerator(back_button.get()); + header->AddChildView(std::move(back_button)); + + // TODO(crbug.com/1382017): Use favicon instead of the GPM icon. + header->AddChildView( + std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon( + GooglePasswordManagerVectorIcon(), ui::kColorIcon, + layout_provider->GetDistanceMetric( + DISTANCE_BUBBLE_HEADER_VECTOR_ICON_SIZE)))); + + std::string shown_origin = + password_manager::GetShownOriginAndLinkUrl(password_form).first; + header->AddChildView(views::BubbleFrameView::CreateDefaultTitleLabel( + base::UTF8ToUTF16(shown_origin))); + return header; +} + std::unique_ptr<views::View> ManagePasswordsView::CreatePasswordListView() { auto container_view = std::make_unique<views::BoxLayoutView>(); container_view->SetOrientation(views::BoxLayout::Orientation::kVertical); @@ -108,6 +150,9 @@ base::BindRepeating( [](ManagePasswordsView* view, const password_manager::PasswordForm& password_form) { + DCHECK(view->GetBubbleFrameView()); + view->GetBubbleFrameView()->SetTitleView( + view->CreatePasswordDetailsTitleView(password_form)); view->page_container_->SwitchToPage( view->CreatePasswordDetailsView(password_form)); },
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_view.h b/chrome/browser/ui/views/passwords/manage_passwords_view.h index 5fbcbf89..6182d8d 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_view.h +++ b/chrome/browser/ui/views/passwords/manage_passwords_view.h
@@ -34,6 +34,8 @@ std::unique_ptr<views::View> CreatePasswordListView(); std::unique_ptr<views::View> CreatePasswordDetailsView( const password_manager::PasswordForm& password_form) const; + std::unique_ptr<views::View> CreatePasswordDetailsTitleView( + const password_manager::PasswordForm& password_form); std::unique_ptr<views::View> CreateFooterView(); ItemsBubbleController controller_;
diff --git a/chrome/browser/ui/views/performance_controls/battery_saver_bubble_view.cc b/chrome/browser/ui/views/performance_controls/battery_saver_bubble_view.cc index ad17b5c..0f2c6e8 100644 --- a/chrome/browser/ui/views/performance_controls/battery_saver_bubble_view.cc +++ b/chrome/browser/ui/views/performance_controls/battery_saver_bubble_view.cc
@@ -12,6 +12,7 @@ #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/dialog_model.h" +#include "ui/base/models/dialog_model_field.h" #include "ui/views/bubble/bubble_dialog_model_host.h" #include "ui/views/view_class_properties.h" @@ -40,11 +41,15 @@ ui::DialogModelLabel(IDS_BATTERY_SAVER_BUBBLE_DESCRIPTION) .set_is_secondary() .set_allow_character_break()) - .AddOkButton(base::DoNothing(), l10n_util::GetStringUTF16(IDS_OK)) + .AddOkButton(base::DoNothing(), + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_OK))) .AddCancelButton( base::BindOnce(&BatterySaverBubbleDelegate::OnSessionOffClicked, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16(IDS_BATTERY_SAVER_SESSION_TURN_OFF)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_BATTERY_SAVER_SESSION_TURN_OFF))) .Build(); auto bubble_unique = std::make_unique<views::BubbleDialogModelHost>(
diff --git a/chrome/browser/ui/views/performance_controls/high_efficiency_bubble_view.cc b/chrome/browser/ui/views/performance_controls/high_efficiency_bubble_view.cc index 5339605..e9bb8dd 100644 --- a/chrome/browser/ui/views/performance_controls/high_efficiency_bubble_view.cc +++ b/chrome/browser/ui/views/performance_controls/high_efficiency_bubble_view.cc
@@ -46,7 +46,8 @@ .SetDialogDestroyingCallback( base::BindOnce(&HighEfficiencyBubbleDelegate::OnDialogDestroy, base::Unretained(bubble_delegate))) - .AddOkButton(base::DoNothing(), l10n_util::GetStringUTF16(IDS_OK)); + .AddOkButton(base::DoNothing(), ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_OK))); TabDiscardTabHelper* const tab_helper = TabDiscardTabHelper::FromWebContents( browser->tab_strip_model()->GetActiveWebContents());
diff --git a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_notice_bubble.cc b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_notice_bubble.cc index f939b6bd..f4a3fcc 100644 --- a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_notice_bubble.cc +++ b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_notice_bubble.cc
@@ -118,8 +118,9 @@ base::BindRepeating( &PrivacySandboxNoticeBubbleModelDelegate::OnOkButtonPressed, base::Unretained(bubble_delegate)), - l10n_util::GetStringUTF16( - IDS_PRIVACY_SANDBOX_DIALOG_NOTICE_ACKNOWLEDGE_BUTTON)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_PRIVACY_SANDBOX_DIALOG_NOTICE_ACKNOWLEDGE_BUTTON))) .AddExtraLink(ui::DialogModelLabel::CreateLink( IDS_PRIVACY_SANDBOX_BUBBLE_NOTICE_SETTINGS_LINK, base::BindRepeating(&PrivacySandboxNoticeBubbleModelDelegate::
diff --git a/chrome/browser/ui/views/safe_browsing/tailored_security_desktop_dialog_manager.cc b/chrome/browser/ui/views/safe_browsing/tailored_security_desktop_dialog_manager.cc index a5e3ab6..d4f9afea 100644 --- a/chrome/browser/ui/views/safe_browsing/tailored_security_desktop_dialog_manager.cc +++ b/chrome/browser/ui/views/safe_browsing/tailored_security_desktop_dialog_manager.cc
@@ -130,8 +130,9 @@ .AddCancelButton( base::BindOnce(&EnabledDialogModelDelegate::OnDialogRejected, base::Unretained(model_delegate_ptr), browser), - l10n_util::GetStringUTF16( - IDS_TAILORED_SECURITY_DIALOG_SETTINGS_BUTTON)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_TAILORED_SECURITY_DIALOG_SETTINGS_BUTTON))) .Build(); // `window` should always be non-null unless this is called before @@ -165,13 +166,15 @@ .AddOkButton( base::BindOnce(&DisabledDialogModelDelegate::OnDialogAccepted, base::Unretained(model_delegate_ptr)), - l10n_util::GetStringUTF16( - IDS_TAILORED_SECURITY_DISABLED_DIALOG_ACCEPT_BUTTON)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_TAILORED_SECURITY_DISABLED_DIALOG_ACCEPT_BUTTON))) .AddCancelButton( base::BindOnce(&DisabledDialogModelDelegate::OnDialogRejected, base::Unretained(model_delegate_ptr), browser), - l10n_util::GetStringUTF16( - IDS_TAILORED_SECURITY_DIALOG_SETTINGS_BUTTON)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16( + IDS_TAILORED_SECURITY_DIALOG_SETTINGS_BUTTON))) .Build(); // `window` should always be non-null unless this is called before
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view.cc b/chrome/browser/ui/views/session_crashed_bubble_view.cc index 7fbdbf0..5fbf4eb0 100644 --- a/chrome/browser/ui/views/session_crashed_bubble_view.cc +++ b/chrome/browser/ui/views/session_crashed_bubble_view.cc
@@ -301,7 +301,8 @@ dialog_builder.AddOkButton( base::BindOnce(&SessionCrashedBubbleDelegate::RestorePreviousSession, base::Unretained(bubble_delegate), browser), - l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_RESTORE_BUTTON)); + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_RESTORE_BUTTON))); auto bubble = std::make_unique<views::BubbleDialogModelHost>( dialog_builder.Build(), anchor_view, views::BubbleBorder::TOP_RIGHT);
diff --git a/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator.h b/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator.h index fb37e7f..ae59ec5 100644 --- a/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator.h +++ b/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator.h
@@ -25,6 +25,7 @@ class SidePanelRegistry; class UserNoteView; class BrowserView; +class TabStripModel; namespace user_notes { class UserNoteInstance;
diff --git a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc index f6876648..0f4c23e 100644 --- a/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc +++ b/chrome/browser/ui/views/site_data/page_specific_site_data_dialog.cc
@@ -571,7 +571,8 @@ base::BindRepeating(&PageSpecificSiteDataDialogModelDelegate:: OnDialogExplicitlyClosed, base::Unretained(delegate)), - l10n_util::GetStringUTF16(IDS_DONE)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_DONE))) .SetCloseActionCallback(base::BindOnce( &PageSpecificSiteDataDialogModelDelegate::OnDialogExplicitlyClosed, base::Unretained(delegate)));
diff --git a/chrome/browser/ui/views/supervised_user/extension_install_blocked_by_parent_dialog.cc b/chrome/browser/ui/views/supervised_user/extension_install_blocked_by_parent_dialog.cc index 76c0b97..371a04f 100644 --- a/chrome/browser/ui/views/supervised_user/extension_install_blocked_by_parent_dialog.cc +++ b/chrome/browser/ui/views/supervised_user/extension_install_blocked_by_parent_dialog.cc
@@ -67,7 +67,9 @@ chromeos::kNotificationSupervisedUserIcon, ui::kColorIcon))) .AddParagraph( ui::DialogModelLabel(GetBodyText(action, extension_type))) - .AddOkButton(base::DoNothing(), l10n_util::GetStringUTF16(IDS_OK)) + .AddOkButton(base::DoNothing(), + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_OK))) .SetDialogDestroyingCallback(std::move(done_callback)) .Build();
diff --git a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc index 16c561df..6d592357 100644 --- a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc +++ b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.cc
@@ -218,7 +218,7 @@ // Walk the model, calling our insertion observer method for each item within // it. for (int i = 0; i < model_->count(); ++i) - AddTab(model_->GetWebContentsAt(i), i, model_->active_index() == i); + AddTab(model_->GetWebContentsAt(i), i); } bool BrowserTabStripController::IsCommandEnabledForTab( @@ -611,8 +611,7 @@ case TabStripModelChange::kInserted: { for (const auto& contents : change.GetInsert()->contents) { DCHECK(model_->ContainsIndex(contents.index)); - AddTab(contents.contents, contents.index, - selection.new_contents == contents.contents); + AddTab(contents.contents, contents.index); } break; } @@ -778,9 +777,7 @@ TabRendererData::FromTabInModel(model_, model_index)); } -void BrowserTabStripController::AddTab(WebContents* contents, - int index, - bool is_active) { +void BrowserTabStripController::AddTab(WebContents* contents, int index) { // Cancel any pending tab transition. hover_tab_selector_.CancelTabTransition();
diff --git a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.h b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.h index a1c11d2..27d98c6 100644 --- a/chrome/browser/ui/views/tabs/browser_tab_strip_controller.h +++ b/chrome/browser/ui/views/tabs/browser_tab_strip_controller.h
@@ -154,7 +154,7 @@ void SetTabDataAt(content::WebContents* web_contents, int model_index); // Adds a tab. - void AddTab(content::WebContents* contents, int index, bool is_active); + void AddTab(content::WebContents* contents, int index); raw_ptr<TabStripModel> model_;
diff --git a/chrome/browser/ui/views/tabs/compound_tab_container.cc b/chrome/browser/ui/views/tabs/compound_tab_container.cc index f59edd7..e6016cf 100644 --- a/chrome/browser/ui/views/tabs/compound_tab_container.cc +++ b/chrome/browser/ui/views/tabs/compound_tab_container.cc
@@ -358,6 +358,13 @@ new_visuals); } +void CompoundTabContainer::ToggleTabGroup( + const tab_groups::TabGroupId& group, + bool is_collapsing, + ToggleTabGroupCollapsedStateOrigin origin) { + unpinned_tab_container_->ToggleTabGroup(group, is_collapsing, origin); +} + void CompoundTabContainer::OnGroupClosed(const tab_groups::TabGroupId& group) { unpinned_tab_container_->OnGroupClosed(group); }
diff --git a/chrome/browser/ui/views/tabs/compound_tab_container.h b/chrome/browser/ui/views/tabs/compound_tab_container.h index c46c301d..86c237f 100644 --- a/chrome/browser/ui/views/tabs/compound_tab_container.h +++ b/chrome/browser/ui/views/tabs/compound_tab_container.h
@@ -54,6 +54,9 @@ const tab_groups::TabGroupVisualData* old_visuals, const tab_groups::TabGroupVisualData* new_visuals) override; void OnGroupClosed(const tab_groups::TabGroupId& group) override; + void ToggleTabGroup(const tab_groups::TabGroupId& group, + bool is_collapsing, + ToggleTabGroupCollapsedStateOrigin origin) override; void UpdateTabGroupVisuals(tab_groups::TabGroupId group_id) override; void NotifyTabGroupEditorBubbleOpened() override; void NotifyTabGroupEditorBubbleClosed() override;
diff --git a/chrome/browser/ui/views/tabs/tab_container.h b/chrome/browser/ui/views/tabs/tab_container.h index e80d80f..22832e5 100644 --- a/chrome/browser/ui/views/tabs/tab_container.h +++ b/chrome/browser/ui/views/tabs/tab_container.h
@@ -75,6 +75,9 @@ const tab_groups::TabGroupId& group, const tab_groups::TabGroupVisualData* old_visuals, const tab_groups::TabGroupVisualData* new_visuals) = 0; + virtual void ToggleTabGroup(const tab_groups::TabGroupId& group, + bool is_collapsing, + ToggleTabGroupCollapsedStateOrigin origin) = 0; virtual void OnGroupClosed(const tab_groups::TabGroupId& group) = 0; virtual void UpdateTabGroupVisuals(tab_groups::TabGroupId group_id) = 0; virtual void NotifyTabGroupEditorBubbleOpened() = 0;
diff --git a/chrome/browser/ui/views/tabs/tab_container_impl.cc b/chrome/browser/ui/views/tabs/tab_container_impl.cc index a21b659..79be883 100644 --- a/chrome/browser/ui/views/tabs/tab_container_impl.cc +++ b/chrome/browser/ui/views/tabs/tab_container_impl.cc
@@ -496,6 +496,35 @@ OrderTabSlotView(group_views_[group]->header()); } +void TabContainerImpl::ToggleTabGroup( + const tab_groups::TabGroupId& group, + bool is_collapsing, + ToggleTabGroupCollapsedStateOrigin origin) { + if (is_collapsing && GetWidget()) { + if (origin != ToggleTabGroupCollapsedStateOrigin::kMouse && + origin != ToggleTabGroupCollapsedStateOrigin::kGesture) { + return; + } + + const int current_group_width = GetGroupViews(group)->GetBounds().width(); + // A collapsed group only has the width of its header, which is slightly + // smaller for collapsed groups compared to expanded groups. + const int collapsed_group_width = + GetGroupViews(group)->header()->GetCollapsedHeaderWidth(); + const CloseTabSource source = + origin == ToggleTabGroupCollapsedStateOrigin::kMouse + ? CloseTabSource::CLOSE_TAB_FROM_MOUSE + : CloseTabSource::CLOSE_TAB_FROM_TOUCH; + + EnterTabClosingMode( + tabs_view_model_.ideal_bounds(GetTabCount() - 1).right() - + current_group_width + collapsed_group_width, + source); + } else { + ExitTabClosingMode(); + } +} + void TabContainerImpl::OnGroupClosed(const tab_groups::TabGroupId& group) { bounds_animator_.StopAnimatingView(group_views_.at(group).get()->header()); layout_helper_->RemoveGroupHeader(group);
diff --git a/chrome/browser/ui/views/tabs/tab_container_impl.h b/chrome/browser/ui/views/tabs/tab_container_impl.h index a16eaf6..df7884d 100644 --- a/chrome/browser/ui/views/tabs/tab_container_impl.h +++ b/chrome/browser/ui/views/tabs/tab_container_impl.h
@@ -74,6 +74,9 @@ const tab_groups::TabGroupId& group, const tab_groups::TabGroupVisualData* old_visuals, const tab_groups::TabGroupVisualData* new_visuals) override; + void ToggleTabGroup(const tab_groups::TabGroupId& group, + bool is_collapsing, + ToggleTabGroupCollapsedStateOrigin origin) override; void OnGroupClosed(const tab_groups::TabGroupId& group) override; void UpdateTabGroupVisuals(tab_groups::TabGroupId group_id) override; void NotifyTabGroupEditorBubbleOpened() override;
diff --git a/chrome/browser/ui/views/tabs/tab_strip.cc b/chrome/browser/ui/views/tabs/tab_strip.cc index 1979dc20d..f4a7d92 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.cc +++ b/chrome/browser/ui/views/tabs/tab_strip.cc
@@ -1135,31 +1135,7 @@ void TabStrip::ToggleTabGroup(const tab_groups::TabGroupId& group, bool is_collapsing, ToggleTabGroupCollapsedStateOrigin origin) { - if (is_collapsing && GetWidget()) { - if (origin != ToggleTabGroupCollapsedStateOrigin::kMouse && - origin != ToggleTabGroupCollapsedStateOrigin::kGesture) { - return; - } - - const int current_group_width = - tab_container_->GetGroupViews(group)->GetBounds().width(); - // A collapsed group only has the width of its header, which is slightly - // smaller for collapsed groups compared to expanded groups. - const int collapsed_group_width = tab_container_->GetGroupViews(group) - ->header() - ->GetCollapsedHeaderWidth(); - const CloseTabSource source = - origin == ToggleTabGroupCollapsedStateOrigin::kMouse - ? CloseTabSource::CLOSE_TAB_FROM_MOUSE - : CloseTabSource::CLOSE_TAB_FROM_TOUCH; - - tab_container_->EnterTabClosingMode( - tab_container_->GetIdealBounds(GetModelCount() - 1).right() - - current_group_width + collapsed_group_width, - source); - } else { - tab_container_->ExitTabClosingMode(); - } + tab_container_->ToggleTabGroup(group, is_collapsing, origin); } void TabStrip::OnGroupMoved(const tab_groups::TabGroupId& group) {
diff --git a/chrome/browser/ui/views/tabs/tab_strip.h b/chrome/browser/ui/views/tabs/tab_strip.h index 1d0b7e8..c7f3a82 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.h +++ b/chrome/browser/ui/views/tabs/tab_strip.h
@@ -166,7 +166,6 @@ const tab_groups::TabGroupVisualData* new_visuals); // Handles animations relating to toggling the collapsed state of a group. - // TODO(1295774): Maybe move this functionality into TabContainer. void ToggleTabGroup(const tab_groups::TabGroupId& group, bool is_collapsing, ToggleTabGroupCollapsedStateOrigin origin);
diff --git a/chrome/browser/ui/views/web_apps/web_app_detailed_install_dialog.cc b/chrome/browser/ui/views/web_apps/web_app_detailed_install_dialog.cc index 3cabcab..a93525ed 100644 --- a/chrome/browser/ui/views/web_apps/web_app_detailed_install_dialog.cc +++ b/chrome/browser/ui/views/web_apps/web_app_detailed_install_dialog.cc
@@ -356,7 +356,8 @@ base::BindOnce( &web_app::WebAppDetailedInstallDialogDelegate::OnAccept, base::Unretained(delegate_ptr)), - l10n_util::GetStringUTF16(IDS_INSTALL)) + ui::DialogModelButton::Params().SetLabel( + l10n_util::GetStringUTF16(IDS_INSTALL))) .AddCancelButton(base::BindOnce( &web_app::WebAppDetailedInstallDialogDelegate::OnCancel, base::Unretained(delegate_ptr)))
diff --git a/chrome/browser/ui/webui/ash/diagnostics_dialog.cc b/chrome/browser/ui/webui/ash/diagnostics_dialog.cc index 7ac83a20..d9946de4 100644 --- a/chrome/browser/ui/webui/ash/diagnostics_dialog.cc +++ b/chrome/browser/ui/webui/ash/diagnostics_dialog.cc
@@ -8,6 +8,7 @@ #include "ash/constants/ash_features.h" #include "ash/system/diagnostics/diagnostics_log_controller.h" +#include "ash/webui/diagnostics_ui/diagnostics_ui.h" #include "ash/webui/diagnostics_ui/url_constants.h" #include "base/strings/strcat.h" #include "ui/display/display.h" @@ -70,4 +71,8 @@ *size = display_size; } +bool DiagnosticsDialog::ShouldCloseDialogOnEscape() const { + return DiagnosticsDialogUI::ShouldCloseDialogOnEscape(); +} + } // namespace ash
diff --git a/chrome/browser/ui/webui/ash/diagnostics_dialog.h b/chrome/browser/ui/webui/ash/diagnostics_dialog.h index c21f788..d8b7fafb 100644 --- a/chrome/browser/ui/webui/ash/diagnostics_dialog.h +++ b/chrome/browser/ui/webui/ash/diagnostics_dialog.h
@@ -37,6 +37,7 @@ // SystemWebDialogDelegate const std::string& Id() override; + bool ShouldCloseDialogOnEscape() const override; // ui::WebDialogDelegate void GetDialogSize(gfx::Size* size) const override;
diff --git a/chrome/browser/ui/webui/ash/login/oobe_ui.cc b/chrome/browser/ui/webui/ash/login/oobe_ui.cc index eab184a..21fb1a4 100644 --- a/chrome/browser/ui/webui/ash/login/oobe_ui.cc +++ b/chrome/browser/ui/webui/ash/login/oobe_ui.cc
@@ -162,11 +162,15 @@ constexpr char kArcPlaystoreLogoPath[] = "arc_support/icon/playstore.svg"; constexpr char kArcSupervisionIconPath[] = "supervision_icon.png"; constexpr char kDebuggerMJSPath[] = "debug/debug.m.js"; +constexpr char kDebuggerUtilJSPath[] = "debug/debug_util.js"; constexpr char kKeyboardUtilsJSPath[] = "keyboard_utils.js"; constexpr char kKeyboardUtilsForInjectionModulePath[] = "components/keyboard_utils_for_injection.m.js"; constexpr char kProductLogoPath[] = "product-logo.png"; +// TODO(crbug.com/1261902): Clean-up old implementation once feature is +// launched. +constexpr char kRecommendAppListViewJSPath[] = "recommend_app_list_view.js"; constexpr char kTestAPIJsMPath[] = "test_api/test_api.m.js"; // Components @@ -214,6 +218,12 @@ source->AddResourcePath(kArcPlaystoreLogoPath, IDR_ARC_SUPPORT_PLAYSTORE_LOGO); + // TODO(crbug.com/1261902): Clean-up old implementation once feature is + // launched. + if (!features::IsOobeNewRecommendAppsEnabled()) { + source->AddResourcePath(kRecommendAppListViewJSPath, + IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_JS); + } #if BUILDFLAG(GOOGLE_CHROME_BRANDING) source->AddResourcePath(kArcAppDownloadingVideoPath, IDR_OOBE_ARC_APPS_DOWNLOADING_VIDEO); @@ -246,10 +256,12 @@ } if (enable_debugger) { + source->AddResourcePath(kDebuggerUtilJSPath, IDR_OOBE_DEBUGGER_UTIL_JS); source->AddResourcePath(kDebuggerMJSPath, IDR_OOBE_DEBUGGER_M_JS); } else { // Serve empty files under all resource paths. source->AddResourcePath(kDebuggerMJSPath, IDR_OOBE_DEBUGGER_STUB_JS); + source->AddResourcePath(kDebuggerUtilJSPath, IDR_OOBE_DEBUGGER_STUB_JS); } }
diff --git a/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc b/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc index e509560..ff76de5 100644 --- a/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc +++ b/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc
@@ -93,8 +93,6 @@ content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIBrowserSwitchHost); - source->DisableTrustedTypesCSP(); - auto* service = GetBrowserSwitcherService(web_ui); source->AddInteger("launchDelay", service->prefs().GetDelay());
diff --git a/chrome/browser/ui/webui/browsing_topics/browsing_topics_internals_ui.cc b/chrome/browser/ui/webui/browsing_topics/browsing_topics_internals_ui.cc index 52af0b6..bfe2dfd 100644 --- a/chrome/browser/ui/webui/browsing_topics/browsing_topics_internals_ui.cc +++ b/chrome/browser/ui/webui/browsing_topics/browsing_topics_internals_ui.cc
@@ -25,6 +25,7 @@ base::make_span(kBrowsingTopicsInternalsResources, kBrowsingTopicsInternalsResourcesSize), IDR_BROWSING_TOPICS_INTERNALS_BROWSING_TOPICS_INTERNALS_HTML); + webui::EnableTrustedTypesCSP(source); content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), source);
diff --git a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc index 284c21c..149968e 100644 --- a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc +++ b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
@@ -157,7 +157,7 @@ feature_list_.InitWithFeatures(enabled_features, {}); } - void CheckTrustedTypesViolation(base::StringPiece url) { + void CheckNoTrustedTypesViolation(base::StringPiece url) { std::string message_filter1 = "*This document requires*assignment*"; std::string message_filter2 = "*Refused to create a TrustedTypePolicy*"; content::WebContents* content = @@ -180,6 +180,35 @@ EXPECT_TRUE(console_observer.messages().empty()); } + void CheckTrustedTypesEnabled(base::StringPiece url) { + content::WebContents* content = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(embedded_test_server()->Start()); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(url))); + + if (url == "chrome://network-error" || url == "chrome://dino") { + // We don't ASSERT_TRUE here because some WebUI pages are + // PAGE_TYPE_ERROR by design. + content::WaitForLoadStop(content); + } else { + ASSERT_TRUE(content::WaitForLoadStop(content)); + } + + const char kIsTrustedTypesEnabled[] = + "(function isTrustedTypesEnabled() {" + " try {" + " document.body.innerHTML = 'foo';" + " } catch(e) {" + " return true;" + " }" + " return false;" + "})();"; + + EXPECT_EQ(true, EvalJs(content, kIsTrustedTypesEnabled, + content::EXECUTE_SCRIPT_DEFAULT_OPTIONS, + 1 /* world_id */)); + } + static std::string ParamInfoToString( const ::testing::TestParamInfo<const char*>& info) { std::string name(info.param); @@ -195,33 +224,41 @@ #endif }; -// Verify that there's no Trusted Types violation in chrome://chrome-urls +// Verify that there's no Trusted Types violation in any `kChromeUrls`. IN_PROC_BROWSER_TEST_P(ChromeURLDataManagerWebUITrustedTypesTest, NoTrustedTypesViolation) { - CheckTrustedTypesViolation(GetParam()); + CheckNoTrustedTypesViolation(GetParam()); } -// Non-exhaustive list of chrome:// URLs to test for trusted types violations. +// Verify that Trusted Types checks are actually enabled for all `kChromeUrls`. +IN_PROC_BROWSER_TEST_P(ChromeURLDataManagerWebUITrustedTypesTest, + TrustedTypesEnabled) { + CheckTrustedTypesEnabled(GetParam()); +} + +// Non-exhaustive list of chrome:// URLs to test for +// 1) TrustedTypes violations (see NoTrustedTypesViolation test). +// 2) Presence of TrustedTypes checks (see TrustedTypesEnabled test). // This list was derived from chrome://about. :) +// +// TODO(crbug.com/1098690): For all commented out URLs below, uncomment after +// enabling TrustedTypes, unless they are commented out for another reason +// (like flaky failures). static constexpr const char* const kChromeUrls[] = { "chrome://accessibility", "chrome://apc-internals", "chrome://attribution-internals", "chrome://autofill-internals", - "chrome://blob-internals", + // "chrome://blob-internals", "chrome://bookmarks", "chrome://chrome-urls", "chrome://components", "chrome://connection-help", "chrome://connection-monitoring-detected", "chrome://crashes", -#if !((BUILDFLAG(IS_LINUX) && !defined(NDEBUG)) || defined(ADDRESS_SANITIZER)) - // TODO(crbug.com/1380393): Failing on Linux debug builder and ASan (time - // out). "chrome://credits", -#endif "chrome://device-log", - "chrome://dino", + // "chrome://dino", // TODO(crbug.com/1113446): Test failure due to excessive output. // "chrome://discards", "chrome://download-internals", @@ -247,8 +284,8 @@ // TODO(crbug.com/1217395): DCHECK failure // "chrome://memory-internals", "chrome://net-export", - "chrome://net-internals", - "chrome://network-error", + // "chrome://net-internals", + // "chrome://network-error", "chrome://network-errors", "chrome://new-tab-page", "chrome://newtab", @@ -258,7 +295,7 @@ "chrome://policy", "chrome://predictors", "chrome://prefs-internals", - "chrome://print", + // "chrome://print", "chrome://process-internals", "chrome://quota-internals", "chrome://reset-password", @@ -266,7 +303,6 @@ "chrome://serviceworker-internals", "chrome://settings", // TODO(crbug.com/1115600): DCHECK failure when opening - // chrome://signin-dice-web-intercept. // "chrome://signin-dice-web-intercept", "chrome://signin-internals", "chrome://site-engagement", @@ -280,7 +316,7 @@ // navigating away cause DCHECK failure. // "chrome://tab-strip", "chrome://terms", - "chrome://tracing", + // "chrome://tracing", "chrome://translate-internals", "chrome://ukm", "chrome://usb-internals", @@ -298,49 +334,49 @@ "chrome://webapks", #endif #if BUILDFLAG(IS_CHROMEOS_ASH) - "chrome://account-manager-error", - "chrome://account-migration-welcome", - "chrome://add-supervision", + // "chrome://account-manager-error", + // "chrome://account-migration-welcome", + // "chrome://add-supervision", // TODO(crbug.com/1102129): DCHECK failure in // ArcGraphicsTracingHandler::ArcGraphicsTracingHandler. // "chrome://arc-graphics-tracing", // "chrome://arc-overview-tracing", - "chrome://assistant-optin", - "chrome://bluetooth-pairing", - "chrome://certificate-manager", - "chrome://crostini-credits", - "chrome://crostini-installer", + // "chrome://assistant-optin", + // "chrome://bluetooth-pairing", + // "chrome://certificate-manager", + // "chrome://crostini-credits", + // "chrome://crostini-installer", "chrome://cryptohome", "chrome://drive-internals", "chrome://family-link-user-internals", "chrome://help-app", - "chrome://internet-config-dialog", - "chrome://internet-detail-dialog", + // "chrome://internet-config-dialog", + // "chrome://internet-detail-dialog", "chrome://linux-proxy-config", - "chrome://multidevice-setup", - "chrome://network", - "chrome://os-credits", - "chrome://os-settings", + // "chrome://multidevice-setup", + // "chrome://network", + // "chrome://os-credits", + // "chrome://os-settings", "chrome://power", "chrome://projector", "chrome://proximity-auth/proximity_auth.html", - "chrome://set-time", + // "chrome://set-time", "chrome://slow", - "chrome://smb-credentials-dialog", - "chrome://smb-share-dialog", - "chrome://sys-internals", - "chrome-untrusted://terminal", + // "chrome://smb-credentials-dialog", + // "chrome://smb-share-dialog", + // "chrome://sys-internals", + // "chrome-untrusted://terminal", #endif #if !BUILDFLAG(IS_CHROMEOS) "chrome://apps", "chrome://browser-switch", - "chrome://welcome", + // "chrome://welcome", #endif #if !BUILDFLAG(IS_CHROMEOS_ASH) "chrome://signin-email-confirmation", #endif #if !BUILDFLAG(IS_CHROMEOS_LACROS) - "chrome://connectors-internals", + // "chrome://connectors-internals", #endif #if !BUILDFLAG(IS_MAC) "chrome://sandbox",
diff --git a/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chrome/browser/ui/webui/extensions/extensions_ui.cc index cbeb1486..960d4ae0 100644 --- a/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -134,6 +134,8 @@ {"keyboardShortcuts", IDS_EXTENSIONS_SIDEBAR_KEYBOARD_SHORTCUTS}, {"incognitoInfoWarning", IDS_EXTENSIONS_INCOGNITO_WARNING}, {"hostPermissionsDescription", IDS_EXTENSIONS_HOST_PERMISSIONS_DESCRIPTION}, + {"permissionsLearnMoreLabel", + IDS_EXTENSIONS_PERMISSIONS_LEARN_MORE_A11Y_LABEL}, {"hostPermissionsEdit", IDS_EXTENSIONS_HOST_PERMISSIONS_EDIT}, {"hostPermissionsHeading", IDS_EXTENSIONS_ITEM_HOST_PERMISSIONS_HEADING}, {"newHostPermissionsHeading", IDS_EXTENSIONS_NEW_HOST_PERMISSIONS_HEADING},
diff --git a/chrome/browser/ui/webui/management/management_ui.cc b/chrome/browser/ui/webui/management/management_ui.cc index 58028f6..ed4a46c1 100644 --- a/chrome/browser/ui/webui/management/management_ui.cc +++ b/chrome/browser/ui/webui/management/management_ui.cc
@@ -49,8 +49,6 @@ content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIManagementHost); - source->DisableTrustedTypesCSP(); - source->AddString("pageSubtitle", ManagementUI::GetManagementPageSubtitle(profile));
diff --git a/chrome/browser/ui/webui/realbox/realbox_handler.cc b/chrome/browser/ui/webui/realbox/realbox_handler.cc index 53dc183..f094186 100644 --- a/chrome/browser/ui/webui/realbox/realbox_handler.cc +++ b/chrome/browser/ui/webui/realbox/realbox_handler.cc
@@ -790,9 +790,6 @@ bool default_match_changed) { DCHECK(controller == autocomplete_controller_.get()); - // Prepend missing tail suggestion prefixes in results, if present. - autocomplete_controller_->SetTailSuggestCommonPrefixes(); - page_->AutocompleteResultChanged(CreateAutocompleteResult( autocomplete_controller_->input().text(), autocomplete_controller_->result(),
diff --git a/chrome/browser/ui/webui/reset_password/reset_password_ui.cc b/chrome/browser/ui/webui/reset_password/reset_password_ui.cc index ac92c50..6fd6b781c 100644 --- a/chrome/browser/ui/webui/reset_password/reset_password_ui.cc +++ b/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
@@ -15,6 +15,7 @@ #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h" +#include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "components/safe_browsing/content/browser/password_protection/password_protection_service.h" @@ -118,7 +119,7 @@ password_type_(GetPasswordType(web_ui->GetWebContents())) { std::unique_ptr<content::WebUIDataSource> html_source( content::WebUIDataSource::Create(chrome::kChromeUIResetPasswordHost)); - html_source->DisableTrustedTypesCSP(); + webui::EnableTrustedTypesCSP(html_source.get()); html_source->AddResourcePath("reset_password.js", IDR_RESET_PASSWORD_JS); html_source->AddResourcePath("reset_password.mojom-webui.js", IDR_RESET_PASSWORD_MOJOM_WEBUI_JS);
diff --git a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc index 187396e..99e2c449 100644 --- a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc +++ b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc
@@ -719,6 +719,18 @@ IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_LINK_TITLE}, {"selectToSpeakOptionsHighlightDescription", IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_DESCRIPTION}, + {"selectToSpeakOptionsHighlightColorDescription", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_DESCRIPTION}, + {"selectToSpeakOptionsHighlightColorBlue", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_BLUE}, + {"selectToSpeakOptionsHighlightColorOrange", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_ORANGE}, + {"selectToSpeakOptionsHighlightColorYellow", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_YELLOW}, + {"selectToSpeakOptionsHighlightColorGreen", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_GREEN}, + {"selectToSpeakOptionsHighlightColorPink", + IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_HIGHLIGHT_COLOR_PINK}, {"selectToSpeakOptionsBackgroundShadingDescription", IDS_SETTINGS_ACCESSIBILITY_SELECT_TO_SPEAK_BACKGROUND_SHADING_DESCRIPTION}, {"selectToSpeakOptionsNavigationControlsDescription",
diff --git a/chrome/browser/ui/webui/webui_gallery/webui_gallery_ui.cc b/chrome/browser/ui/webui/webui_gallery/webui_gallery_ui.cc index 0379d49..e3f0cf9 100644 --- a/chrome/browser/ui/webui/webui_gallery/webui_gallery_ui.cc +++ b/chrome/browser/ui/webui/webui_gallery/webui_gallery_ui.cc
@@ -25,7 +25,6 @@ IDR_WEBUI_GALLERY_WEBUI_GALLERY_HTML); webui::EnableTrustedTypesCSP(source); - source->DisableTrustedTypesCSP(); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::FrameSrc, "frame-src 'self';"); source->OverrideContentSecurityPolicy(
diff --git a/chrome/browser/ui/webui/webui_js_error/webui_js_error_ui.cc b/chrome/browser/ui/webui/webui_js_error/webui_js_error_ui.cc index e018d93..3e1a031c 100644 --- a/chrome/browser/ui/webui/webui_js_error/webui_js_error_ui.cc +++ b/chrome/browser/ui/webui/webui_js_error/webui_js_error_ui.cc
@@ -40,6 +40,7 @@ source, base::make_span(kWebuiJsErrorResources, kWebuiJsErrorResourcesSize), IDR_WEBUI_JS_ERROR_WEBUI_JS_ERROR_HTML); + webui::EnableTrustedTypesCSP(source); Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, source); }
diff --git a/chrome/browser/web_applications/isolated_web_apps/install_isolated_web_app_from_command_line.cc b/chrome/browser/web_applications/isolated_web_apps/install_isolated_web_app_from_command_line.cc index d8cd41f..f35912cf 100644 --- a/chrome/browser/web_applications/isolated_web_apps/install_isolated_web_app_from_command_line.cc +++ b/chrome/browser/web_applications/isolated_web_apps/install_isolated_web_app_from_command_line.cc
@@ -98,7 +98,7 @@ return base::unexpected( base::StrCat({"Invalid path provided to --", switches::kInstallIsolatedWebAppFromFile, " flag: '", - absolute_path.AsUTF8Unsafe(), "'"})); + switch_value.AsUTF8Unsafe(), "'"})); } return IsolationData{IsolationData::DevModeBundle{.path = absolute_path}};
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index b2b3aa25..598a6c5f4 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1669118022-67e39f4e393a301accb76a9b7ae9c41e67f30d4a.profdata +chrome-linux-main-1669161596-fc302c86baaad9bb4bf67c0b6d4d88fe7f012eb2.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 2ae7006f..eb849f95 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1669118022-8c0271846be2d9e7271cc73ef25b824ae537909d.profdata +chrome-mac-arm-main-1669161596-b7715982c634ef72c4403e6c7fa40f3eecb672e4.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index af3cc6e..8f5ea51 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1669139889-aedfce4c631058bfa133fc19f996331b8d857528.profdata +chrome-mac-main-1669161596-847b0c6f3615419a186f2f290b8e1cc51712a20f.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 2a4fa72a..67bde76 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1669118022-7d733e0712cb7443c62cc67d4bb74a8b7c02b7a6.profdata +chrome-win32-main-1669161596-98e628ef068411f941f2279cf1c7d82542b3c16e.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 14248f73..e5859eca 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1669129049-07cf842809d14c8c9a373e35549016b5d65d5630.profdata +chrome-win64-main-1669161596-803b94bdcc5ffc5a28bfd6cb68e18f21712c5929.profdata
diff --git a/chrome/chrome_elf/hook_util/hook_util.cc b/chrome/chrome_elf/hook_util/hook_util.cc index 207f93c..faed9bf 100644 --- a/chrome/chrome_elf/hook_util/hook_util.cc +++ b/chrome/chrome_elf/hook_util/hook_util.cc
@@ -11,7 +11,6 @@ #include "sandbox/win/src/interception_internal.h" #include "sandbox/win/src/internal_types.h" #include "sandbox/win/src/sandbox_utils.h" -#include "sandbox/win/src/service_resolver.h" namespace { @@ -199,43 +198,6 @@ namespace elf_hook { //------------------------------------------------------------------------------ -// System Service hooking support -//------------------------------------------------------------------------------ - -sandbox::ServiceResolverThunk* HookSystemService(bool relaxed) { - // Create a thunk via the appropriate ServiceResolver instance. - sandbox::ServiceResolverThunk* thunk = nullptr; - - // No hooking on unsupported OS versions. - if (!::IsWindows7OrGreater()) - return thunk; - - // Pseudo-handle, no need to close. - HANDLE current_process = ::GetCurrentProcess(); - -#if defined(_WIN64) - // ServiceResolverThunk can handle all the formats in 64-bit (instead only - // handling one like it does in 32-bit versions). - thunk = new sandbox::ServiceResolverThunk(current_process, relaxed); -#else - if (nt::IsCurrentProcWow64()) { - if (::IsWindows10OrGreater()) - thunk = new sandbox::Wow64W10ResolverThunk(current_process, relaxed); - else if (::IsWindows8OrGreater()) - thunk = new sandbox::Wow64W8ResolverThunk(current_process, relaxed); - else - thunk = new sandbox::Wow64ResolverThunk(current_process, relaxed); - } else if (::IsWindows8OrGreater()) { - thunk = new sandbox::Win8ResolverThunk(current_process, relaxed); - } else { - thunk = new sandbox::ServiceResolverThunk(current_process, relaxed); - } -#endif - - return thunk; -} - -//------------------------------------------------------------------------------ // Import Address Table hooking support //------------------------------------------------------------------------------
diff --git a/chrome/chrome_elf/hook_util/hook_util.h b/chrome/chrome_elf/hook_util/hook_util.h index 687042e..9070b9d9 100644 --- a/chrome/chrome_elf/hook_util/hook_util.h +++ b/chrome/chrome_elf/hook_util/hook_util.h
@@ -7,21 +7,9 @@ #include <windows.h> -namespace sandbox { -class ServiceResolverThunk; -} - namespace elf_hook { //------------------------------------------------------------------------------ -// System Service hooking support -//------------------------------------------------------------------------------ - -// Creates a |ServiceResolverThunk| based on the OS version. Ownership of the -// resulting thunk is passed to the caller. -sandbox::ServiceResolverThunk* HookSystemService(bool relaxed); - -//------------------------------------------------------------------------------ // Import Address Table hooking support //------------------------------------------------------------------------------ class IATHook {
diff --git a/chrome/chrome_elf/third_party_dlls/hook.cc b/chrome/chrome_elf/third_party_dlls/hook.cc index 6501e3b8..fd7e38c 100644 --- a/chrome/chrome_elf/third_party_dlls/hook.cc +++ b/chrome/chrome_elf/third_party_dlls/hook.cc
@@ -6,7 +6,6 @@ #include <atomic> #include <limits> -#include <memory> #include <assert.h> @@ -416,13 +415,10 @@ return ThirdPartyStatus::kHookInitImportsFailure; // Prep system-service thunk via the appropriate ServiceResolver instance. - std::unique_ptr<sandbox::ServiceResolverThunk> thunk( - elf_hook::HookSystemService(false)); - if (!thunk) - return ThirdPartyStatus::kHookUnsupportedOs; + sandbox::ServiceResolverThunk thunk(::GetCurrentProcess(), /*relaxed=*/false); // Set target process to self. - thunk->AllowLocalPatches(); + thunk.AllowLocalPatches(); // Mark the thunk storage as readable and writeable, since we // are ready to write to it now. @@ -440,10 +436,10 @@ // Setup() applies the system-service patch, and stores a copy of the original // system service coded in |thunk_storage|. ntstatus = - thunk->Setup(::GetModuleHandle(sandbox::kNtdllName), - reinterpret_cast<void*>(&__ImageBase), "NtMapViewOfSection", - nullptr, reinterpret_cast<void*>(&NewNtMapViewOfSection64), - thunk_storage, sizeof(sandbox::ThunkData), nullptr); + thunk.Setup(::GetModuleHandle(sandbox::kNtdllName), + reinterpret_cast<void*>(&__ImageBase), "NtMapViewOfSection", + nullptr, reinterpret_cast<void*>(&NewNtMapViewOfSection64), + thunk_storage, sizeof(sandbox::ThunkData), nullptr); // Keep a pointer to the original system-service code, which is now in // |thunk_storage|. Use this pointer for passing off execution from new shim. @@ -460,10 +456,10 @@ } #else // x86 ntstatus = - thunk->Setup(::GetModuleHandle(sandbox::kNtdllName), - reinterpret_cast<void*>(&__ImageBase), "NtMapViewOfSection", - nullptr, reinterpret_cast<void*>(&NewNtMapViewOfSection), - thunk_storage, sizeof(sandbox::ThunkData), nullptr); + thunk.Setup(::GetModuleHandle(sandbox::kNtdllName), + reinterpret_cast<void*>(&__ImageBase), "NtMapViewOfSection", + nullptr, reinterpret_cast<void*>(&NewNtMapViewOfSection), + thunk_storage, sizeof(sandbox::ThunkData), nullptr); #endif // defined(_WIN64) if (!NT_SUCCESS(ntstatus)) {
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index dc6fcbf..d94b606d 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -52,6 +52,12 @@ #endif #if BUILDFLAG(IS_CHROMEOS_ASH) +BASE_FEATURE(kAppDiscoveryForOobe, + "AppDiscoveryForOobe", + base::FEATURE_ENABLED_BY_DEFAULT); +#endif + +#if BUILDFLAG(IS_CHROMEOS_ASH) BASE_FEATURE(kAppManagementAppDetails, "AppManagementAppDetails", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index d2d5bd67..ee6579e 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -56,6 +56,10 @@ #endif #if BUILDFLAG(IS_CHROMEOS_ASH) +COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kAppDiscoveryForOobe); +#endif + +#if BUILDFLAG(IS_CHROMEOS_ASH) COMPONENT_EXPORT(CHROME_FEATURES) BASE_DECLARE_FEATURE(kAppManagementAppDetails); #endif
diff --git a/chrome/common/media/cdm_host_file_path.cc b/chrome/common/media/cdm_host_file_path.cc index 368d42d..245d7c8 100644 --- a/chrome/common/media/cdm_host_file_path.cc +++ b/chrome/common/media/cdm_host_file_path.cc
@@ -49,17 +49,16 @@ // kBrowserProcessExecutableName (e.g. for a local build of Chrome). // DIR_ASSETS sorts this out for us. base::FilePath chrome_assets_dir; - CHECK(base::PathService::Get(base::DIR_ASSETS, &chrome_assets_dir)); // Find where kBrowserProcessExecutableName is installed. Signature file is - // in the assets directory. - base::FilePath chrome_exe; - CHECK(base::PathService::Get(base::FILE_EXE, &chrome_exe)); - DCHECK(base::FilePath::CompareEqualIgnoreCase( - chrome::kBrowserProcessExecutableName, chrome_exe.BaseName().value())) - << "Filename returned by FILE_EXE '" << chrome_exe.BaseName().value() - << "' does not match kBrowserProcessExecutableName '" - << chrome::kBrowserProcessExecutableName << "'."; + // in the assets directory. FILE_EXE may not be kBrowserProcessExecutableName, + // e.g. browser_tests.exe, which is fine since we don't verify those + // signatures in tests. + base::FilePath dir_exe; + CHECK(base::PathService::Get(base::DIR_EXE, &dir_exe)); + base::FilePath chrome_exe = + dir_exe.DirName().Append(chrome::kBrowserProcessExecutableName); + CHECK(base::PathService::Get(base::DIR_ASSETS, &chrome_assets_dir)); const auto chrome_exe_sig = GetSigFilePath( chrome_assets_dir.Append(chrome::kBrowserProcessExecutableName)); DVLOG(2) << __func__ << ":" << chrome_exe.value() << ", signature file "
diff --git a/chrome/services/speech/cros_speech_recognition_recognizer_impl.cc b/chrome/services/speech/cros_speech_recognition_recognizer_impl.cc index 9297148..146486b 100644 --- a/chrome/services/speech/cros_speech_recognition_recognizer_impl.cc +++ b/chrome/services/speech/cros_speech_recognition_recognizer_impl.cc
@@ -4,6 +4,9 @@ #include "chrome/services/speech/cros_speech_recognition_recognizer_impl.h" +#include <string> + +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "chrome/services/speech/soda/cros_soda_client.h" #include "google_apis/google_api_keys.h" @@ -44,10 +47,12 @@ mojo::PendingRemote<media::mojom::SpeechRecognitionRecognizerClient> remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path) { + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) { mojo::MakeSelfOwnedReceiver( std::make_unique<CrosSpeechRecognitionRecognizerImpl>( - std::move(remote), std::move(options), binary_path, config_path), + std::move(remote), std::move(options), binary_path, config_paths, + primary_language_name), std::move(receiver)); } CrosSpeechRecognitionRecognizerImpl::~CrosSpeechRecognitionRecognizerImpl() = @@ -57,13 +62,14 @@ mojo::PendingRemote<media::mojom::SpeechRecognitionRecognizerClient> remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path) + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) : SpeechRecognitionRecognizerImpl(std::move(remote), std::move(options), binary_path, - config_path), - binary_path_(binary_path), - languagepack_path_(config_path) { + config_paths, + primary_language_name), + binary_path_(binary_path) { cros_soda_client_ = std::make_unique<soda::CrosSodaClient>(); } @@ -92,7 +98,7 @@ config->channel_count = channel_count; config->sample_rate = sample_rate; config->api_key = google_apis::GetSodaAPIKey(); - config->language_dlc_path = languagepack_path_.value(); + config->language_dlc_path = config_paths()[primary_language_name()].value(); config->library_dlc_path = binary_path_.value(); config->recognition_mode = GetSodaSpeechRecognitionMode(options_->recognition_mode);
diff --git a/chrome/services/speech/cros_speech_recognition_recognizer_impl.h b/chrome/services/speech/cros_speech_recognition_recognizer_impl.h index 83234c5..b36be427 100644 --- a/chrome/services/speech/cros_speech_recognition_recognizer_impl.h +++ b/chrome/services/speech/cros_speech_recognition_recognizer_impl.h
@@ -6,7 +6,9 @@ #define CHROME_SERVICES_SPEECH_CROS_SPEECH_RECOGNITION_RECOGNIZER_IMPL_H_ #include <memory> +#include <string> +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "chrome/services/speech/speech_recognition_recognizer_impl.h" @@ -31,7 +33,8 @@ remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path); + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name); ~CrosSpeechRecognitionRecognizerImpl() override; static void Create( @@ -40,7 +43,8 @@ remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path); + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name); // SpeechRecognitionRecognizerImpl: void SendAudioToSpeechRecognitionServiceInternal( @@ -51,8 +55,7 @@ private: std::unique_ptr<soda::CrosSodaClient> cros_soda_client_; - const base::FilePath binary_path_, languagepack_path_; - + const base::FilePath binary_path_; base::WeakPtrFactory<CrosSpeechRecognitionRecognizerImpl> weak_factory_{this}; }; } // namespace speech
diff --git a/chrome/services/speech/speech_recognition_recognizer_impl.cc b/chrome/services/speech/speech_recognition_recognizer_impl.cc index f52b6b4..f6f474c8 100644 --- a/chrome/services/speech/speech_recognition_recognizer_impl.cc +++ b/chrome/services/speech/speech_recognition_recognizer_impl.cc
@@ -8,10 +8,12 @@ #include <utility> #include "base/bind.h" +#include "base/containers/flat_map.h" #include "base/containers/span.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/metrics/histogram_functions.h" +#include "base/strings/string_util.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_runner.h" #include "base/task/task_traits.h" @@ -128,10 +130,12 @@ mojo::PendingRemote<media::mojom::SpeechRecognitionRecognizerClient> remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path) { + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) { mojo::MakeSelfOwnedReceiver( std::make_unique<SpeechRecognitionRecognizerImpl>( - std::move(remote), std::move(options), binary_path, config_path), + std::move(remote), std::move(options), binary_path, config_paths, + primary_language_name), std::move(receiver)); } @@ -176,10 +180,12 @@ mojo::PendingRemote<media::mojom::SpeechRecognitionRecognizerClient> remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path) + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) : options_(std::move(options)), client_remote_(std::move(remote)), - config_path_(config_path) { + config_paths_(config_paths), + primary_language_name_(primary_language_name) { recognition_event_callback_ = media::BindToCurrentLoop( base::BindRepeating(&SpeechRecognitionRecognizerImpl::OnRecognitionEvent, weak_factory_.GetWeakPtr())); @@ -293,7 +299,6 @@ } CHECK(soda_client_); - DCHECK(base::PathExists(config_path_)); if (!soda_client_->IsInitialized() || soda_client_->DidAudioPropertyChange(sample_rate_, channel_count_)) { ResetSoda(); @@ -311,9 +316,11 @@ return; // Only reset SODA if the language changed. - LanguageCode language_code = language_component_config.value().language_code; - if (language_code == language_ || language_code == LanguageCode::kNone) + if (language_component_config.value().language_name == + primary_language_name_ || + language_component_config.value().language_code == LanguageCode::kNone) { return; + } if (!task_runner_) { task_runner_ = base::ThreadPool::CreateSequencedTaskRunner( @@ -338,16 +345,16 @@ config_file_path), base::BindOnce(&SpeechRecognitionRecognizerImpl::ResetSodaWithNewLanguage, weak_factory_.GetWeakPtr(), config_file_path, - language_code)); + language_component_config.value().language_name)); } void SpeechRecognitionRecognizerImpl::ResetSodaWithNewLanguage( base::FilePath config_path, - speech::LanguageCode language_code, + std::string language_name, bool config_exists) { if (config_exists) { - config_path_ = config_path; - language_ = language_code; + config_paths_[language_name] = config_path; + primary_language_name_ = language_name; ResetSoda(); } } @@ -379,7 +386,8 @@ // to determine the appropriate language pack path. Note that // SodaInstaller::GetLanguagePath() is not implemented outside of Chrome OS, // and options_->language is not set for Live Caption. - std::string language_pack_directory = config_path_.AsUTF8Unsafe(); + std::string language_pack_directory = + config_paths_[primary_language_name_].AsUTF8Unsafe(); // Initialize the SODA instance with the serialized config. soda::chrome::ExtendedSodaConfigMsg config_msg; @@ -394,6 +402,18 @@ config_msg.set_enable_formatting(options_->enable_formatting); config_msg.set_enable_speaker_change_detection( base::FeatureList::IsEnabled(media::kSpeakerChangeDetection)); + if (base::FeatureList::IsEnabled(media::kLiveCaptionMultiLanguage) && + config_paths_.size() > 0) { + auto* multilang_config = config_msg.mutable_multilang_config(); + multilang_config->set_rewind_when_switching_language(true); + auto& multilang_language_pack_directory = + *(multilang_config->mutable_multilang_language_pack_directory()); + for (const auto& config : config_paths_) { + multilang_language_pack_directory[base::ToLowerASCII(config.first)] = + config.second.AsUTF8Unsafe(); + } + } + auto serialized = config_msg.SerializeAsString(); SerializedSodaConfig config;
diff --git a/chrome/services/speech/speech_recognition_recognizer_impl.h b/chrome/services/speech/speech_recognition_recognizer_impl.h index 473c3b2a..c317ad86 100644 --- a/chrome/services/speech/speech_recognition_recognizer_impl.h +++ b/chrome/services/speech/speech_recognition_recognizer_impl.h
@@ -8,6 +8,7 @@ #include <memory> #include <string> +#include "base/containers/flat_map.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "chrome/services/speech/audio_source_consumer.h" @@ -40,7 +41,8 @@ remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path); + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name); SpeechRecognitionRecognizerImpl(const SpeechRecognitionRecognizerImpl&) = delete; @@ -58,7 +60,8 @@ remote, media::mojom::SpeechRecognitionOptionsPtr options, const base::FilePath& binary_path, - const base::FilePath& config_path); + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name); static bool IsMultichannelSupported(); @@ -104,13 +107,18 @@ void OnRecognitionStoppedCallback(); + base::flat_map<std::string, base::FilePath> config_paths() const { + return config_paths_; + } + std::string primary_language_name() const { return primary_language_name_; } + media::mojom::SpeechRecognitionOptionsPtr options_; private: void OnLanguageChanged(const std::string& language) final; void ResetSodaWithNewLanguage(base::FilePath config_path, - speech::LanguageCode language_code, + std::string language_name, bool config_exists); void RecordDuration(); @@ -140,10 +148,10 @@ OnSpeechRecognitionStoppedCallback speech_recognition_stopped_callback_; - base::FilePath config_path_; + base::flat_map<std::string, base::FilePath> config_paths_; + std::string primary_language_name_; int sample_rate_ = 0; int channel_count_ = 0; - LanguageCode language_ = LanguageCode::kNone; base::TimeDelta caption_bubble_visible_duration_; base::TimeDelta caption_bubble_hidden_duration_;
diff --git a/chrome/services/speech/speech_recognition_service_impl.cc b/chrome/services/speech/speech_recognition_service_impl.cc index b7478dd..790eea1 100644 --- a/chrome/services/speech/speech_recognition_service_impl.cc +++ b/chrome/services/speech/speech_recognition_service_impl.cc
@@ -4,6 +4,9 @@ #include "chrome/services/speech/speech_recognition_service_impl.h" +#include <string> + +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/memory/weak_ptr.h" @@ -43,11 +46,13 @@ speech_recognition_contexts_.Add(this, std::move(context)); } -void SpeechRecognitionServiceImpl::SetSodaPath( +void SpeechRecognitionServiceImpl::SetSodaPaths( const base::FilePath& binary_path, - const base::FilePath& config_path) { + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) { binary_path_ = binary_path; - config_path_ = config_path; + config_paths_ = config_paths; + primary_language_name_ = primary_language_name; } void SpeechRecognitionServiceImpl::BindRecognizer( @@ -66,15 +71,15 @@ // Destroy the speech recognition service if the SODA files haven't been // downloaded yet. - if (!base::PathExists(binary_path_) || !base::PathExists(config_path_)) { + if (!FilePathsExist()) { speech_recognition_contexts_.Clear(); receiver_.reset(); return; } - SpeechRecognitionRecognizerImpl::Create(std::move(receiver), - std::move(client), std::move(options), - binary_path_, config_path_); + SpeechRecognitionRecognizerImpl::Create( + std::move(receiver), std::move(client), std::move(options), binary_path_, + config_paths_, primary_language_name_); std::move(callback).Run( SpeechRecognitionRecognizerImpl::IsMultichannelSupported()); } @@ -96,7 +101,7 @@ // Destroy the speech recognition service if the SODA files haven't been // downloaded yet. - if (!base::PathExists(binary_path_) || !base::PathExists(config_path_)) { + if (!FilePathsExist()) { speech_recognition_contexts_.Clear(); receiver_.reset(); return; @@ -106,9 +111,22 @@ AudioSourceFetcherImpl::Create( std::move(fetcher_receiver), std::make_unique<SpeechRecognitionRecognizerImpl>( - std::move(client), std::move(options), binary_path_, config_path_), + std::move(client), std::move(options), binary_path_, config_paths_, + primary_language_name_), is_multi_channel_supported, is_server_based); std::move(callback).Run(is_multi_channel_supported); } +bool SpeechRecognitionServiceImpl::FilePathsExist() { + if (!base::PathExists(binary_path_)) + return false; + + for (const auto& config : config_paths_) { + if (!base::PathExists(config.second)) + return false; + } + + return true; +} + } // namespace speech
diff --git a/chrome/services/speech/speech_recognition_service_impl.h b/chrome/services/speech/speech_recognition_service_impl.h index 672bc55..685525b 100644 --- a/chrome/services/speech/speech_recognition_service_impl.h +++ b/chrome/services/speech/speech_recognition_service_impl.h
@@ -5,6 +5,9 @@ #ifndef CHROME_SERVICES_SPEECH_SPEECH_RECOGNITION_SERVICE_IMPL_H_ #define CHROME_SERVICES_SPEECH_SPEECH_RECOGNITION_SERVICE_IMPL_H_ +#include <string> + +#include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "media/mojo/mojom/speech_recognition.mojom.h" @@ -38,8 +41,10 @@ void BindAudioSourceSpeechRecognitionContext( mojo::PendingReceiver<media::mojom::AudioSourceSpeechRecognitionContext> context) override; - void SetSodaPath(const base::FilePath& binary_path, - const base::FilePath& config_path) override; + void SetSodaPaths( + const base::FilePath& binary_path, + const base::flat_map<std::string, base::FilePath>& config_paths, + const std::string& primary_language_name) override; // media::mojom::SpeechRecognitionContext: void BindRecognizer( @@ -58,6 +63,9 @@ BindAudioSourceFetcherCallback callback) override; protected: + // Returns whether the binary and config paths exist. + bool FilePathsExist(); + mojo::Receiver<media::mojom::SpeechRecognitionService> receiver_; // The sets of receivers used to receive messages from the clients. @@ -67,7 +75,8 @@ audio_source_speech_recognition_contexts_; base::FilePath binary_path_ = base::FilePath(); - base::FilePath config_path_ = base::FilePath(); + base::flat_map<std::string, base::FilePath> config_paths_; + std::string primary_language_name_; base::WeakPtrFactory<SpeechRecognitionServiceImpl> weak_factory_{this}; };
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/tabmodel/MockTabCreator.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/tabmodel/MockTabCreator.java index 9792fed..f657f44f 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/tabmodel/MockTabCreator.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/tabmodel/MockTabCreator.java
@@ -48,13 +48,19 @@ @Override public Tab createNewTab(LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent) { + return createNewTab(loadUrlParams, type, parent, TabModel.INVALID_TAB_INDEX); + } + + @Override + public Tab createNewTab( + LoadUrlParams loadUrlParams, @TabLaunchType int type, Tab parent, int position) { Tab tab = new MockTab(0, mIsIncognito, TabLaunchType.FROM_LINK); tab.getUserDataHost().setUserData(MockTabAttributes.class, new MockTabAttributes(false)); if (loadUrlParams != null) { ((TabImpl) tab).initialize(null, null, loadUrlParams, null, null, false, null); } mSelector.getModel(mIsIncognito) - .addTab(tab, TabModel.INVALID_TAB_INDEX, type, TabCreationState.LIVE_IN_FOREGROUND); + .addTab(tab, position, type, TabCreationState.LIVE_IN_FOREGROUND); storeTabInfo(null, tab.getId()); return tab; } @@ -91,4 +97,4 @@ created.put(id, state); callback.notifyCalled(); } -} \ No newline at end of file +}
diff --git a/chrome/test/data/android/view_transition.html b/chrome/test/data/android/view_transition.html deleted file mode 100644 index 080e2fbb..0000000 --- a/chrome/test/data/android/view_transition.html +++ /dev/null
@@ -1,134 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <script> - const params = new URLSearchParams(window.location.search); - let metaTagContent = 'width=device-width,minimum-scale=1'; - if (params.has('resizes-content')) - metaTagContent += ',interactive-widget=resizes-content'; - else if (params.has('resizes-visual')) - metaTagContent += ',interactive-widget=resizes-visual'; - else if (params.has('overlays-content')) { - metaTagContent += ',interactive-widget=overlays-content'; - } - - let meta = document.createElement('meta'); - meta.name = 'viewport'; - meta.content = metaTagContent; - document.head.appendChild(meta); - - if (params.has('new')) - document.documentElement.classList.add('new'); - else if (params.has('old')) - document.documentElement.classList.add('old'); - </script> - <style> - input { - /* Invisible so that blinking cursor doesn't affect pixel tests */ - position: absolute; - top: 50px; - opacity: 0; - } - - #bottomfixed { - position: fixed; - left: 20px; - bottom: 10px; - width: 100px; - height: 30px; - background-color: coral; - view-transition-name: bottom; - contain: paint; - } - - #topfixed { - position: fixed; - left: 20px; - top: 10px; - width: 100px; - height: 30px; - background-color: dodgerblue; - view-transition-name: top; - contain: paint; - } - - #inflow { - position: absolute; - left: 100px; - top: 200px; - width: 100px; - height: 300px; - background-color: rebeccapurple; - } - - /* For live testing - if no class is set on the root use the regular but - * slow transition */ - ::view-transition-group(*), - ::view-transition-new(*), - ::view-transition-old(*) { - animation-duration: 5s; - } - - /* Step function and long duration means we'll simply keep the snapshots - * in their initial state for 30 seconds so the pixel test can take a - * screenshot reliably. */ - .old::view-transition-group(*), - .old::view-transition-new(*), - .old::view-transition-old(*) { - animation-duration: 30s; - animation-direction: normal; - animation-timing-function: steps(1, end); - } - - /* Reverse the direction if we're capturing the new state */ - .new::view-transition-group(*), - .new::view-transition-new(*), - .new::view-transition-old(*) { - animation-duration: 30s; - animation-direction: reverse; - animation-timing-function: steps(1, start); - } - </style> - <script> - let transition = null; - - // Allow tests to control when the transition starts. - let startTransitionAnimation = null; - let startPromise = new Promise(resolve => {startTransitionAnimation = resolve;}); - - // Allow tests to wait until the snapshot has been taken and is ready to - // start transitioning. - let readyToStartResolve = null; - let readyToStartPromise = new Promise(resolve => {readyToStartResolve = resolve;}); - - function updateDOM() { - document.getElementById("inflow").style.transform = "translateX(100px)"; - document.getElementById("bottomfixed").style.transform = "translateX(100px)"; - document.getElementById("topfixed").style.transform = "translateX(100px)"; - } - - function undoUpdateDOM() { - document.getElementById("inflow").style = ""; - document.getElementById("bottomfixed").style = ""; - document.getElementById("topfixed").style = ""; - } - - function createTransition() { - transition = document.startViewTransition(() => { - updateDOM(); - - readyToStartResolve(); - - return startPromise; - }); - - } - </script> - </head> - <body> - <input id="inputElement" type="text"> - <div id="inflow"></div> - <div id="bottomfixed"></div> - <div id="topfixed"></div> - </body> -</html>
diff --git a/chrome/test/data/webui/chromeos/diagnostics/input_card_test.js b/chrome/test/data/webui/chromeos/diagnostics/input_card_test.js index 6521f0d1..54cf761 100644 --- a/chrome/test/data/webui/chromeos/diagnostics/input_card_test.js +++ b/chrome/test/data/webui/chromeos/diagnostics/input_card_test.js
@@ -87,7 +87,7 @@ assertEquals( keyboards[0].name, elements[0].querySelector('.device-name').innerText); assertEquals( - 'Internal keyboard', + 'Built-in keyboard', elements[0].querySelector('.device-description').innerText); assertEquals( keyboards[1].name, elements[1].querySelector('.device-name').innerText);
diff --git a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js index f8a9ad5..356e312 100644 --- a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js +++ b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js
@@ -690,6 +690,10 @@ this.runMochaTest(extension_error_page_tests.TestNames.ErrorSelection); }); +TEST_F('CrExtensionsErrorPageTest', 'InvalidUrl', function() { + this.runMochaTest(extension_error_page_tests.TestNames.InvalidUrl); +}); + //////////////////////////////////////////////////////////////////////////////// // Extension Code Section Tests
diff --git a/chrome/test/data/webui/extensions/error_page_test.ts b/chrome/test/data/webui/extensions/error_page_test.ts index 65993f8..160f9f0d 100644 --- a/chrome/test/data/webui/extensions/error_page_test.ts +++ b/chrome/test/data/webui/extensions/error_page_test.ts
@@ -19,6 +19,7 @@ Layout: 'layout', CodeSection: 'code section', ErrorSelection: 'error selection', + InvalidUrl: 'invalid url', }, }; @@ -219,4 +220,22 @@ ironCollapses[1]!.querySelector<HTMLElement>( '.context-url')!.textContent!.trim()); }); + + // Tests that the element can still be shown with an invalid URL. Regression + // test for crbug.com/1257170, as without the fix, this test would simply + // crash when the page tries and fails to create a URL object. + test(extension_error_page_tests.TestNames.InvalidUrl, function() { + const newRuntimeError = Object.assign( + { + severity: chrome.developerPrivate.ErrorLevel.ERROR, + source: 'invalid_url', + }, + runtimeErrorBase); + // Replace the runtime error URL with something malformed, and check that + // the error is still displayed and opened. + errorPage.set('data.runtimeErrors', [newRuntimeError]); + flush(); + + assertEquals(extensionData.runtimeErrors[0], errorPage.getSelectedError()); + }); });
diff --git a/chrome/test/data/webui/settings/chromeos/select_to_speak_subpage_tests.js b/chrome/test/data/webui/settings/chromeos/select_to_speak_subpage_tests.js index 5081b36..cc905622 100644 --- a/chrome/test/data/webui/settings/chromeos/select_to_speak_subpage_tests.js +++ b/chrome/test/data/webui/settings/chromeos/select_to_speak_subpage_tests.js
@@ -6,6 +6,7 @@ import {CrSettingsPrefs, Router, routes} from 'chrome://os-settings/chromeos/os_settings.js'; import {assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; +import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; suite('SelectToSpeakSubpageTests', function() { /** @type {SettingsSelectToSpeakSubpageElement} */ @@ -65,4 +66,21 @@ page.getPref('settings.a11y.select_to_speak_navigation_controls'); assertFalse(navigationControlsPref.value); }); + + test('highlight color pref and dropdown synced', async function() { + // Make sure highlight color dropdown is blue, matching default pref state. + const highlightColorDropdown = + page.shadowRoot.querySelector('#highlightColorDropdown'); + await waitAfterNextRender(highlightColorDropdown); + const highlightColorSelectElement = + highlightColorDropdown.shadowRoot.querySelector('select'); + assertEquals('#5e9bff', highlightColorSelectElement.value); + + // Turn highlight color to orange, and verify pref is also orange. + highlightColorSelectElement.value = '#ffa13d'; + highlightColorSelectElement.dispatchEvent(new CustomEvent('change')); + const highlightColorPref = + page.getPref('settings.a11y.select_to_speak_highlight_color'); + assertEquals('#ffa13d', highlightColorPref.value); + }); });
diff --git a/chrome/test/interaction/webcontents_interaction_test_util.cc b/chrome/test/interaction/webcontents_interaction_test_util.cc index 6eae3339e..95282d8 100644 --- a/chrome/test/interaction/webcontents_interaction_test_util.cc +++ b/chrome/test/interaction/webcontents_interaction_test_util.cc
@@ -34,6 +34,7 @@ #include "chrome/browser/ui/views/frame/contents_web_view.h" #include "chrome/test/interaction/interaction_test_util_browser.h" #include "chrome/test/interaction/tracked_element_webcontents.h" +#include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -611,14 +612,12 @@ navigating_away_from_ = web_contents()->GetURL(); DiscardCurrentElement(); } - if (url.SchemeIs("chrome")) { - Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); - CHECK(browser); - NavigateParams navigate_params(browser, url, ui::PAGE_TRANSITION_TYPED); - navigate_params.disposition = WindowOpenDisposition::CURRENT_TAB; - auto navigate_result = Navigate(&navigate_params); - CHECK(navigate_result); + if (url.SchemeIs("chrome") || web_view_data_) { + // Secure pages and non-tab WebViews must be navigated via the controller. + content::NavigationController::LoadURLParams params(url); + CHECK(web_contents()->GetController().LoadURLWithParams(params)); } else { + // Regular web pages can be navigated directly. const bool result = content::BeginNavigateToURLFromRenderer(web_contents(), url); CHECK(result);
diff --git a/chrome/test/interaction/webcontents_interaction_test_util_browsertest.cc b/chrome/test/interaction/webcontents_interaction_test_util_browsertest.cc index 083fc2d..b6dfbce 100644 --- a/chrome/test/interaction/webcontents_interaction_test_util_browsertest.cc +++ b/chrome/test/interaction/webcontents_interaction_test_util_browsertest.cc
@@ -309,14 +309,12 @@ auto util = WebContentsInteractionTestUtil::ForExistingTabInBrowser( browser(), kWebContentsElementId); - // Load the first page and make sure we wait for the page transition. - util->LoadPage(url); - auto sequence = ui::InteractionSequence::Builder() .SetCompletedCallback(completed.Get()) .SetAbortedCallback(aborted.Get()) .SetContext(browser()->window()->GetElementContext()) + // Load the first page and make sure we wait for the page transition. .AddStep(ui::InteractionSequence::StepBuilder() .SetType(ui::InteractionSequence::StepType::kShown) .SetElementID(kWebContentsElementId) @@ -324,6 +322,17 @@ .SetStartCallback(base::BindLambdaForTesting( [&](ui::InteractionSequence* sequence, ui::TrackedElement* element) { + util->LoadPage(url); + })) + .Build()) + .AddStep(ui::InteractionSequence::StepBuilder() + .SetType(ui::InteractionSequence::StepType::kShown) + .SetElementID(kWebContentsElementId) + .SetMustRemainVisible(false) + .SetTransitionOnlyOnEvent(true) + .SetStartCallback(base::BindLambdaForTesting( + [&](ui::InteractionSequence* sequence, + ui::TrackedElement* element) { EXPECT_EQ(url, util->web_contents()->GetURL()); // Load the second page and wait for it to finish // loading.
diff --git a/chrome/updater/constants.cc b/chrome/updater/constants.cc index 57423a2..b9c42b79 100644 --- a/chrome/updater/constants.cc +++ b/chrome/updater/constants.cc
@@ -52,7 +52,7 @@ const char kAppIdSwitch[] = "app-id"; const char kAppVersionSwitch[] = "app-version"; const char kWakeSwitch[] = "wake"; -const char kWakeAllSwitch[] = "wakeall"; +const char kWakeAllSwitch[] = "wake-all"; const char kTagSwitch[] = "tag"; const char kInstallerDataSwitch[] = "installerdata";
diff --git a/chrome/updater/mac/setup/setup.mm b/chrome/updater/mac/setup/setup.mm index 24f34ba8..a37bb14 100644 --- a/chrome/updater/mac/setup/setup.mm +++ b/chrome/updater/mac/setup/setup.mm
@@ -169,7 +169,8 @@ [NSMutableArray<NSString*> array]; [program_arguments addObjectsFromArray:@[ base::SysUTF8ToNSString(updater_path.value()), - MakeProgramArgument(kWakeSwitch), MakeProgramArgument(kEnableLoggingSwitch) + MakeProgramArgument(kWakeAllSwitch), + MakeProgramArgument(kEnableLoggingSwitch) ]]; if (scope == UpdaterScope::kSystem) [program_arguments addObject:MakeProgramArgument(kSystemSwitch)]; @@ -371,9 +372,6 @@ "cause Gatekeeper to show a prompt to the user."; } - if (!CreateWakeLaunchdJobPlist(scope, updater_executable_path)) - return kErrorFailedToCreateWakeLaunchdJobPlist; - if (!CreateUpdateServiceInternalLaunchdJobPlist(scope, updater_executable_path)) return kErrorFailedToCreateUpdateServiceInternalLaunchdJobPlist; @@ -381,9 +379,6 @@ if (!StartUpdateServiceInternalVersionedLaunchdJob(scope)) return kErrorFailedToStartLaunchdUpdateServiceInternalJob; - if (!StartUpdateWakeVersionedLaunchdJob(scope)) - return kErrorFailedToStartLaunchdWakeJob; - return kErrorOk; } @@ -404,9 +399,15 @@ const base::FilePath updater_executable_path = dest_path->Append(GetExecutableRelativePath()); + if (!CreateWakeLaunchdJobPlist(scope, updater_executable_path)) + return kErrorFailedToCreateWakeLaunchdJobPlist; + if (!CreateUpdateServiceLaunchdJobPlist(scope, updater_executable_path)) return kErrorFailedToCreateUpdateServiceLaunchdJobPlist; + if (!StartUpdateWakeVersionedLaunchdJob(scope)) + return kErrorFailedToStartLaunchdWakeJob; + if (!StartLaunchdServiceJob(scope)) return kErrorFailedToStartLaunchdActiveServiceJob;
diff --git a/chrome/updater/mac/xpc_service_names.mm b/chrome/updater/mac/xpc_service_names.mm index 8fc25afb..7935bb097 100644 --- a/chrome/updater/mac/xpc_service_names.mm +++ b/chrome/updater/mac/xpc_service_names.mm
@@ -51,9 +51,9 @@ return scope == UpdaterScope::kSystem ? base::SysUTF8ToCFStringRef( base::StrCat({MAC_BUNDLE_IDENTIFIER_STRING ".wake.", - kUpdaterVersion, kSystemLevelKeyword})) - : base::SysUTF8ToCFStringRef(base::StrCat( - {MAC_BUNDLE_IDENTIFIER_STRING ".wake.", kUpdaterVersion})); + kSystemLevelKeyword})) + : base::SysUTF8ToCFStringRef( + base::StrCat({MAC_BUNDLE_IDENTIFIER_STRING ".wake"})); } base::ScopedCFTypeRef<CFStringRef> CopyUpdateServiceInternalLaunchdName(
diff --git a/chrome/updater/test/integration_test_commands.h b/chrome/updater/test/integration_test_commands.h index d22d1d1e..6071841 100644 --- a/chrome/updater/test/integration_test_commands.h +++ b/chrome/updater/test/integration_test_commands.h
@@ -64,6 +64,7 @@ virtual void ExpectAppVersion(const std::string& app_id, const base::Version& version) const = 0; virtual void RunWake(int exit_code) const = 0; + virtual void RunWakeAll() const = 0; virtual void RunWakeActive(int exit_code) const = 0; virtual void Update(const std::string& app_id, const std::string& install_data_index) const = 0;
diff --git a/chrome/updater/test/integration_test_commands_system.cc b/chrome/updater/test/integration_test_commands_system.cc index ef4886a..1e1e344 100644 --- a/chrome/updater/test/integration_test_commands_system.cc +++ b/chrome/updater/test/integration_test_commands_system.cc
@@ -172,6 +172,8 @@ {Param("exit_code", base::NumberToString(expected_exit_code))}); } + void RunWakeAll() const override { RunCommand("run_wake_all", {}); } + void RunWakeActive(int expected_exit_code) const override { RunCommand("run_wake_active", {Param("exit_code", base::NumberToString(expected_exit_code))});
diff --git a/chrome/updater/test/integration_test_commands_user.cc b/chrome/updater/test/integration_test_commands_user.cc index f1236da..453e1dda 100644 --- a/chrome/updater/test/integration_test_commands_user.cc +++ b/chrome/updater/test/integration_test_commands_user.cc
@@ -151,6 +151,10 @@ updater::test::RunWake(updater_scope_, exit_code); } + void RunWakeAll() const override { + updater::test::RunWakeAll(updater_scope_); + } + void RunWakeActive(int exit_code) const override { updater::test::RunWakeActive(updater_scope_, exit_code); }
diff --git a/chrome/updater/test/integration_tests.cc b/chrome/updater/test/integration_tests.cc index 8ddee0a..89d32c7 100644 --- a/chrome/updater/test/integration_tests.cc +++ b/chrome/updater/test/integration_tests.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" +#include "base/functional/callback_helpers.h" #include "base/logging.h" #include "base/memory/scoped_refptr.h" #include "base/numerics/checked_math.h" @@ -34,6 +35,7 @@ #include "chrome/updater/test/integration_tests_impl.h" #include "chrome/updater/test/server.h" #include "chrome/updater/test_scope.h" +#include "chrome/updater/unittest_util.h" #include "chrome/updater/update_service.h" #include "chrome/updater/updater_scope.h" #include "chrome/updater/updater_version.h" @@ -258,6 +260,8 @@ void RunWake(int exit_code) { test_commands_->RunWake(exit_code); } + void RunWakeAll() { test_commands_->RunWakeAll(); } + void RunWakeActive(int exit_code) { test_commands_->RunWakeActive(exit_code); } @@ -471,6 +475,21 @@ Uninstall(); } +TEST_F(IntegrationTest, SelfUpdateWithWakeAll) { + ScopedServer test_server(test_commands_); + Install(); + + base::Version next_version(base::StringPrintf("%s1", kUpdaterVersion)); + ExpectUpdateSequence(&test_server, kUpdaterAppId, "", + base::Version(kUpdaterVersion), next_version); + + RunWakeAll(); + EXPECT_TRUE(WaitForUpdaterExit()); + ExpectAppVersion(kUpdaterAppId, next_version); + + Uninstall(); +} + TEST_F(IntegrationTest, ReportsActive) { // A longer than usual timeout is needed for this test because the macOS // UpdateServiceInternal server takes at least 10 seconds to shut down after @@ -786,6 +805,12 @@ // Tests that installing and uninstalling an old version of the updater from // CIPD is possible. TEST_F(IntegrationTest, InstallLowerVersion) { +#if BUILDFLAG(IS_WIN) + updater::test::StartProcmonLogging(); + const base::ScopedClosureRunner stop_procmon_logging( + base::BindOnce(&updater::test::StopProcmonLogging)); +#endif // BUILDFLAG(IS_WIN) + ASSERT_NO_FATAL_FAILURE(SetupRealUpdaterLowerVersion()); ExpectVersionNotActive(kUpdaterVersion); Uninstall();
diff --git a/chrome/updater/test/integration_tests_helper.cc b/chrome/updater/test/integration_tests_helper.cc index 24cc4dac..4f37c72 100644 --- a/chrome/updater/test/integration_tests_helper.cc +++ b/chrome/updater/test/integration_tests_helper.cc
@@ -280,6 +280,7 @@ {"install", WithSystemScope(Wrap(&Install))}, {"print_log", WithSystemScope(Wrap(&PrintLog))}, {"run_wake", WithSwitch("exit_code", WithSystemScope(Wrap(&RunWake)))}, + {"run_wake_all", WithSystemScope(Wrap(&RunWakeAll))}, {"run_wake_active", WithSwitch("exit_code", WithSystemScope(Wrap(&RunWakeActive)))}, {"update",
diff --git a/chrome/updater/test/integration_tests_impl.cc b/chrome/updater/test/integration_tests_impl.cc index 29210dec..b085a35 100644 --- a/chrome/updater/test/integration_tests_impl.cc +++ b/chrome/updater/test/integration_tests_impl.cc
@@ -175,6 +175,22 @@ }); } +void RunUpdaterWithSwitch(const base::Version& version, + UpdaterScope scope, + const std::string& command, + int expected_exit_code) { + const absl::optional<base::FilePath> installed_executable_path = + GetVersionedInstallDirectory(scope, version) + ->Append(GetExecutableRelativePath()); + ASSERT_TRUE(installed_executable_path); + ASSERT_TRUE(base::PathExists(*installed_executable_path)); + base::CommandLine command_line(*installed_executable_path); + command_line.AppendSwitch(command); + int exit_code = -1; + ASSERT_TRUE(Run(scope, command_line, &exit_code)); + EXPECT_EQ(exit_code, expected_exit_code); +} + } // namespace void ExitTestMode(UpdaterScope scope) { @@ -248,13 +264,6 @@ } } -base::FilePath GetLogDestinationDir() { - // Fetch path to ${ISOLATED_OUTDIR} env var. - // ResultDB reads logs and test artifacts info from there. - const char* var = std::getenv("ISOLATED_OUTDIR"); - return var ? base::FilePath::FromUTF8Unsafe(var) : base::FilePath(); -} - // Copies the updater log file present in `src_dir` to a test-specific directory // name in Swarming/Isolate. Avoids overwriting the destination log file if // other instances of it exist in the destination directory. Swarming retries @@ -282,15 +291,13 @@ } void RunWake(UpdaterScope scope, int expected_exit_code) { - const absl::optional<base::FilePath> installed_executable_path = - GetInstalledExecutablePath(scope); - ASSERT_TRUE(installed_executable_path); - EXPECT_TRUE(base::PathExists(*installed_executable_path)); - base::CommandLine command_line(*installed_executable_path); - command_line.AppendSwitch(kWakeSwitch); - int exit_code = -1; - ASSERT_TRUE(Run(scope, command_line, &exit_code)); - EXPECT_EQ(exit_code, expected_exit_code); + RunUpdaterWithSwitch(base::Version(kUpdaterVersion), scope, kWakeSwitch, + expected_exit_code); +} + +void RunWakeAll(UpdaterScope scope) { + RunUpdaterWithSwitch(base::Version(kUpdaterVersion), scope, kWakeAllSwitch, + kErrorOk); } void RunWakeActive(UpdaterScope scope, int expected_exit_code) { @@ -309,13 +316,7 @@ ASSERT_TRUE(active_version.IsValid()); // Invoke the wake client of that version. - base::CommandLine command_line( - GetVersionedInstallDirectory(scope, active_version) - ->Append(GetExecutableRelativePath())); - command_line.AppendSwitch(kWakeSwitch); - int exit_code = -1; - ASSERT_TRUE(Run(scope, command_line, &exit_code)); - EXPECT_EQ(exit_code, expected_exit_code); + RunUpdaterWithSwitch(active_version, scope, kWakeSwitch, expected_exit_code); } void Update(UpdaterScope scope,
diff --git a/chrome/updater/test/integration_tests_impl.h b/chrome/updater/test/integration_tests_impl.h index b70bd4a2..061a92abc 100644 --- a/chrome/updater/test/integration_tests_impl.h +++ b/chrome/updater/test/integration_tests_impl.h
@@ -106,6 +106,10 @@ // `exit_code`. The server should exit a few seconds after. void RunWake(UpdaterScope scope, int exit_code); +// Runs the wake-all client and wait for it to exit. Assert that it exits with +// kErrorOk. The server should exit a few seconds after. +void RunWakeAll(UpdaterScope scope); + // As RunWake, but runs the wake client for whatever version of the server is // active, rather than kUpdaterVersion. void RunWakeActive(UpdaterScope scope, int exit_code);
diff --git a/chrome/updater/unittest_util.cc b/chrome/updater/unittest_util.cc index 04c13a7..b5f6b8d 100644 --- a/chrome/updater/unittest_util.cc +++ b/chrome/updater/unittest_util.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/base_paths.h" +#include "base/check.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" @@ -18,6 +19,7 @@ #include "base/process/process_iterator.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" #include "base/time/time.h" #include "chrome/updater/constants.h" #include "chrome/updater/policy/manager.h" @@ -89,6 +91,11 @@ return Local::DeleteDirsIfEmpty(file_path->DirName()); } +base::FilePath GetLogDestinationDir() { + const char* var = std::getenv("ISOLATED_OUTDIR"); + return var ? base::FilePath::FromUTF8Unsafe(var) : base::FilePath(); +} + #if BUILDFLAG(IS_WIN) void MaybeExcludePathsFromWindowsDefender() { constexpr char kTestLauncherExcludePathsFromWindowDefender[] = @@ -129,6 +136,47 @@ LOG_IF(ERROR, !process.IsValid()) << "Failed to disable Windows Defender: " << cmdline; } + +void StartProcmonLogging() { + base::FilePath dest_dir = GetLogDestinationDir(); + if (dest_dir.empty() || !base::PathExists(dest_dir)) { + LOG(ERROR) << "Cannot log, failed to get log destination dir"; + return; + } + + dest_dir = dest_dir.AppendASCII(GetTestName()); + CHECK(base::CreateDirectory(dest_dir)); + + base::Time::Exploded start_time; + base::Time::Now().LocalExplode(&start_time); + const std::wstring cmdline = base::StrCat( + {L"C:\\tools\\Procmon.exe /AcceptEula /BackingFile \"", + dest_dir + .AppendASCII(base::StringPrintf( + "%02d%02d%02d-%02d%02d%02d.PML", start_time.year, + start_time.month, start_time.day_of_month, start_time.hour, + start_time.minute, start_time.second)) + .value(), + L"\" /Nofilter /Quiet /externalcapture"}); + + base::LaunchOptions options; + options.start_hidden = true; + VLOG(1) << "Running: " << cmdline; + base::Process process = base::LaunchProcess(cmdline, options); + LOG_IF(ERROR, !process.IsValid()) << "Failed to run procmon: " << cmdline; +} + +void StopProcmonLogging() { + const std::wstring cmdline = L"C:\\tools\\Procmon.exe /Terminate"; + + base::LaunchOptions options; + options.start_hidden = true; + options.wait = true; + VLOG(1) << "Running: " << cmdline; + base::Process process = base::LaunchProcess(cmdline, options); + LOG_IF(ERROR, !process.IsValid()) << "Failed to stop procmon: " << cmdline; +} + #endif // BUILDFLAG(IS_WIN) } // namespace updater::test
diff --git a/chrome/updater/unittest_util.h b/chrome/updater/unittest_util.h index 4ab54676..0ab65db 100644 --- a/chrome/updater/unittest_util.h +++ b/chrome/updater/unittest_util.h
@@ -58,10 +58,18 @@ bool DeleteFileAndEmptyParentDirectories( const absl::optional<base::FilePath>& file_path); +// Fetches the path to the ${ISOLATED_OUTDIR} env var. +// ResultDB reads logs and test artifacts info from there. +base::FilePath GetLogDestinationDir(); + #if BUILDFLAG(IS_WIN) // Change Windows Defender settings to skip scanning the paths used by the // updater if test runs with the flag `exclude-paths-from-win-defender`. void MaybeExcludePathsFromWindowsDefender(); + +// Start and stop procmon.exe logging. +void StartProcmonLogging(); +void StopProcmonLogging(); #endif } // namespace updater::test
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java index 57ecf05f..9d2bf50 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java
@@ -24,6 +24,7 @@ import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; +import androidx.annotation.VisibleForTesting; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.chromium.base.BuildInfo; @@ -92,6 +93,9 @@ private final Controller<Unit> mIsTestingState = new Controller<>(); // Set at creation. Handles destroying SurfaceHelper. private final Controller<CastWebContentsSurfaceHelper> mSurfaceHelperState = new Controller<>(); + // Set when the activity has the surface available. + @VisibleForTesting + final Controller<Unit> mSurfaceAvailable = new Controller<>(); @Nullable private CastWebContentsSurfaceHelper mSurfaceHelper; @@ -123,7 +127,9 @@ (FrameLayout) findViewById(R.id.web_contents_container), CastSwitches.getSwitchValueColor( CastSwitches.CAST_APP_BACKGROUND_COLOR, Color.BLACK)), - (Uri uri) -> mIsFinishingState.set("Delayed teardown for URI: " + uri))); + (Uri uri) + -> mIsFinishingState.set("Delayed teardown for URI: " + uri), + mSurfaceAvailable)); })); mSurfaceHelperState.subscribe((CastWebContentsSurfaceHelper surfaceHelper) -> { @@ -156,6 +162,7 @@ sendVisibilityChanged(both.second, CastWebContentsIntentUtils.VISIBITY_TYPE_HIDDEN); }; }); + mStartedState.subscribe(Observers.onEnter(mSurfaceAvailable::set)); // Set a flag to exit sleep mode when this activity starts. mCreatedState.and(mGotIntentState) @@ -293,6 +300,8 @@ if (DEBUG) Log.d(TAG, "onUserLeaveHint"); if (canUsePictureInPicture() && mAllowPictureInPicture) { enterPictureInPictureMode(new PictureInPictureParams.Builder().build()); + } else { + mSurfaceAvailable.reset(); } }
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java index dc74ca6..0e0fbf6 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java
@@ -103,8 +103,8 @@ * @param webContentsView A Observer that displays incoming WebContents. * @param finishCallback Invoked to tell host to finish. */ - CastWebContentsSurfaceHelper( - Observer<WebContents> webContentsView, Consumer<Uri> finishCallback) { + CastWebContentsSurfaceHelper(Observer<WebContents> webContentsView, + Consumer<Uri> finishCallback, Observable<Unit> surfaceAvailable) { Handler handler = new Handler(); mMediaSessionGetter = @@ -162,6 +162,9 @@ // webContentsView is responsible for displaying each new WebContents. webContentsState.subscribe(webContentsView); + webContentsState.and(surfaceAvailable) + .map(Both::getFirst) + .subscribe(Observers.onExit(WebContents::tearDownDialogOverlays)); // Take audio focus when receiving new WebContents if not the remote control app. mStartParamsState.filter(params -> !params.isRemoteControlMode)
diff --git a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsActivityTest.java b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsActivityTest.java index 7a16ab03..09be535 100644 --- a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsActivityTest.java +++ b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsActivityTest.java
@@ -55,6 +55,9 @@ import org.robolectric.shadows.ShadowPackageManager; import org.chromium.base.ContextUtils; +import org.chromium.chromecast.base.Observer; +import org.chromium.chromecast.base.Scope; +import org.chromium.chromecast.base.Unit; import org.chromium.content_public.browser.WebContents; import org.chromium.testing.local.LocalRobolectricTestRunner; @@ -517,6 +520,21 @@ assertFalse(shadowActivity.getInPictureInPictureMode()); } + @Test + public void testSurfaceAvailable() { + Observer<Unit> observer = mock(Observer.class); + Scope scope = mock(Scope.class); + when(observer.open(any())).thenReturn(scope); + + mActivity.mSurfaceAvailable.subscribe(observer); + + mActivityLifecycle.create().start().resume(); + verify(observer).open(any()); + + mActivity.onUserLeaveHint(); + verify(scope).close(); + } + private IntentFilter filterFor(String action) { IntentFilter filter = new IntentFilter(); Uri instanceUri = CastWebContentsIntentUtils.getInstanceUri(mSessionId);
diff --git a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelperTest.java b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelperTest.java index b9448e2b..fae57349 100644 --- a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelperTest.java +++ b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelperTest.java
@@ -27,8 +27,10 @@ import org.robolectric.shadows.ShadowLooper; import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chromecast.base.Controller; import org.chromium.chromecast.base.Observer; import org.chromium.chromecast.base.Scope; +import org.chromium.chromecast.base.Unit; import org.chromium.chromecast.shell.CastWebContentsSurfaceHelper.MediaSessionGetter; import org.chromium.chromecast.shell.CastWebContentsSurfaceHelper.StartParams; import org.chromium.content.browser.MediaSessionImpl; @@ -47,6 +49,7 @@ private CastWebContentsSurfaceHelper mSurfaceHelper; private @Mock MediaSessionGetter mMediaSessionGetter; private @Mock MediaSessionImpl mMediaSessionImpl; + private Controller<Unit> mSurfaceAvailable = new Controller<>(); private static class StartParamsBuilder { private String mId = "0"; @@ -89,7 +92,8 @@ MockitoAnnotations.initMocks(this); when(mMediaSessionGetter.get(any())).thenReturn(mMediaSessionImpl); when(mWebContentsView.open(any())).thenReturn(mock(Scope.class)); - mSurfaceHelper = new CastWebContentsSurfaceHelper(mWebContentsView, mFinishCallback); + mSurfaceHelper = new CastWebContentsSurfaceHelper( + mWebContentsView, mFinishCallback, mSurfaceAvailable); mSurfaceHelper.setMediaSessionGetterForTesting(mMediaSessionGetter); } @@ -294,4 +298,17 @@ mSurfaceHelper.onDestroy(); verify(scope).close(); } + + @Test + public void testWindowAndroidPreSurfaceDestroy() { + WebContents webContents = mock(WebContents.class); + + StartParams params = new StartParamsBuilder().withWebContents(webContents).build(); + mSurfaceHelper.onNewStartParams(params); + + mSurfaceAvailable.set(Unit.unit()); + mSurfaceAvailable.reset(); + + verify(webContents).tearDownDialogOverlays(); + } }
diff --git a/chromecast/cast_core/runtime/browser/BUILD.gn b/chromecast/cast_core/runtime/browser/BUILD.gn index acce93f..a2b3dac 100644 --- a/chromecast/cast_core/runtime/browser/BUILD.gn +++ b/chromecast/cast_core/runtime/browser/BUILD.gn
@@ -59,46 +59,6 @@ ] } -cast_source_set("runtime_application_dispatcher") { - sources = [ - "runtime_application_base.cc", - "runtime_application_base.h", - "runtime_application_dispatcher_impl.h", - "streaming_runtime_application.cc", - "streaming_runtime_application.h", - "web_runtime_application.cc", - "web_runtime_application.h", - ] - - public_deps = [ - "//base", - "//chromecast/browser", - "//chromecast/common:feature_constants", - "//components/cast_receiver/browser", - "//components/cast_receiver/browser:streaming_receiver_session_client", - "//components/cast_receiver/common", - "//components/cast_streaming/public/mojom", - "//components/url_rewrite/browser", - "//third_party/abseil-cpp:absl", - ] - - deps = [ - "//chromecast/cast_core/runtime/browser/url_rewrite", - "//components/cast/message_port", - "//components/cast_receiver/browser:page_state_observer", - "//components/cast_receiver/browser:permissions_manager", - "//components/cast_receiver/browser:runtime", - "//components/cast_streaming/browser", - "//components/cast_streaming/public", - "//components/media_control/browser", - "//components/url_rewrite/browser", - "//content/public/browser", - "//mojo/public/cpp/bindings", - "//third_party/blink/public/common:headers", - "//url", - ] -} - cast_source_set("runtime_service_impl") { sources = [ "core_conversions.cc", @@ -123,7 +83,6 @@ deps = [ ":grpc_webui", ":metrics_recorder", - ":runtime_application_dispatcher", "//base", "//chromecast/browser", "//chromecast/cast_core:cast_core_switches", @@ -134,7 +93,7 @@ "//components/cast/message_port", "//components/cast_receiver/browser", "//components/cast_receiver/browser:page_state_observer", - "//components/cast_receiver/browser:streaming_receiver_session_client", + "//components/cast_receiver/browser:runtime", "//components/cast_receiver/common", "//components/cast_streaming/browser", "//components/cast_streaming/public", @@ -182,7 +141,6 @@ ] public_deps = [ - ":runtime_application_dispatcher", "//chromecast/browser", "//components/cast_receiver/browser", ]
diff --git a/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc b/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc index 0243f3b..26528b30 100644 --- a/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc +++ b/chromecast/cast_core/runtime/browser/cast_runtime_content_browser_client.cc
@@ -11,7 +11,6 @@ #include "chromecast/browser/service/cast_service_simple.h" #include "chromecast/browser/webui/constants.h" #include "chromecast/cast_core/cast_core_switches.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" #include "chromecast/cast_core/runtime/browser/runtime_service_impl.h" #include "chromecast/common/cors_exempt_headers.h" #include "chromecast/media/base/video_plane_controller.h"
diff --git a/chromecast/cast_core/runtime/browser/runtime_service_impl.cc b/chromecast/cast_core/runtime/browser/runtime_service_impl.cc index b6e517c..442a1c0 100644 --- a/chromecast/cast_core/runtime/browser/runtime_service_impl.cc +++ b/chromecast/cast_core/runtime/browser/runtime_service_impl.cc
@@ -13,12 +13,11 @@ #include "chromecast/browser/cast_web_service.h" #include "chromecast/cast_core/cast_core_switches.h" #include "chromecast/cast_core/runtime/browser/core_conversions.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_dispatcher_impl.h" #include "chromecast/cast_core/runtime/browser/runtime_application_service_impl.h" #include "chromecast/metrics/cast_event_builder_simple.h" #include "components/cast_receiver/browser/public/application_client.h" #include "components/cast_receiver/browser/public/embedder_application.h" +#include "components/cast_receiver/browser/runtime_application_dispatcher_impl.h" #include "third_party/cast_core/public/src/proto/common/application_config.pb.h" namespace chromecast { @@ -38,9 +37,8 @@ // TODO(crbug.com/1359579): Move RuntimeApplicationDispatcher creation to // cast_receiver::ApplicationClient. application_dispatcher_( - std::make_unique< - RuntimeApplicationDispatcherImpl<RuntimeApplicationServiceImpl>>( - application_client)), + std::make_unique<cast_receiver::RuntimeApplicationDispatcherImpl< + RuntimeApplicationServiceImpl>>(application_client)), task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), web_service_(web_service), metrics_recorder_(this) {
diff --git a/chromecast/cast_core/runtime/browser/streaming_runtime_application.h b/chromecast/cast_core/runtime/browser/streaming_runtime_application.h deleted file mode 100644 index 77713354..0000000 --- a/chromecast/cast_core/runtime/browser/streaming_runtime_application.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_STREAMING_RUNTIME_APPLICATION_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_STREAMING_RUNTIME_APPLICATION_H_ - -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" -#include "components/cast_receiver/browser/public/application_config.h" -#include "components/cast_receiver/browser/streaming_receiver_session_client.h" -#include "components/cast_streaming/browser/public/network_context_getter.h" - -namespace cast_receiver { -class ApplicationClient; -class MessagePortService; -} - -namespace chromecast { - -class StreamingRuntimeApplication final - : public RuntimeApplicationBase, - public cast_receiver::StreamingReceiverSessionClient::Handler { - public: - // |web_service| and |application_client| are expected to exist for the - // lifetime of this instance. - StreamingRuntimeApplication( - std::string cast_session_id, - cast_receiver::ApplicationConfig app_config, - cast_receiver::ApplicationClient& application_client); - ~StreamingRuntimeApplication() override; - - private: - // RuntimeApplicationBase implementation: - void Launch(StatusCallback callback) override; - void StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason stop_reason, - int32_t net_error_code) override; - bool IsStreamingApplication() const override; - - // StreamingReceiverSessionClient::Handler implementation: - void OnStreamingSessionStarted() override; - void OnError() override; - void OnResolutionChanged( - const gfx::Rect& size, - const ::media::VideoTransformation& transformation) override; - - base::raw_ref<cast_receiver::ApplicationClient> const application_client_; - - // Returns the network context used by |receiver_session_client_|. - const cast_streaming::NetworkContextGetter network_context_getter_; - - // Handles communication with cast core over gRPC. - std::unique_ptr<cast_receiver::MessagePortService> message_port_service_; - - // Object responsible for maintaining the lifetime of the streaming session. - std::unique_ptr<cast_receiver::StreamingReceiverSessionClient> - receiver_session_client_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<StreamingRuntimeApplication> weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_STREAMING_RUNTIME_APPLICATION_H_
diff --git a/chromecast/cast_core/runtime/browser/web_runtime_application.h b/chromecast/cast_core/runtime/browser/web_runtime_application.h deleted file mode 100644 index a7cfc73..0000000 --- a/chromecast/cast_core/runtime/browser/web_runtime_application.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_WEB_RUNTIME_APPLICATION_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_WEB_RUNTIME_APPLICATION_H_ - -#include <vector> - -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" -#include "components/cast_receiver/browser/bindings_manager.h" -#include "components/cast_receiver/browser/page_state_observer.h" -#include "components/cast_receiver/browser/public/application_config.h" -#include "content/public/browser/web_contents_observer.h" - -namespace chromecast { - -class WebRuntimeApplication final - : public RuntimeApplicationBase, - public content::WebContentsObserver, - public cast_receiver::BindingsManager::Client, - public cast_receiver::PageStateObserver { - public: - // |web_service| is expected to exist for the lifetime of this instance. - WebRuntimeApplication(std::string cast_session_id, - cast_receiver::ApplicationConfig app_config, - cast_receiver::ApplicationClient& application_client); - ~WebRuntimeApplication() override; - - private: - const GURL& app_url() { - DCHECK(config().url); - return *config().url; - } - - void OnAllBindingsReceived(cast_receiver::Status status, - std::vector<std::string> bindings); - - // RuntimeApplicationBase implementation: - void Launch(StatusCallback callback) override; - bool IsStreamingApplication() const override; - - // cast_receiver::PageStateObserver implementation: - void OnPageLoadComplete() override; - void OnPageStopped(StopReason reason, int32_t error_code) override; - - // content::WebContentsObserver implementation: - void InnerWebContentsCreated( - content::WebContents* inner_web_contents) override; - void MediaStartedPlaying(const MediaPlayerInfo& video_type, - const content::MediaPlayerId& id) override; - void MediaStoppedPlaying( - const MediaPlayerInfo& video_type, - const content::MediaPlayerId& id, - content::WebContentsObserver::MediaStoppedReason reason) override; - - // BindingsManagerWebRuntime::Client implementation: - void OnError() override; - - std::unique_ptr<cast_receiver::BindingsManager> bindings_manager_; - - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<WebRuntimeApplication> weak_factory_{this}; -}; - -} // namespace chromecast - -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_WEB_RUNTIME_APPLICATION_H_
diff --git a/chromeos/ash/services/cellular_setup/esim_manager.cc b/chromeos/ash/services/cellular_setup/esim_manager.cc index c8e662b..10428ad6 100644 --- a/chromeos/ash/services/cellular_setup/esim_manager.cc +++ b/chromeos/ash/services/cellular_setup/esim_manager.cc
@@ -23,7 +23,7 @@ namespace { // The Stork SM-DS Prod server used to fetch pending ESim profiles. -const char kStorkSmdsServerAddress[] = "prod.smds.rsp.goog"; +const char kStorkSmdsServerAddress[] = "1$prod.smds.rsp.goog$"; void LogEuiccPaths(const std::set<dbus::ObjectPath>& new_euicc_paths) { if (new_euicc_paths.empty()) {
diff --git a/chromeos/ash/services/ime/ime_service.cc b/chromeos/ash/services/ime/ime_service.cc index 788a7966..fae5b47e 100644 --- a/chromeos/ash/services/ime/ime_service.cc +++ b/chromeos/ash/services/ime/ime_service.cc
@@ -190,21 +190,16 @@ if (strcmp(feature_name, chromeos::features::kLacrosSupport.name) == 0) { return base::FeatureList::IsEnabled(chromeos::features::kLacrosSupport); } - if (strcmp(feature_name, - chromeos::features::kSystemChinesePhysicalTyping.name) == 0) { - return base::FeatureList::IsEnabled( - chromeos::features::kSystemChinesePhysicalTyping); + if (strcmp(feature_name, "SystemChinesePhysicalTyping") == 0) { + return true; } if (strcmp(feature_name, chromeos::features::kSystemJapanesePhysicalTyping.name) == 0) { return base::FeatureList::IsEnabled( chromeos::features::kSystemJapanesePhysicalTyping); } - if (strcmp(feature_name, - chromeos::features::kSystemTransliterationPhysicalTyping.name) == - 0) { - return base::FeatureList::IsEnabled( - chromeos::features::kSystemTransliterationPhysicalTyping); + if (strcmp(feature_name, "SystemTransliterationPhysicalTyping") == 0) { + return true; } return false; }
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index 8a7a8cf..35ab9163d 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -1170,13 +1170,13 @@ </message> <message name="IDS_INPUT_DIAGNOSTICS_INTERNAL_KEYBOARD" desc="Noun phrase that describes an internal keyboard (built-in, as found on a laptop) to the user. Used as a label in a list of input devices in a diagnostic tool."> - Internal keyboard + Built-in keyboard </message> <message name="IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHPAD" desc="Noun phrase that describes an internal touchpad (built-in, as found on a laptop) to the user. Used as a label in a list of input devices in a diagnostic tool."> - Internal touchpad + Built-in touchpad </message> <message name="IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHSCREEN" desc="Noun phrase that describes an internal (built-in) touchscreen to the user. Used as a label in a list of input devices in a diagnostic tool."> - Internal touchscreen + Built-in touchscreen </message> <message name="IDS_INPUT_DIAGNOSTICS_USB_KEYBOARD" desc="Noun phrase that describes a USB keyboard to the user. Used as a label in a list of input devices in a diagnostic tool.">
diff --git a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_KEYBOARD.png.sha1 b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_KEYBOARD.png.sha1 index 934bf709..e163509 100644 --- a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_KEYBOARD.png.sha1 +++ b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_KEYBOARD.png.sha1
@@ -1 +1 @@ -ca3aa53f3b418f2337718ba9a0d790b42dfb1a8b \ No newline at end of file +bc14a416d84cfb3cc3bfd9698c50223d44a45396 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHPAD.png.sha1 b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHPAD.png.sha1 index 5c7053bf..e163509 100644 --- a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHPAD.png.sha1 +++ b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHPAD.png.sha1
@@ -1 +1 @@ -ee002005295d759b3e5b75f75b563302672ef4e1 \ No newline at end of file +bc14a416d84cfb3cc3bfd9698c50223d44a45396 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHSCREEN.png.sha1 b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHSCREEN.png.sha1 index 28b6c4a..e163509 100644 --- a/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHSCREEN.png.sha1 +++ b/chromeos/chromeos_strings_grd/IDS_INPUT_DIAGNOSTICS_INTERNAL_TOUCHSCREEN.png.sha1
@@ -1 +1 @@ -520956a00c80f439b22b586f5dcc7d0da5cd3e04 \ No newline at end of file +bc14a416d84cfb3cc3bfd9698c50223d44a45396 \ No newline at end of file
diff --git a/chromeos/crosapi/mojom/tts.mojom b/chromeos/crosapi/mojom/tts.mojom index ac79242f..6f3acdf 100644 --- a/chromeos/crosapi/mojom/tts.mojom +++ b/chromeos/crosapi/mojom/tts.mojom
@@ -144,6 +144,18 @@ // |all_voices| contains the new voices (provided by both Ash and // Lacros). VoicesChanged@0(array<TtsVoice> all_voices); + + // Called from Ash to request a Lacros Tts engine to speak the |utterance| + // with the given |voice|. |utterance_client| is provided only if |utterance| + // is issued by Ash. + [MinVersion=1] + SpeakWithLacrosVoice@1(TtsUtterance utterance, TtsVoice voice, + pending_remote<TtsUtteranceClient>? ash_utterance_client); + + // Called from Ash to request the specified Lacros speech engine to stop + // speaking. + [MinVersion=1] + Stop@2(string engine_id); }; // This interface serves as a remote client of a TtsUtterance in Ash which is
diff --git a/chromeos/dbus/power/fake_power_manager_client.cc b/chromeos/dbus/power/fake_power_manager_client.cc index adf432d6..982277e 100644 --- a/chromeos/dbus/power/fake_power_manager_client.cc +++ b/chromeos/dbus/power/fake_power_manager_client.cc
@@ -72,11 +72,6 @@ return base::TimeDelta::FromTimeSpec(ts); } -std::string SysnameFromBluetoothAddress(const std::string& address) { - return "/sys/class/power_supply/hid-" + base::ToLowerASCII(address) + - "-battery"; -} - } // namespace // static @@ -387,22 +382,6 @@ return kDarkSuspendDelayTimeout; } -void FakePowerManagerClient::RefreshBluetoothBattery( - const std::string& address) { - if (!base::Contains(peripheral_battery_refresh_levels_, address)) - return; - - for (auto& observer : observers_) { - observer.PeripheralBatteryStatusReceived( - SysnameFromBluetoothAddress(address), "somename", - peripheral_battery_refresh_levels_[address], - power_manager:: - PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_UNKNOWN, - /*serial_number=*/"", - /*active_update=*/true); - } -} - void FakePowerManagerClient::SetExternalDisplayALSBrightness(bool enabled) { external_display_als_brightness_enabled_ = enabled; }
diff --git a/chromeos/dbus/power/fake_power_manager_client.h b/chromeos/dbus/power/fake_power_manager_client.h index 476b00c0c..2d1bd1a 100644 --- a/chromeos/dbus/power/fake_power_manager_client.h +++ b/chromeos/dbus/power/fake_power_manager_client.h
@@ -85,10 +85,6 @@ void set_user_activity_callback(base::RepeatingClosure callback) { user_activity_callback_ = std::move(callback); } - void set_peripheral_battery_refresh_level(const std::string& address, - int level) { - peripheral_battery_refresh_levels_[address] = level; - } void set_restart_callback(base::OnceClosure callback) { restart_callback_ = std::move(callback); } @@ -144,7 +140,6 @@ void DeleteArcTimers(const std::string& tag, VoidDBusMethodCallback callback) override; base::TimeDelta GetDarkSuspendDelayTimeout() override; - void RefreshBluetoothBattery(const std::string& address) override; void SetExternalDisplayALSBrightness(bool enabled) override; void GetExternalDisplayALSBrightness( DBusMethodCallback<bool> callback) override; @@ -330,9 +325,6 @@ // If set then |StartArcTimer| returns failure. bool simulate_start_arc_timer_failure_ = false; - // Used in RefreshBluetoothBattery. - base::flat_map<std::string, int> peripheral_battery_refresh_levels_; - bool external_display_als_brightness_enabled_ = false; // Charge history returned by GetChargeHistoryForAdaptiveCharging()
diff --git a/chromeos/dbus/power/power_manager_client.cc b/chromeos/dbus/power/power_manager_client.cc index b535b22..3cee6c33 100644 --- a/chromeos/dbus/power/power_manager_client.cc +++ b/chromeos/dbus/power/power_manager_client.cc
@@ -608,17 +608,6 @@ return max_dark_suspend_delay_timeout_; } - void RefreshBluetoothBattery(const std::string& address) override { - dbus::MethodCall method_call(power_manager::kPowerManagerInterface, - power_manager::kRefreshBluetoothBatteryMethod); - dbus::MessageWriter writer(&method_call); - writer.AppendString(address); - // This refresh request is best effort, so we don't have to handle errors. - power_manager_proxy_->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::DoNothing()); - } - void SetExternalDisplayALSBrightness(bool enabled) override { dbus::MethodCall method_call( power_manager::kPowerManagerInterface,
diff --git a/chromeos/dbus/power/power_manager_client.h b/chromeos/dbus/power/power_manager_client.h index ad5b3ab1b..44e943d85 100644 --- a/chromeos/dbus/power/power_manager_client.h +++ b/chromeos/dbus/power/power_manager_client.h
@@ -368,10 +368,6 @@ // The time power manager will wait before resuspending from a dark resume. virtual base::TimeDelta GetDarkSuspendDelayTimeout() = 0; - // Refreshes the battery signal of the specified Bluetooth device. - // TODO(b/166543531): Remove after migrating to BlueZ Battery Provider API. - virtual void RefreshBluetoothBattery(const std::string& address) = 0; - // On devices that support external displays with ambient light sensors, this // enables/disables the ALS-based brightness adjustment on those displays. virtual void SetExternalDisplayALSBrightness(bool enabled) = 0;
diff --git a/chromeos/tast_control.gni b/chromeos/tast_control.gni index 221ae65..d079af4 100644 --- a/chromeos/tast_control.gni +++ b/chromeos/tast_control.gni
@@ -298,6 +298,9 @@ # https://crbug.com/1361163 "lacros.AudioPinnedStream.play", + # https://crbug.com/1392911 + "login.RestrictSignin", + # READ COMMENT AT TOP BEFORE ADDING NEW TESTS HERE. ]
diff --git a/components/access_code_cast/common/access_code_cast_metrics.cc b/components/access_code_cast/common/access_code_cast_metrics.cc index 826a5bfb..818dd83 100644 --- a/components/access_code_cast/common/access_code_cast_metrics.cc +++ b/components/access_code_cast/common/access_code_cast_metrics.cc
@@ -18,6 +18,8 @@ "AccessCodeCast.Discovery.AddSinkResult.Remembered"; const char AccessCodeCastMetrics::kHistogramCastModeOnSuccess[] = "AccessCodeCast.Discovery.CastModeOnSuccess"; +const char AccessCodeCastMetrics::kHistogramDeviceDurationOnRoute[] = + "AccessCodeCast.Discovery.DeviceDurationOnRoute"; const char AccessCodeCastMetrics::kHistogramDialogCloseReason[] = "AccessCodeCast.Ui.DialogCloseReason"; const char AccessCodeCastMetrics::kHistogramDialogLoadTime[] = @@ -45,6 +47,15 @@ } // static +void AccessCodeCastMetrics::RecordAccessCodeRouteStarted( + base::TimeDelta duration) { + int64_t duration_seconds = duration.InSeconds(); + // Duration can take one of five values, ranging from zero (0 sec), up to + // a year (31536000 sec). So, recording as a sparse histogram is best. + base::UmaHistogramSparse(kHistogramDeviceDurationOnRoute, duration_seconds); +} + +// static void AccessCodeCastMetrics::RecordAddSinkResult( bool is_remembered, AccessCodeCastAddSinkResult result) {
diff --git a/components/access_code_cast/common/access_code_cast_metrics.h b/components/access_code_cast/common/access_code_cast_metrics.h index 9c95eec..47c18d0a 100644 --- a/components/access_code_cast/common/access_code_cast_metrics.h +++ b/components/access_code_cast/common/access_code_cast_metrics.h
@@ -82,6 +82,7 @@ static const char kHistogramAddSinkResultNew[]; static const char kHistogramAddSinkResultRemembered[]; static const char kHistogramCastModeOnSuccess[]; + static const char kHistogramDeviceDurationOnRoute[]; static const char kHistogramDialogCloseReason[]; static const char kHistogramDialogLoadTime[]; static const char kHistogramDialogOpenLocation[]; @@ -95,6 +96,10 @@ // Records the count of ACCESS_CODE_NOT_FOUND errors per instance of dialog. static void RecordAccessCodeNotFoundCount(int count); + // Records the value of the device duration pref on successful creation of + // an access code route. + static void RecordAccessCodeRouteStarted(base::TimeDelta duration); + // Records the result of adding an access code sink. static void RecordAddSinkResult(bool is_remembered, AccessCodeCastAddSinkResult result);
diff --git a/components/access_code_cast/common/access_code_cast_metrics_unittest.cc b/components/access_code_cast/common/access_code_cast_metrics_unittest.cc index 16eb353..53fdea5 100644 --- a/components/access_code_cast/common/access_code_cast_metrics_unittest.cc +++ b/components/access_code_cast/common/access_code_cast_metrics_unittest.cc
@@ -119,6 +119,27 @@ 3); } +TEST(AccessCodeCastMetricsTest, RecordAccessCodeRouteStarted) { + base::HistogramTester histogram_tester; + + AccessCodeCastMetrics::RecordAccessCodeRouteStarted(base::Seconds(0)); + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 0, 1); + + // Ensure the functions properly converts duration to seconds + AccessCodeCastMetrics::RecordAccessCodeRouteStarted( + base::Milliseconds(10000)); + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 10, 1); + AccessCodeCastMetrics::RecordAccessCodeRouteStarted( + base::Milliseconds(20000)); + histogram_tester.ExpectBucketCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 20, 1); + + histogram_tester.ExpectTotalCount( + "AccessCodeCast.Discovery.DeviceDurationOnRoute", 3); +} + TEST(AccessCodeCastMetricsTest, RecordDialogLoadTime) { base::HistogramTester histogram_tester;
diff --git a/components/attribution_reporting/suitable_origin.cc b/components/attribution_reporting/suitable_origin.cc index 69d02be8..c04ba130 100644 --- a/components/attribution_reporting/suitable_origin.cc +++ b/components/attribution_reporting/suitable_origin.cc
@@ -40,6 +40,10 @@ return Create(GURL(str)); } +SuitableOrigin::SuitableOrigin() { + DCHECK(!IsValid()); +} + SuitableOrigin::SuitableOrigin(url::Origin origin) : origin_(std::move(origin)) { DCHECK(IsValid());
diff --git a/components/attribution_reporting/suitable_origin.h b/components/attribution_reporting/suitable_origin.h index df50e26..3d13c08 100644 --- a/components/attribution_reporting/suitable_origin.h +++ b/components/attribution_reporting/suitable_origin.h
@@ -16,6 +16,10 @@ class GURL; +namespace mojo { +struct DefaultConstructTraits; +} // namespace mojo + namespace attribution_reporting { // A thin wrapper around `url::Origin` that enforces invariants required for an @@ -44,8 +48,6 @@ // All parts of the URL other than the origin are ignored. static absl::optional<SuitableOrigin> Deserialize(base::StringPiece); - SuitableOrigin() = delete; - ~SuitableOrigin(); SuitableOrigin(const SuitableOrigin&); @@ -82,11 +84,17 @@ std::string Serialize() const; - private: - explicit SuitableOrigin(url::Origin); - bool IsValid() const; + private: + friend mojo::DefaultConstructTraits; + + // Creates an invalid instance for use with Mojo deserialization, which + // requires types to be default-constructible. + SuitableOrigin(); + + explicit SuitableOrigin(url::Origin); + url::Origin origin_; };
diff --git a/components/attribution_reporting/suitable_origin_unittest.cc b/components/attribution_reporting/suitable_origin_unittest.cc index 19ff5955..2d9b4ab 100644 --- a/components/attribution_reporting/suitable_origin_unittest.cc +++ b/components/attribution_reporting/suitable_origin_unittest.cc
@@ -47,8 +47,10 @@ EXPECT_EQ(test_case.expected_suitable, actual.has_value()) << test_case.origin; - if (test_case.expected_suitable) + if (test_case.expected_suitable) { EXPECT_EQ(test_case.origin, *actual.value()); + EXPECT_TRUE(actual->IsValid()); + } } }
diff --git a/components/cast_receiver/browser/BUILD.gn b/components/cast_receiver/browser/BUILD.gn index acd50fe7..e22c6c2 100644 --- a/components/cast_receiver/browser/BUILD.gn +++ b/components/cast_receiver/browser/BUILD.gn
@@ -40,6 +40,8 @@ deps = [ ":browser", ":page_state_observer", + ":permissions_manager", + ":streaming_receiver_session_client", "//base", "//components/cast/api_bindings:manager", "//components/cast/message_port", @@ -48,13 +50,16 @@ "//components/cast/named_message_port_connector", "//components/cast_receiver/common", "//components/cast_streaming/browser", + "//components/cast_streaming/public", "//components/media_control/browser", "//components/on_load_script_injector/browser", "//components/url_rewrite/browser", "//content/public/browser", "//content/public/common", "//media", + "//third_party/abseil-cpp:absl", "//ui/base", + "//url", ] sources = [ "bindings_manager.cc", @@ -65,6 +70,13 @@ "public/embedder_application.h", "public/message_port_service.h", "public/runtime_application_dispatcher.h", + "runtime_application_base.cc", + "runtime_application_base.h", + "runtime_application_dispatcher_impl.h", + "streaming_runtime_application.cc", + "streaming_runtime_application.h", + "web_runtime_application.cc", + "web_runtime_application.h", ] }
diff --git a/components/cast_receiver/browser/DEPS b/components/cast_receiver/browser/DEPS index 739ac0131..752deaa 100644 --- a/components/cast_receiver/browser/DEPS +++ b/components/cast_receiver/browser/DEPS
@@ -3,8 +3,8 @@ "+components/cast_streaming/public", "+components/media_control/browser", "+components/on_load_script_injector/browser", - "+components/url_rewrite/mojom", "+components/url_rewrite/browser", + "+components/url_rewrite/mojom", "+content/public/browser", "+content/public/common", "+media",
diff --git a/components/cast_receiver/browser/page_state_observer.cc b/components/cast_receiver/browser/page_state_observer.cc index 0a1d88d..433f0b12 100644 --- a/components/cast_receiver/browser/page_state_observer.cc +++ b/components/cast_receiver/browser/page_state_observer.cc
@@ -9,7 +9,6 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "net/base/net_errors.h" namespace cast_receiver { @@ -74,7 +73,8 @@ return; } - wrapped_->OnPageStopped(StopReason::kHttpError, error_code); + wrapped_->OnPageStopped(StopReason::kHttpError, + static_cast<net::Error>(error_code)); } void WebContentsDestroyed() override {
diff --git a/components/cast_receiver/browser/page_state_observer.h b/components/cast_receiver/browser/page_state_observer.h index 422a47a..8efcb59 100644 --- a/components/cast_receiver/browser/page_state_observer.h +++ b/components/cast_receiver/browser/page_state_observer.h
@@ -6,6 +6,7 @@ #define COMPONENTS_CAST_RECEIVER_BROWSER_PAGE_STATE_OBSERVER_H_ #include "content/public/browser/web_contents_observer.h" +#include "net/base/net_errors.h" #include "url/gurl.h" namespace content { @@ -32,7 +33,7 @@ // Called when the observed |web_contents| stops trying to load the page for // reasons outside of the user's control - such as the page closing or an // HTTP error. - virtual void OnPageStopped(StopReason reason, int32_t error_code) {} + virtual void OnPageStopped(StopReason reason, net::Error error_code) {} protected: PageStateObserver();
diff --git a/chromecast/cast_core/runtime/browser/runtime_application_base.cc b/components/cast_receiver/browser/runtime_application_base.cc similarity index 79% rename from chromecast/cast_core/runtime/browser/runtime_application_base.cc rename to components/cast_receiver/browser/runtime_application_base.cc index 796d7e1a..b6abca7 100644 --- a/chromecast/cast_core/runtime/browser/runtime_application_base.cc +++ b/components/cast_receiver/browser/runtime_application_base.cc
@@ -2,25 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" +#include "components/cast_receiver/browser/runtime_application_base.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" #include "base/task/sequenced_task_runner.h" -#include "chromecast/browser/cast_content_window.h" -#include "chromecast/browser/cast_web_contents.h" -#include "chromecast/common/feature_constants.h" #include "components/cast_receiver/browser/permissions_manager_impl.h" #include "components/media_control/browser/media_blocker.h" #include "components/url_rewrite/browser/url_request_rewrite_rules_manager.h" #include "content/public/browser/web_contents.h" -namespace chromecast { +namespace cast_receiver { RuntimeApplicationBase::RuntimeApplicationBase( std::string cast_session_id, - cast_receiver::ApplicationConfig app_config, - cast_receiver::ApplicationClient& application_client) + ApplicationConfig app_config, + ApplicationClient& application_client) : cast_session_id_(std::move(cast_session_id)), app_config_(std::move(app_config)), task_runner_(base::SequencedTaskRunner::GetCurrentDefault()), @@ -34,7 +31,7 @@ } void RuntimeApplicationBase::SetEmbedderApplication( - cast_receiver::EmbedderApplication& embedder_application) { + EmbedderApplication& embedder_application) { DCHECK(!embedder_application_); embedder_application_ = &embedder_application; } @@ -61,19 +58,18 @@ SetUrlRewriteRules(std::move(cached_mojom_rules_)); } - LOG(INFO) << "Loaded application: " << *this; - std::move(callback).Run(cast_receiver::OkStatus()); + DVLOG(1) << "Loaded application: " << *this; + std::move(callback).Run(OkStatus()); } void RuntimeApplicationBase::Stop(StatusCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kUserRequest, - /*net_error_code=*/0); - std::move(callback).Run(cast_receiver::OkStatus()); + StopApplication(EmbedderApplication::ApplicationStopReason::kUserRequest, + net::ERR_ABORTED); + std::move(callback).Run(OkStatus()); } -cast_receiver::ApplicationClient::ApplicationControls& +ApplicationClient::ApplicationControls& RuntimeApplicationBase::GetApplicationControls() { DCHECK(embedder_application().GetWebContents()); @@ -91,9 +87,8 @@ void RuntimeApplicationBase::SetContentPermissions( content::WebContents& web_contents) { - cast_receiver::PermissionsManagerImpl* permissions_manager = - cast_receiver::PermissionsManagerImpl::CreateInstance(web_contents, - GetAppId()); + PermissionsManagerImpl* permissions_manager = + PermissionsManagerImpl::CreateInstance(web_contents, GetAppId()); if (config().url.has_value()) { auto app_url_origin = url::Origin::Create(config().url.value()); if (!app_url_origin.opaque()) { @@ -111,7 +106,7 @@ void RuntimeApplicationBase::OnPageLoaded() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DLOG(INFO) << "Page loaded: " << *this; + DVLOG(1) << "Page loaded: " << *this; auto* window_controls = embedder_application().GetContentWindowControls(); DCHECK(window_controls); @@ -124,10 +119,10 @@ // Create the window and show the web view. if (is_visible_) { - LOG(INFO) << "Loading page in full screen: " << *this; + DVLOG(1) << "Loading page in full screen: " << *this; window_controls->ShowWindow(); } else { - LOG(INFO) << "Loading page in background: " << *this; + DVLOG(1) << "Loading page in background: " << *this; window_controls->HideWindow(); } @@ -153,8 +148,8 @@ is_media_load_blocked_ = load_blocked; is_media_start_blocked_ = start_blocked; - LOG(INFO) << "Media state updated: is_load_blocked=" << load_blocked - << ", is_start_blocked=" << start_blocked << ", " << *this; + DVLOG(1) << "Media state updated: is_load_blocked=" << load_blocked + << ", is_start_blocked=" << start_blocked << ", " << *this; if (!embedder_application().GetWebContents()) { return; @@ -172,8 +167,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is_visible_ = is_visible; - LOG(INFO) << "Visibility updated: is_visible_=" << is_visible_ << ", " - << *this; + DVLOG(1) << "Visibility updated: is_visible_=" << is_visible_ << ", " + << *this; auto* window_controls = embedder_application().GetContentWindowControls(); if (!window_controls) { @@ -191,8 +186,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is_touch_input_enabled_ = enabled; - LOG(INFO) << "Touch input updated: is_touch_input_enabled_= " - << is_touch_input_enabled_ << ", " << *this; + DVLOG(1) << "Touch input updated: is_touch_input_enabled_= " + << is_touch_input_enabled_ << ", " << *this; auto* window_controls = embedder_application().GetContentWindowControls(); if (!window_controls) { @@ -211,8 +206,8 @@ } void RuntimeApplicationBase::StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason stop_reason, - int32_t net_error_code) { + EmbedderApplication::ApplicationStopReason stop_reason, + net::Error net_error_code) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!is_application_running_) { @@ -234,8 +229,8 @@ embedder_application().NotifyApplicationStopped(stop_reason, net_error_code); - LOG(INFO) << "Application is stopped: stop_reason=" << stop_reason << ", " - << *this; + DVLOG(1) << "Application is stopped: stop_reason=" << stop_reason << ", " + << *this; } void RuntimeApplicationBase::SetWebVisibilityAndPaint(bool is_visible) { @@ -265,4 +260,4 @@ SetWebVisibilityAndPaint(false); } -} // namespace chromecast +} // namespace cast_receiver
diff --git a/chromecast/cast_core/runtime/browser/runtime_application_base.h b/components/cast_receiver/browser/runtime_application_base.h similarity index 74% rename from chromecast/cast_core/runtime/browser/runtime_application_base.h rename to components/cast_receiver/browser/runtime_application_base.h index 80560e89..df03001 100644 --- a/chromecast/cast_core/runtime/browser/runtime_application_base.h +++ b/components/cast_receiver/browser/runtime_application_base.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_BASE_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_BASE_H_ +#ifndef COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_BASE_H_ +#define COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_BASE_H_ #include <ostream> #include <string> @@ -19,27 +19,28 @@ #include "components/cast_receiver/browser/public/embedder_application.h" #include "components/cast_receiver/browser/public/runtime_application.h" #include "components/url_rewrite/mojom/url_request_rewrite.mojom.h" +#include "net/base/net_errors.h" namespace content { class WebContents; } // namespace content -namespace chromecast { - -class CastWebContents; +namespace cast_receiver { // This class is for sharing code between Web and streaming RuntimeApplication // implementations, including Load and Launch behavior. class RuntimeApplicationBase - : public cast_receiver::RuntimeApplication, - public cast_receiver::ContentWindowControls::VisibilityChangeObserver { + : public RuntimeApplication, + public ContentWindowControls::VisibilityChangeObserver { public: ~RuntimeApplicationBase() override; + RuntimeApplicationBase(RuntimeApplicationBase& other) = delete; + RuntimeApplicationBase& operator=(RuntimeApplicationBase& other) = delete; + // Sets the |embedder_application| to be used for making calls to platform- // specific implementations of cast_receiver interfaces. - void SetEmbedderApplication( - cast_receiver::EmbedderApplication& embedder_application); + void SetEmbedderApplication(EmbedderApplication& embedder_application); // RuntimeApplication implementation. // @@ -62,28 +63,28 @@ // |application_client| is expected to exist for the lifetime of this // instance. RuntimeApplicationBase(std::string cast_session_id, - cast_receiver::ApplicationConfig app_config, - cast_receiver::ApplicationClient& application_client); + ApplicationConfig app_config, + ApplicationClient& application_client); // Stops the running application. Must be called before destruction of any // instance of the implementing object. virtual void StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason stop_reason, - int32_t net_error_code); + EmbedderApplication::ApplicationStopReason stop_reason, + net::Error net_error_code); scoped_refptr<base::SequencedTaskRunner> task_runner() { return task_runner_; } - cast_receiver::EmbedderApplication& embedder_application() { + EmbedderApplication& embedder_application() { DCHECK(embedder_application_); return *embedder_application_; } // NOTE: This field is empty until after Load() is called. - const cast_receiver::ApplicationConfig& config() const { return app_config_; } + const ApplicationConfig& config() const { return app_config_; } - // Loads the page at the given |url| in the CastWebContents. + // Loads the page at the given |url| in the associated WebContents. void LoadPage(const GURL& url); // Called by the actual implementation as Cast application page has loaded. @@ -95,9 +96,9 @@ // Returns the ApplicationControls associated with this application, if such // controls exist. + // // TODO(crbug.com/1382907): Change to a callback-based API. - cast_receiver::ApplicationClient::ApplicationControls& - GetApplicationControls(); + ApplicationClient::ApplicationControls& GetApplicationControls(); private: void SetWebVisibilityAndPaint(bool is_visible); @@ -107,14 +108,13 @@ void OnWindowHidden() override; const std::string cast_session_id_; - const cast_receiver::ApplicationConfig app_config_; + const ApplicationConfig app_config_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::raw_ref<cast_receiver::ApplicationClient> application_client_; + base::raw_ref<ApplicationClient> application_client_; - base::raw_ptr<cast_receiver::EmbedderApplication> embedder_application_{ - nullptr}; + base::raw_ptr<EmbedderApplication> embedder_application_{nullptr}; // Cached mojom rules that are set iff |cast_web_view_| is not created before // SetUrlRewriteRules is called. @@ -133,6 +133,6 @@ base::WeakPtrFactory<RuntimeApplicationBase> weak_factory_{this}; }; -} // namespace chromecast +} // namespace cast_receiver -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_BASE_H_ +#endif // COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_BASE_H_
diff --git a/chromecast/cast_core/runtime/browser/runtime_application_dispatcher_impl.h b/components/cast_receiver/browser/runtime_application_dispatcher_impl.h similarity index 75% rename from chromecast/cast_core/runtime/browser/runtime_application_dispatcher_impl.h rename to components/cast_receiver/browser/runtime_application_dispatcher_impl.h index dc62fba..e9c48b0 100644 --- a/chromecast/cast_core/runtime/browser/runtime_application_dispatcher_impl.h +++ b/components/cast_receiver/browser/runtime_application_dispatcher_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_ -#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_ +#ifndef COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_ +#define COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_ #include <memory> @@ -12,42 +12,46 @@ #include "base/memory/raw_ptr.h" #include "base/memory/raw_ref.h" #include "base/sequence_checker.h" -#include "chromecast/cast_core/runtime/browser/runtime_application_base.h" -#include "chromecast/cast_core/runtime/browser/streaming_runtime_application.h" -#include "chromecast/cast_core/runtime/browser/web_runtime_application.h" #include "components/cast_receiver/browser/public/application_client.h" #include "components/cast_receiver/browser/public/application_config.h" #include "components/cast_receiver/browser/public/runtime_application_dispatcher.h" +#include "components/cast_receiver/browser/runtime_application_base.h" +#include "components/cast_receiver/browser/streaming_runtime_application.h" +#include "components/cast_receiver/browser/web_runtime_application.h" #include "components/cast_streaming/public/app_ids.h" -namespace chromecast { +namespace cast_receiver { template <typename TEmbedderApplication> class RuntimeApplicationDispatcherImpl - : public cast_receiver::RuntimeApplicationDispatcher<TEmbedderApplication> { + : public RuntimeApplicationDispatcher<TEmbedderApplication> { public: // |application_client| is expected to persist for the lifetime of this // instance. explicit RuntimeApplicationDispatcherImpl( - cast_receiver::ApplicationClient& application_client); + ApplicationClient& application_client); ~RuntimeApplicationDispatcherImpl() override = default; + RuntimeApplicationDispatcherImpl(RuntimeApplicationDispatcherImpl& other) = + delete; + RuntimeApplicationDispatcherImpl& operator=( + RuntimeApplicationDispatcherImpl& other) = delete; + private: - using EmbedderApplicationFactory = - cast_receiver::RuntimeApplicationDispatcher< - TEmbedderApplication>::EmbedderApplicationFactory; + using EmbedderApplicationFactory = RuntimeApplicationDispatcher< + TEmbedderApplication>::EmbedderApplicationFactory; // RuntimeApplicationDispatcher implementation. TEmbedderApplication* CreateApplication( std::string session_id, - cast_receiver::ApplicationConfig app_config, + ApplicationConfig app_config, EmbedderApplicationFactory factory) override; TEmbedderApplication* GetApplication(const std::string& session_id) override; std::unique_ptr<TEmbedderApplication> DestroyApplication( const std::string& session_id) override; SEQUENCE_CHECKER(sequence_checker_); - base::raw_ref<cast_receiver::ApplicationClient> const application_client_; + base::raw_ref<ApplicationClient> const application_client_; base::flat_map<std::string, std::unique_ptr<TEmbedderApplication>> loaded_apps_; @@ -55,15 +59,14 @@ template <typename TEmbedderApplication> RuntimeApplicationDispatcherImpl<TEmbedderApplication>:: - RuntimeApplicationDispatcherImpl( - cast_receiver::ApplicationClient& application_client) + RuntimeApplicationDispatcherImpl(ApplicationClient& application_client) : application_client_(application_client) {} template <typename TEmbedderApplication> TEmbedderApplication* RuntimeApplicationDispatcherImpl<TEmbedderApplication>::CreateApplication( std::string session_id, - cast_receiver::ApplicationConfig app_config, + ApplicationConfig app_config, EmbedderApplicationFactory factory) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -119,6 +122,6 @@ return app; } -} // namespace chromecast +} // namespace cast_receiver -#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_ +#endif // COMPONENTS_CAST_RECEIVER_BROWSER_RUNTIME_APPLICATION_DISPATCHER_IMPL_H_
diff --git a/chromecast/cast_core/runtime/browser/streaming_runtime_application.cc b/components/cast_receiver/browser/streaming_runtime_application.cc similarity index 73% rename from chromecast/cast_core/runtime/browser/streaming_runtime_application.cc rename to components/cast_receiver/browser/streaming_runtime_application.cc index 5a765cb..84fdb22 100644 --- a/chromecast/cast_core/runtime/browser/streaming_runtime_application.cc +++ b/components/cast_receiver/browser/streaming_runtime_application.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chromecast/cast_core/runtime/browser/streaming_runtime_application.h" +#include "components/cast_receiver/browser/streaming_runtime_application.h" #include "components/cast/message_port/platform_message_port.h" #include "components/cast_receiver/browser/public/application_client.h" @@ -12,10 +12,9 @@ #include "components/cast_streaming/public/cast_streaming_url.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" -#include "net/base/net_errors.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" -namespace chromecast { +namespace cast_receiver { namespace { constexpr char kCastTransportBindingName[] = "cast.__platform__.cast_transport"; @@ -30,8 +29,8 @@ StreamingRuntimeApplication::StreamingRuntimeApplication( std::string cast_session_id, - cast_receiver::ApplicationConfig app_config, - cast_receiver::ApplicationClient& application_client) + ApplicationConfig app_config, + ApplicationClient& application_client) : RuntimeApplicationBase(std::move(cast_session_id), std::move(app_config), application_client), @@ -39,9 +38,8 @@ StreamingRuntimeApplication::~StreamingRuntimeApplication() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kUserRequest, - net::OK); + StopApplication(EmbedderApplication::ApplicationStopReason::kUserRequest, + net::OK); } void StreamingRuntimeApplication::OnStreamingSessionStarted() { @@ -52,14 +50,13 @@ void StreamingRuntimeApplication::OnError() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); LOG(WARNING) << "Streaming session for " << *this << " has hit an error!"; - StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kRuntimeError, - net::ERR_FAILED); + StopApplication(EmbedderApplication::ApplicationStopReason::kRuntimeError, + net::ERR_FAILED); } void StreamingRuntimeApplication::OnResolutionChanged( const gfx::Rect& size, - const ::media::VideoTransformation& transformation) { + const media::VideoTransformation& transformation) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); application_client_->OnStreamingResolutionChanged(size, transformation); } @@ -80,14 +77,13 @@ std::move(client_port)); // Initialize the streaming receiver. - receiver_session_client_ = - std::make_unique<cast_receiver::StreamingReceiverSessionClient>( - task_runner(), application_client_->GetNetworkContextGetter(), - std::move(server_port), embedder_application().GetWebContents(), this, - embedder_application().GetStreamingConfigManager(), - /* supports_audio= */ GetAppId() != - cast_streaming::GetIosAppStreamingAudioVideoAppId(), - /* supports_video= */ true); + receiver_session_client_ = std::make_unique<StreamingReceiverSessionClient>( + task_runner(), application_client_->GetNetworkContextGetter(), + std::move(server_port), embedder_application().GetWebContents(), this, + embedder_application().GetStreamingConfigManager(), + /* supports_audio= */ GetAppId() != + cast_streaming::GetIosAppStreamingAudioVideoAppId(), + /* supports_video= */ true); receiver_session_client_->LaunchStreamingReceiverAsync(); // Application is initialized now - we can load the URL. @@ -96,16 +92,16 @@ cast_streaming::GetCastStreamingMediaSourceUrl().spec().c_str()))); // Signal that application is launching. - std::move(callback).Run(cast_receiver::OkStatus()); + std::move(callback).Run(OkStatus()); } void StreamingRuntimeApplication::StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason stop_reason, - int32_t net_error_code) { + EmbedderApplication::ApplicationStopReason stop_reason, + net::Error net_error_code) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!receiver_session_client_) { - DLOG(INFO) << "Streaming session never started prior to " << *this - << " stop."; + DLOG(WARNING) << "Streaming session never started prior to " << *this + << " stop."; } receiver_session_client_.reset(); @@ -117,4 +113,4 @@ return true; } -} // namespace chromecast +} // namespace cast_receiver
diff --git a/components/cast_receiver/browser/streaming_runtime_application.h b/components/cast_receiver/browser/streaming_runtime_application.h new file mode 100644 index 0000000..35a7be3 --- /dev/null +++ b/components/cast_receiver/browser/streaming_runtime_application.h
@@ -0,0 +1,65 @@ +// Copyright 2021 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_CAST_RECEIVER_BROWSER_STREAMING_RUNTIME_APPLICATION_H_ +#define COMPONENTS_CAST_RECEIVER_BROWSER_STREAMING_RUNTIME_APPLICATION_H_ + +#include "components/cast_receiver/browser/public/application_config.h" +#include "components/cast_receiver/browser/runtime_application_base.h" +#include "components/cast_receiver/browser/streaming_receiver_session_client.h" +#include "components/cast_streaming/browser/public/network_context_getter.h" +#include "net/base/net_errors.h" + +namespace cast_receiver { + +class ApplicationClient; +class MessagePortService; + +class StreamingRuntimeApplication final + : public RuntimeApplicationBase, + public StreamingReceiverSessionClient::Handler { + public: + // |application_client| is expected to exist for the lifetime of this + // instance. + StreamingRuntimeApplication(std::string cast_session_id, + ApplicationConfig app_config, + ApplicationClient& application_client); + ~StreamingRuntimeApplication() override; + + StreamingRuntimeApplication(StreamingRuntimeApplication& other) = delete; + StreamingRuntimeApplication& operator=(StreamingRuntimeApplication& other) = + delete; + + private: + // RuntimeApplicationBase implementation: + void Launch(StatusCallback callback) override; + void StopApplication(EmbedderApplication::ApplicationStopReason stop_reason, + net::Error net_error_code) override; + bool IsStreamingApplication() const override; + + // StreamingReceiverSessionClient::Handler implementation: + void OnStreamingSessionStarted() override; + void OnError() override; + void OnResolutionChanged( + const gfx::Rect& size, + const media::VideoTransformation& transformation) override; + + base::raw_ref<ApplicationClient> const application_client_; + + // Returns the network context used by |receiver_session_client_|. + const cast_streaming::NetworkContextGetter network_context_getter_; + + // Handles communication with other MessagePort endpoints. + std::unique_ptr<MessagePortService> message_port_service_; + + // Object responsible for maintaining the lifetime of the streaming session. + std::unique_ptr<StreamingReceiverSessionClient> receiver_session_client_; + + SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory<StreamingRuntimeApplication> weak_factory_{this}; +}; + +} // namespace cast_receiver + +#endif // COMPONENTS_CAST_RECEIVER_BROWSER_STREAMING_RUNTIME_APPLICATION_H_
diff --git a/chromecast/cast_core/runtime/browser/web_runtime_application.cc b/components/cast_receiver/browser/web_runtime_application.cc similarity index 72% rename from chromecast/cast_core/runtime/browser/web_runtime_application.cc rename to components/cast_receiver/browser/web_runtime_application.cc index 59a4ada..3d44285 100644 --- a/chromecast/cast_core/runtime/browser/web_runtime_application.cc +++ b/components/cast_receiver/browser/web_runtime_application.cc
@@ -2,11 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chromecast/cast_core/runtime/browser/web_runtime_application.h" +#include "components/cast_receiver/browser/web_runtime_application.h" #include "base/task/bind_post_task.h" -#include "chromecast/browser/cast_web_service.h" -#include "chromecast/common/feature_constants.h" #include "components/cast_receiver/browser/public/embedder_application.h" #include "components/cast_receiver/browser/public/message_port_service.h" #include "components/url_rewrite/browser/url_request_rewrite_rules_manager.h" @@ -14,14 +12,15 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_controller_factory.h" #include "mojo/public/cpp/bindings/associated_remote.h" +#include "net/base/net_errors.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" -namespace chromecast { +namespace cast_receiver { WebRuntimeApplication::WebRuntimeApplication( std::string cast_session_id, - cast_receiver::ApplicationConfig config, - cast_receiver::ApplicationClient& application_client) + ApplicationConfig config, + ApplicationClient& application_client) : RuntimeApplicationBase(std::move(cast_session_id), std::move(config), application_client) { @@ -30,15 +29,14 @@ WebRuntimeApplication::~WebRuntimeApplication() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kUserRequest, - net::OK); + StopApplication(EmbedderApplication::ApplicationStopReason::kUserRequest, + net::ERR_ABORTED); } void WebRuntimeApplication::Launch(StatusCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - LOG(INFO) << "Launching application: " << *this; + DVLOG(1) << "Launching application: " << *this; SetContentPermissions(*embedder_application().GetWebContents()); @@ -58,7 +56,7 @@ weak_factory_.GetWeakPtr()))); // Signal that application is launching. - std::move(callback).Run(cast_receiver::OkStatus()); + std::move(callback).Run(OkStatus()); } bool WebRuntimeApplication::IsStreamingApplication() const { @@ -71,7 +69,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(inner_web_contents); - DLOG(INFO) << "Inner web contents created"; + DVLOG(1) << "Inner web contents created"; auto* outer_web_contents = embedder_application().GetWebContents(); if (outer_web_contents) { @@ -99,25 +97,23 @@ } void WebRuntimeApplication::OnAllBindingsReceived( - cast_receiver::Status status, + Status status, std::vector<std::string> bindings) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!status.ok()) { LOG(ERROR) << "Failed to get all bindings: " << status; - StopApplication(cast_receiver::EmbedderApplication::ApplicationStopReason:: - kRuntimeError, + StopApplication(EmbedderApplication::ApplicationStopReason::kRuntimeError, net::ERR_FAILED); return; } content::WebContentsObserver::Observe( embedder_application().GetWebContents()); - cast_receiver::PageStateObserver::Observe( - embedder_application().GetWebContents()); + PageStateObserver::Observe(embedder_application().GetWebContents()); auto* message_port_sevice = embedder_application().GetMessagePortService(); DCHECK(message_port_sevice); - bindings_manager_ = std::make_unique<cast_receiver::BindingsManager>( - *this, *message_port_sevice); + bindings_manager_ = + std::make_unique<BindingsManager>(*this, *message_port_sevice); for (auto& binding : bindings) { bindings_manager_->AddBinding(std::move(binding)); } @@ -135,31 +131,28 @@ void WebRuntimeApplication::OnError() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kRuntimeError, - 0); + StopApplication(EmbedderApplication::ApplicationStopReason::kRuntimeError, + net::ERR_UNEXPECTED); } void WebRuntimeApplication::OnPageStopped(StopReason reason, - int32_t error_code) { + net::Error error_code) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); switch (reason) { - case cast_receiver::PageStateObserver::StopReason::kUnknown: - StopApplication(cast_receiver::EmbedderApplication:: - ApplicationStopReason::kRuntimeError, + case PageStateObserver::StopReason::kUnknown: + StopApplication(EmbedderApplication::ApplicationStopReason::kRuntimeError, error_code); break; - case cast_receiver::PageStateObserver::StopReason::kApplicationRequest: - StopApplication(cast_receiver::EmbedderApplication:: - ApplicationStopReason::kApplicationRequest, - error_code); - break; - case cast_receiver::PageStateObserver::StopReason::kHttpError: + case PageStateObserver::StopReason::kApplicationRequest: StopApplication( - cast_receiver::EmbedderApplication::ApplicationStopReason::kHttpError, + EmbedderApplication::ApplicationStopReason::kApplicationRequest, error_code); break; + case PageStateObserver::StopReason::kHttpError: + StopApplication(EmbedderApplication::ApplicationStopReason::kHttpError, + error_code); + break; } } -} // namespace chromecast +} // namespace cast_receiver
diff --git a/components/cast_receiver/browser/web_runtime_application.h b/components/cast_receiver/browser/web_runtime_application.h new file mode 100644 index 0000000..3795b82 --- /dev/null +++ b/components/cast_receiver/browser/web_runtime_application.h
@@ -0,0 +1,69 @@ +// Copyright 2021 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_CAST_RECEIVER_BROWSER_WEB_RUNTIME_APPLICATION_H_ +#define COMPONENTS_CAST_RECEIVER_BROWSER_WEB_RUNTIME_APPLICATION_H_ + +#include <vector> + +#include "components/cast_receiver/browser/bindings_manager.h" +#include "components/cast_receiver/browser/page_state_observer.h" +#include "components/cast_receiver/browser/public/application_config.h" +#include "components/cast_receiver/browser/runtime_application_base.h" +#include "content/public/browser/web_contents_observer.h" + +namespace cast_receiver { + +class WebRuntimeApplication final : public RuntimeApplicationBase, + public content::WebContentsObserver, + public BindingsManager::Client, + public PageStateObserver { + public: + // |web_service| is expected to exist for the lifetime of this instance. + WebRuntimeApplication(std::string cast_session_id, + ApplicationConfig app_config, + ApplicationClient& application_client); + ~WebRuntimeApplication() override; + + WebRuntimeApplication(WebRuntimeApplication& other) = delete; + WebRuntimeApplication& operator=(WebRuntimeApplication& other) = delete; + + private: + const GURL& app_url() { + DCHECK(config().url); + return *config().url; + } + + void OnAllBindingsReceived(Status status, std::vector<std::string> bindings); + + // RuntimeApplicationBase implementation: + void Launch(StatusCallback callback) override; + bool IsStreamingApplication() const override; + + // PageStateObserver implementation: + void OnPageLoadComplete() override; + void OnPageStopped(StopReason reason, net::Error error_code) override; + + // content::WebContentsObserver implementation: + void InnerWebContentsCreated( + content::WebContents* inner_web_contents) override; + void MediaStartedPlaying(const MediaPlayerInfo& video_type, + const content::MediaPlayerId& id) override; + void MediaStoppedPlaying( + const MediaPlayerInfo& video_type, + const content::MediaPlayerId& id, + content::WebContentsObserver::MediaStoppedReason reason) override; + + // BindingsManagerWebRuntime::Client implementation: + void OnError() override; + + std::unique_ptr<BindingsManager> bindings_manager_; + + SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory<WebRuntimeApplication> weak_factory_{this}; +}; + +} // namespace cast_receiver + +#endif // COMPONENTS_CAST_RECEIVER_BROWSER_WEB_RUNTIME_APPLICATION_H_
diff --git a/components/embedder_support/android/delegate/web_contents_delegate_android.cc b/components/embedder_support/android/delegate/web_contents_delegate_android.cc index eb2d28e..5361b1d 100644 --- a/components/embedder_support/android/delegate/web_contents_delegate_android.cc +++ b/components/embedder_support/android/delegate/web_contents_delegate_android.cc
@@ -412,15 +412,6 @@ return Java_WebContentsDelegateAndroid_controlsResizeView(env, obj); } -int WebContentsDelegateAndroid::GetVirtualKeyboardHeight( - content::WebContents* contents) { - JNIEnv* env = AttachCurrentThread(); - ScopedJavaLocalRef<jobject> obj = GetJavaDelegate(env); - if (obj.is_null()) - return false; - return Java_WebContentsDelegateAndroid_getVirtualKeyboardHeight(env, obj); -} - blink::mojom::DisplayMode WebContentsDelegateAndroid::GetDisplayMode( const content::WebContents* web_contents) { JNIEnv* env = base::android::AttachCurrentThread();
diff --git a/components/embedder_support/android/delegate/web_contents_delegate_android.h b/components/embedder_support/android/delegate/web_contents_delegate_android.h index d42e4b7..2b328613 100644 --- a/components/embedder_support/android/delegate/web_contents_delegate_android.h +++ b/components/embedder_support/android/delegate/web_contents_delegate_android.h
@@ -116,7 +116,6 @@ bool ShouldAnimateBrowserControlsHeightChanges() override; bool DoBrowserControlsShrinkRendererSize( content::WebContents* contents) override; - int GetVirtualKeyboardHeight(content::WebContents* contents) override; blink::mojom::DisplayMode GetDisplayMode( const content::WebContents* web_contents) override;
diff --git a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/delegate/WebContentsDelegateAndroid.java b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/delegate/WebContentsDelegateAndroid.java index f9bf9f9..a016799 100644 --- a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/delegate/WebContentsDelegateAndroid.java +++ b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/delegate/WebContentsDelegateAndroid.java
@@ -184,15 +184,6 @@ } /** - * @return If shown, returns the height of the virtual keyboard in physical pixels. Otherwise, - * returns 0. - */ - @CalledByNative - public int getVirtualKeyboardHeight() { - return 0; - } - - /** * Check and return the {@link DisplayMode} value. * * @return The {@link DisplayMode} value.
diff --git a/components/infobars/core/infobar_delegate.h b/components/infobars/core/infobar_delegate.h index 8f621b00..871bf78 100644 --- a/components/infobars/core/infobar_delegate.h +++ b/components/infobars/core/infobar_delegate.h
@@ -93,7 +93,7 @@ // Removed: DATA_REDUCTION_PROXY_INFOBAR_DELEGATE_ANDROID = 22, // Removed: NOTIFICATION_PERMISSION_INFOBAR_DELEGATE = 23, // Removed: AUTO_SIGNIN_FIRST_RUN_INFOBAR_DELEGATE = 24, - GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID = 25, + // Removed: GENERATED_PASSWORD_SAVED_INFOBAR_DELEGATE_ANDROID = 25, SAVE_PASSWORD_INFOBAR_DELEGATE_MOBILE = 26, // Removed: PEPPER_BROKER_INFOBAR_DELEGATE = 27, PERMISSION_UPDATE_INFOBAR_DELEGATE_ANDROID = 28, @@ -131,7 +131,7 @@ // Removed: WINDOW_ERROR_INFOBAR_DELEGATE_ANDROID = 60, DANGEROUS_DOWNLOAD_INFOBAR_DELEGATE_ANDROID = 61, // Removed: DESKTOP_SEARCH_REDIRECTION_INFOBAR_DELEGATE = 62, - UPDATE_PASSWORD_INFOBAR_DELEGATE_MOBILE = 63, + // Removed: UPDATE_PASSWORD_INFOBAR_DELEGATE_MOBILE = 63, // Removed: DATA_REDUCTION_PROMO_INFOBAR_DELEGATE_ANDROID = 64, AUTOFILL_CREDIT_CARD_FILLING_INFOBAR_DELEGATE_ANDROID = 65, ADS_BLOCKED_INFOBAR_DELEGATE_ANDROID = 66,
diff --git a/components/lookalikes/core/lookalike_url_util.cc b/components/lookalikes/core/lookalike_url_util.cc index 682ac68..ed6fd4a 100644 --- a/components/lookalikes/core/lookalike_url_util.cc +++ b/components/lookalikes/core/lookalike_url_util.cc
@@ -179,8 +179,8 @@ // using the format_url binary (components/url_formatter/tools/format_url.cc) const char* kSkeletonsOfPopularKeywordsForCSQ[] = { // Security - "account", "activate", "active", "adrnin", "login", "logout", - "online", "password", "secure", "security", "signin", "signout"}; + "account", "activate", "adrnin", "login", "logout", + "password", "secure", "security", "signin", "signout"}; // Minimum length of brand to be checked for Combo Squatting. const size_t kMinBrandNameLengthForComboSquatting = 4;
diff --git a/components/no_state_prefetch/browser/no_state_prefetch_manager.cc b/components/no_state_prefetch/browser/no_state_prefetch_manager.cc index 358d7104..96ad48a 100644 --- a/components/no_state_prefetch/browser/no_state_prefetch_manager.cc +++ b/components/no_state_prefetch/browser/no_state_prefetch_manager.cc
@@ -216,16 +216,6 @@ } std::unique_ptr<NoStatePrefetchHandle> -NoStatePrefetchManager::StartPrefetchingFromNavigationPredictor( - const GURL& url, - SessionStorageNamespace* session_storage_namespace, - const gfx::Size& size) { - return StartPrefetchingWithPreconnectFallback( - ORIGIN_NAVIGATION_PREDICTOR, url, content::Referrer(), absl::nullopt, - gfx::Rect(size), session_storage_namespace); -} - -std::unique_ptr<NoStatePrefetchHandle> NoStatePrefetchManager::AddIsolatedPrerender( const GURL& url, SessionStorageNamespace* session_storage_namespace,
diff --git a/components/no_state_prefetch/browser/no_state_prefetch_manager.h b/components/no_state_prefetch/browser/no_state_prefetch_manager.h index e7d69c5..bb9c7db 100644 --- a/components/no_state_prefetch/browser/no_state_prefetch_manager.h +++ b/components/no_state_prefetch/browser/no_state_prefetch_manager.h
@@ -122,16 +122,6 @@ content::SessionStorageNamespace* session_storage_namespace, const gfx::Size& size); - // Starts a prefetch for the prefetch url from NavigationPredictor on page - // load, if NoStatePrefetch and prefetch_after_preconnect are true. Uses the - // NavigationPredictor's browser context and the default - // SessionStorageNamespace. Returns a NoStatePrefetchHandle or NULL. - std::unique_ptr<NoStatePrefetchHandle> - StartPrefetchingFromNavigationPredictor( - const GURL& url, - content::SessionStorageNamespace* session_storage_namespace, - const gfx::Size& size); - // Adds a prerender for the prefetch url from IsolatedPrerender on // page load, if NoStatePrefetch and prefetch_after_preconnect are true. // Uses the NavigationPredictor's browser context and the default
diff --git a/components/omnibox/browser/autocomplete_controller.cc b/components/omnibox/browser/autocomplete_controller.cc index d6bb3fd..30dcfc8 100644 --- a/components/omnibox/browser/autocomplete_controller.cc +++ b/components/omnibox/browser/autocomplete_controller.cc
@@ -889,14 +889,6 @@ #endif } -void AutocompleteController::SetTailSuggestContentPrefixes() { - result_.SetTailSuggestContentPrefixes(); -} - -void AutocompleteController::SetTailSuggestCommonPrefixes() { - result_.SetTailSuggestCommonPrefixes(); -} - const AutocompleteResult& AutocompleteController::result() const { return DebouncingEnabled() ? published_result_ : result_; } @@ -987,6 +979,8 @@ UpdateKeywordDescriptions(&result_); UpdateAssociatedKeywords(&result_); UpdateAssistedQueryStats(&result_); + UpdateTailSuggestPrefix(&result_); + if (search_provider_) search_provider_->RegisterDisplayedAnswers(result_); @@ -1214,6 +1208,17 @@ } } +void AutocompleteController::UpdateTailSuggestPrefix( + AutocompleteResult* result) { + const auto common_prefix = result->GetCommonPrefix(); + if (!common_prefix.empty()) { + for (auto& match : *result) { + if (match.type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL) + match.tail_suggest_common_prefix = common_prefix; + } + } +} + void AutocompleteController::NotifyChanged() { // Will log metrics for how many matches changed. Will also log timing metrics // for the current request if it's complete; otherwise, will just update
diff --git a/components/omnibox/browser/autocomplete_controller.h b/components/omnibox/browser/autocomplete_controller.h index b971536..14331da 100644 --- a/components/omnibox/browser/autocomplete_controller.h +++ b/components/omnibox/browser/autocomplete_controller.h
@@ -186,13 +186,6 @@ // Constructs and sets the final destination URL on the given match. void SetMatchDestinationURL(AutocompleteMatch* match) const; - // Populates tail_suggest_common_prefix on the matches as well as prepends - // ellipses. - void SetTailSuggestContentPrefixes(); - - // Populates tail_suggest_common_prefix on the matches. - void SetTailSuggestCommonPrefixes(); - HistoryURLProvider* history_url_provider() const { return history_url_provider_; } @@ -285,9 +278,9 @@ void UpdateResult(bool regenerate_result, bool force_notify_default_match_changed); - // Updates |result| to populate each match's |associated_keyword| if that - // match can show a keyword hint. |result| should be sorted by - // relevance before this is called. + // Updates `result` to populate each match's `associated_keyword` if that + // match can show a keyword hint. `result` should be sorted by relevance + // before this is called. void UpdateAssociatedKeywords(AutocompleteResult* result); // For each group of contiguous matches from the same TemplateURL, show the @@ -295,10 +288,13 @@ // Pack matches show their URLs as descriptions instead of the provider name. void UpdateKeywordDescriptions(AutocompleteResult* result); - // For each AutocompleteMatch in |result|, updates the assisted query stats + // For each AutocompleteMatch in `result`, updates the assisted query stats // iff the provider's TemplateURL supports it. void UpdateAssistedQueryStats(AutocompleteResult* result); + // Update the tail suggestions' `tail_suggest_common_prefix`. + void UpdateTailSuggestPrefix(AutocompleteResult* result); + // Calls AutocompleteController::Observer::OnResultChanged() and if done sends // AUTOCOMPLETE_CONTROLLER_RESULT_READY. void NotifyChanged();
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index ea2f81a..63d3fb973 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -1244,38 +1244,6 @@ } } -void AutocompleteMatch::SetTailSuggestCommonPrefix( - const std::u16string& common_prefix) { - // Prevent re-addition of prefix. - if (type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL && - tail_suggest_common_prefix.empty()) { - tail_suggest_common_prefix = common_prefix; - } -} - -void AutocompleteMatch::SetTailSuggestContentPrefix( - const std::u16string& common_prefix) { - // Prevent re-addition of prefix. - if (type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL && - tail_suggest_common_prefix.empty()) { - SetTailSuggestCommonPrefix(common_prefix); - // Insert an ellipsis before uncommon part. - const std::u16string ellipsis = kEllipsis; - contents = ellipsis + contents; - // If the first class is not already NONE, prepend a NONE class for the new - // ellipsis. - if (contents_class.empty() || - (contents_class[0].offset == 0 && - contents_class[0].style != ACMatchClassification::NONE)) { - contents_class.insert(contents_class.begin(), - {0, ACMatchClassification::NONE}); - } - // Shift existing styles. - for (size_t i = 1; i < contents_class.size(); ++i) - contents_class[i].offset += ellipsis.size(); - } -} - size_t AutocompleteMatch::EstimateMemoryUsage() const { size_t res = 0;
diff --git a/components/omnibox/browser/autocomplete_match.h b/components/omnibox/browser/autocomplete_match.h index 1473aba..d866d2e 100644 --- a/components/omnibox/browser/autocomplete_match.h +++ b/components/omnibox/browser/autocomplete_match.h
@@ -555,13 +555,6 @@ // Input "x" with prevent_inline_autocomplete will allow default match "x". void SetAllowedToBeDefault(const AutocompleteInput& input); - // If this match is a tail suggestion, prepends the passed |common_prefix|. - void SetTailSuggestCommonPrefix(const std::u16string& common_prefix); - - // If this match is a tail suggestion, prepends the passed |common_prefix| - // and adds ellipses to contents. - void SetTailSuggestContentPrefix(const std::u16string& common_prefix); - // Estimates dynamic memory usage. // See base/trace_event/memory_usage_estimator.h for more info. size_t EstimateMemoryUsage() const; @@ -677,7 +670,9 @@ // Optional override to use for types that specify an icon sub-type. DocumentType document_type = DocumentType::NONE; - // Holds the common part of tail suggestion. + // Holds the common part of tail suggestion. Used to indent the contents. + // Can't simply store the character length of the string, as different + // characters may have different rendered widths. std::u16string tail_suggest_common_prefix; // The main text displayed in the address bar dropdown.
diff --git a/components/omnibox/browser/autocomplete_match_unittest.cc b/components/omnibox/browser/autocomplete_match_unittest.cc index 0534c45..58def57e 100644 --- a/components/omnibox/browser/autocomplete_match_unittest.cc +++ b/components/omnibox/browser/autocomplete_match_unittest.cc
@@ -20,16 +20,6 @@ namespace { -bool EqualClassifications(const ACMatchClassifications& lhs, - const ACMatchClassifications& rhs) { - if (lhs.size() != rhs.size()) - return false; - for (size_t n = 0; n < lhs.size(); ++n) - if (lhs[n].style != rhs[n].style || lhs[n].offset != rhs[n].offset) - return false; - return true; -} - void TestSetAllowedToBeDefault(int caseI, const std::string input_text, bool input_prevent_inline_autocomplete, @@ -155,34 +145,6 @@ "0,2," "1,0," "5,7," "6,1," "17,0")))); } -TEST(AutocompleteMatchTest, InlineTailPrefix) { - struct TestData { - std::string before_contents, after_contents; - ACMatchClassifications before_contents_class, after_contents_class; - } cases[] = { - {"90123456", - "... 90123456", - // should prepend ellipsis, and offset remainder - {{0, ACMatchClassification::NONE}, {2, ACMatchClassification::MATCH}}, - {{0, ACMatchClassification::NONE}, {6, ACMatchClassification::MATCH}}}, - {"90123456", - "... 90123456", - // should prepend ellipsis - {}, - {{0, ACMatchClassification::NONE}}}, - }; - for (const auto& test_case : cases) { - AutocompleteMatch match; - match.type = AutocompleteMatchType::SEARCH_SUGGEST_TAIL; - match.contents = base::UTF8ToUTF16(test_case.before_contents); - match.contents_class = test_case.before_contents_class; - match.SetTailSuggestContentPrefix(u"12345678"); - EXPECT_EQ(match.contents, base::UTF8ToUTF16(test_case.after_contents)); - EXPECT_TRUE(EqualClassifications(match.contents_class, - test_case.after_contents_class)); - } -} - TEST(AutocompleteMatchTest, GetMatchComponents) { struct MatchComponentsTestData { const std::string url;
diff --git a/components/omnibox/browser/autocomplete_result.cc b/components/omnibox/browser/autocomplete_result.cc index 8c57cc7..008cd9e3 100644 --- a/components/omnibox/browser/autocomplete_result.cc +++ b/components/omnibox/browser/autocomplete_result.cc
@@ -995,25 +995,6 @@ return common_prefix; } -void AutocompleteResult::SetTailSuggestCommonPrefixes() { - std::u16string common_prefix = GetCommonPrefix(); - - if (!common_prefix.empty()) { - for (auto& match : matches_) - match.SetTailSuggestCommonPrefix(common_prefix); - } -} - -void AutocompleteResult::SetTailSuggestContentPrefixes() { - std::u16string common_prefix = GetCommonPrefix(); - - if (!common_prefix.empty()) { - for (auto& match : matches_) { - match.SetTailSuggestContentPrefix(common_prefix); - } - } -} - size_t AutocompleteResult::EstimateMemoryUsage() const { return base::trace_event::EstimateMemoryUsage(matches_); }
diff --git a/components/omnibox/browser/autocomplete_result.h b/components/omnibox/browser/autocomplete_result.h index 9a61c7b4..b5d6e9c 100644 --- a/components/omnibox/browser/autocomplete_result.h +++ b/components/omnibox/browser/autocomplete_result.h
@@ -219,13 +219,6 @@ // Gets common prefix from SEARCH_SUGGEST_TAIL matches std::u16string GetCommonPrefix(); - // Populates tail_suggest_common_prefix on the matches as well as prepends - // ellipses. - void SetTailSuggestContentPrefixes(); - - // Populates tail_suggest_common_prefix on the matches. - void SetTailSuggestCommonPrefixes(); - // Estimates dynamic memory usage. // See base/trace_event/memory_usage_estimator.h for more info. size_t EstimateMemoryUsage() const;
diff --git a/components/omnibox/browser/autocomplete_result_unittest.cc b/components/omnibox/browser/autocomplete_result_unittest.cc index 1295bed..39b3c2f 100644 --- a/components/omnibox/browser/autocomplete_result_unittest.cc +++ b/components/omnibox/browser/autocomplete_result_unittest.cc
@@ -2323,76 +2323,6 @@ } } -namespace { - -bool EqualClassifications(const std::vector<ACMatchClassification>& lhs, - const std::vector<ACMatchClassification>& rhs) { - if (lhs.size() != rhs.size()) - return false; - for (size_t n = 0; n < lhs.size(); ++n) - if (lhs[n].style != rhs[n].style || lhs[n].offset != rhs[n].offset) - return false; - return true; -} - -} // namespace - -TEST_F(AutocompleteResultTest, InlineTailPrefixes) { - struct TestData { - AutocompleteMatchType::Type type; - std::string before_contents, after_contents; - std::vector<ACMatchClassification> before_contents_class; - std::vector<ACMatchClassification> after_contents_class; - } cases[] = { - // It should not touch this, since it's not a tail suggestion. - { - AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, - "this is a test", - "this is a test", - {{0, ACMatchClassification::NONE}, {9, ACMatchClassification::MATCH}}, - {{0, ACMatchClassification::NONE}, {9, ACMatchClassification::MATCH}}, - }, - // Make sure it finds this tail suggestion, and prepends appropriately. - { - AutocompleteMatchType::SEARCH_SUGGEST_TAIL, - "a recording", - "... a recording", - {{0, ACMatchClassification::MATCH}}, - {{0, ACMatchClassification::NONE}, {4, ACMatchClassification::MATCH}}, - }, - }; - ACMatches matches; - for (const auto& test_case : cases) { - AutocompleteMatch match; - match.type = test_case.type; - match.contents = base::UTF8ToUTF16(test_case.before_contents); - for (const auto& classification : test_case.before_contents_class) - match.contents_class.push_back(classification); - matches.push_back(match); - } - // Tail suggestion needs one-off initialization. - matches[1].RecordAdditionalInfo(kACMatchPropertyContentsStartIndex, "9"); - matches[1].RecordAdditionalInfo(kACMatchPropertySuggestionText, - "this is a test"); - AutocompleteResult result; - result.AppendMatches(matches); - result.SetTailSuggestContentPrefixes(); - for (size_t i = 0; i < std::size(cases); ++i) { - EXPECT_EQ(result.match_at(i)->contents, - base::UTF8ToUTF16(cases[i].after_contents)); - EXPECT_TRUE(EqualClassifications(result.match_at(i)->contents_class, - cases[i].after_contents_class)); - } - // Run twice and make sure that it doesn't re-prepend ellipsis. - result.SetTailSuggestContentPrefixes(); - for (size_t i = 0; i < std::size(cases); ++i) { - EXPECT_EQ(result.match_at(i)->contents, - base::UTF8ToUTF16(cases[i].after_contents)); - EXPECT_TRUE(EqualClassifications(result.match_at(i)->contents_class, - cases[i].after_contents_class)); - } -} - TEST_F(AutocompleteResultTest, ConvertsOpenTabsCorrectly) { AutocompleteResult result; ACMatches matches;
diff --git a/components/omnibox/browser/base_search_provider.cc b/components/omnibox/browser/base_search_provider.cc index f3d87e81..544a228 100644 --- a/components/omnibox/browser/base_search_provider.cc +++ b/components/omnibox/browser/base_search_provider.cc
@@ -166,6 +166,101 @@ // static AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion( + AutocompleteProvider* autocomplete_provider, + const AutocompleteInput& input, + const bool in_keyword_mode, + const SearchSuggestionParser::SuggestResult& suggestion, + const TemplateURL* template_url, + const SearchTermsData& search_terms_data, + int accepted_suggestion, + bool append_extra_query_params_from_command_line) { + AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false, + suggestion.type()); + + if (!template_url) + return match; + match.keyword = template_url->keyword(); + match.image_dominant_color = suggestion.image_dominant_color(); + match.image_url = suggestion.image_url(); + match.entity_id = suggestion.entity_id(); + match.contents = suggestion.match_contents(); + match.contents_class = suggestion.match_contents_class(); + match.suggestion_group_id = suggestion.suggestion_group_id(); + match.answer = suggestion.answer(); + for (const int subtype : suggestion.subtypes()) { + match.subtypes.insert(SuggestSubtypeForNumber(subtype)); + } + if (suggestion.type() == AutocompleteMatchType::SEARCH_SUGGEST_TAIL) { + match.RecordAdditionalInfo(kACMatchPropertySuggestionText, + suggestion.suggestion()); + match.RecordAdditionalInfo(kACMatchPropertyContentsPrefix, + suggestion.match_contents_prefix()); + match.RecordAdditionalInfo( + kACMatchPropertyContentsStartIndex, + static_cast<int>(suggestion.suggestion().length() - + match.contents.length())); + } + + if (!suggestion.annotation().empty()) { + match.description = suggestion.annotation(); + AutocompleteMatch::AddLastClassificationIfNecessary( + &match.description_class, 0, ACMatchClassification::NONE); + } + + const std::u16string input_lower = base::i18n::ToLower(input.text()); + // suggestion.match_contents() should have already been collapsed. + match.allowed_to_be_default_match = + (!in_keyword_mode || suggestion.from_keyword()) && + (base::CollapseWhitespace(input_lower, false) == + base::i18n::ToLower(suggestion.match_contents())); + + if (suggestion.from_keyword()) + match.from_keyword = true; + + // We only allow inlinable navsuggestions that were received before the + // last keystroke because we don't want asynchronous inline autocompletions. + if (!input.prevent_inline_autocomplete() && + !suggestion.received_after_last_keystroke() && + (!in_keyword_mode || suggestion.from_keyword()) && + base::StartsWith(base::i18n::ToLower(suggestion.suggestion()), + input_lower, base::CompareCase::SENSITIVE)) { + match.inline_autocompletion = + suggestion.suggestion().substr(input.text().length()); + match.allowed_to_be_default_match = true; + } + + const TemplateURLRef& search_url = template_url->url_ref(); + DCHECK(search_url.SupportsReplacement(search_terms_data)); + std::u16string query(suggestion.suggestion()); + std::u16string original_query(input.text()); + if (suggestion.type() == AutocompleteMatchType::CALCULATOR) { + // Use query text, rather than the calculator answer suggestion, to search. + query = original_query; + original_query.clear(); + } + match.fill_into_edit = GetFillIntoEdit(suggestion, template_url); + match.search_terms_args = + std::make_unique<TemplateURLRef::SearchTermsArgs>(query); + match.search_terms_args->original_query = original_query; + match.search_terms_args->accepted_suggestion = accepted_suggestion; + match.search_terms_args->additional_query_params = + suggestion.additional_query_params(); + match.search_terms_args->append_extra_query_params_from_command_line = + append_extra_query_params_from_command_line; + // Must be set for deduplication and navigation. AutocompleteController will + // ultimately overwrite this with the searchbox stats before navigation. + match.destination_url = GURL(search_url.ReplaceSearchTerms( + *match.search_terms_args, search_terms_data)); + + // Search results don't look like URLs. + match.transition = suggestion.from_keyword() ? ui::PAGE_TRANSITION_KEYWORD + : ui::PAGE_TRANSITION_GENERATED; + + return match; +} + +// static +AutocompleteMatch BaseSearchProvider::CreateShortcutSearchSuggestion( const std::u16string& suggestion, AutocompleteMatchType::Type type, bool from_keyword, @@ -366,102 +461,6 @@ BaseSearchProvider::~BaseSearchProvider() {} // static -AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion( - AutocompleteProvider* autocomplete_provider, - const AutocompleteInput& input, - const bool in_keyword_mode, - const SearchSuggestionParser::SuggestResult& suggestion, - const TemplateURL* template_url, - const SearchTermsData& search_terms_data, - int accepted_suggestion, - bool append_extra_query_params_from_command_line) { - AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false, - suggestion.type()); - - if (!template_url) - return match; - match.keyword = template_url->keyword(); - match.image_dominant_color = suggestion.image_dominant_color(); - match.image_url = suggestion.image_url(); - match.entity_id = suggestion.entity_id(); - match.contents = suggestion.match_contents(); - match.contents_class = suggestion.match_contents_class(); - match.suggestion_group_id = suggestion.suggestion_group_id(); - match.answer = suggestion.answer(); - for (const int subtype : suggestion.subtypes()) { - match.subtypes.insert(SuggestSubtypeForNumber(subtype)); - } - if (suggestion.type() == AutocompleteMatchType::SEARCH_SUGGEST_TAIL) { - match.RecordAdditionalInfo(kACMatchPropertySuggestionText, - suggestion.suggestion()); - match.RecordAdditionalInfo(kACMatchPropertyContentsPrefix, - suggestion.match_contents_prefix()); - match.RecordAdditionalInfo( - kACMatchPropertyContentsStartIndex, - static_cast<int>( - suggestion.suggestion().length() - match.contents.length())); - } - - if (!suggestion.annotation().empty()) { - match.description = suggestion.annotation(); - AutocompleteMatch::AddLastClassificationIfNecessary( - &match.description_class, 0, ACMatchClassification::NONE); - } - - const std::u16string input_lower = base::i18n::ToLower(input.text()); - // suggestion.match_contents() should have already been collapsed. - match.allowed_to_be_default_match = - (!in_keyword_mode || suggestion.from_keyword()) && - (base::CollapseWhitespace(input_lower, false) == - base::i18n::ToLower(suggestion.match_contents())); - - if (suggestion.from_keyword()) - match.from_keyword = true; - - // We only allow inlinable navsuggestions that were received before the - // last keystroke because we don't want asynchronous inline autocompletions. - if (!input.prevent_inline_autocomplete() && - !suggestion.received_after_last_keystroke() && - (!in_keyword_mode || suggestion.from_keyword()) && - base::StartsWith( - base::i18n::ToLower(suggestion.suggestion()), input_lower, - base::CompareCase::SENSITIVE)) { - match.inline_autocompletion = - suggestion.suggestion().substr(input.text().length()); - match.allowed_to_be_default_match = true; - } - - const TemplateURLRef& search_url = template_url->url_ref(); - DCHECK(search_url.SupportsReplacement(search_terms_data)); - std::u16string query(suggestion.suggestion()); - std::u16string original_query(input.text()); - if (suggestion.type() == AutocompleteMatchType::CALCULATOR) { - // Use query text, rather than the calculator answer suggestion, to search. - query = original_query; - original_query.clear(); - } - match.fill_into_edit = GetFillIntoEdit(suggestion, template_url); - match.search_terms_args = - std::make_unique<TemplateURLRef::SearchTermsArgs>(query); - match.search_terms_args->original_query = original_query; - match.search_terms_args->accepted_suggestion = accepted_suggestion; - match.search_terms_args->additional_query_params = - suggestion.additional_query_params(); - match.search_terms_args->append_extra_query_params_from_command_line = - append_extra_query_params_from_command_line; - // Must be set for deduplication and navigation. AutocompleteController will - // ultimately overwrite this with the searchbox stats before navigation. - match.destination_url = GURL(search_url.ReplaceSearchTerms( - *match.search_terms_args, search_terms_data)); - - // Search results don't look like URLs. - match.transition = suggestion.from_keyword() ? ui::PAGE_TRANSITION_KEYWORD - : ui::PAGE_TRANSITION_GENERATED; - - return match; -} - -// static std::u16string BaseSearchProvider::GetFillIntoEdit( const SearchSuggestionParser::SuggestResult& suggest_result, const TemplateURL* template_url) {
diff --git a/components/omnibox/browser/base_search_provider.h b/components/omnibox/browser/base_search_provider.h index 999447d..2ea8c00 100644 --- a/components/omnibox/browser/base_search_provider.h +++ b/components/omnibox/browser/base_search_provider.h
@@ -46,17 +46,6 @@ // Returns whether |match| is flagged as a query that should be prerendered. static bool ShouldPrerender(const AutocompleteMatch& match); - // Returns a simpler AutocompleteMatch suitable for persistence like in - // ShortcutsDatabase. This wrapper function uses a number of default values - // that may or may not be appropriate for your needs. - // NOTE: Use with care. Most likely you want the other CreateSearchSuggestion. - static AutocompleteMatch CreateSearchSuggestion( - const std::u16string& suggestion, - AutocompleteMatchType::Type type, - bool from_keyword_provider, - const TemplateURL* template_url, - const SearchTermsData& search_terms_data); - // Returns an AutocompleteMatch with the given |autocomplete_provider| // for the search |suggestion|, which represents a search via |template_url|. // If |template_url| is NULL, returns a match with an invalid destination URL. @@ -83,8 +72,16 @@ int accepted_suggestion, bool append_extra_query_params_from_command_line); - // A helper function to convert result from on device providers to - // AutocompleteMatch instance. + // A helper function to return an AutocompleteMatch suitable for persistence + // in ShortcutsDatabase. + static AutocompleteMatch CreateShortcutSearchSuggestion( + const std::u16string& suggestion, + AutocompleteMatchType::Type type, + bool from_keyword_provider, + const TemplateURL* template_url, + const SearchTermsData& search_terms_data); + + // A helper function to return an AutocompleteMatch for OnDeviceHeadProvider. static AutocompleteMatch CreateOnDeviceSearchSuggestion( AutocompleteProvider* autocomplete_provider, const AutocompleteInput& input,
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index 67cd374..68a779d 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -777,11 +777,7 @@ const base::FeatureParam<int> kOmniboxLocalZeroSuggestAgeThresholdParam( &omnibox::kOmniboxLocalZeroSuggestAgeThreshold, "OmniboxLocalZeroSuggestAgeThreshold", -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) - 60); -#else 90); -#endif base::Time GetLocalHistoryZeroSuggestAgeThreshold() { return (base::Time::Now() - @@ -795,11 +791,7 @@ const base::FeatureParam<bool> kPrefixSuggestIgnoreDuplicateVisits( &omnibox::kLocalHistorySuggestRevamp, "PrefixSuggestIgnoreDuplicateVisits", -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) - false); -#else true); -#endif // Short bookmarks.
diff --git a/components/omnibox/browser/omnibox_field_trial_unittest.cc b/components/omnibox/browser/omnibox_field_trial_unittest.cc index 8dd7f0b..0a527bc 100644 --- a/components/omnibox/browser/omnibox_field_trial_unittest.cc +++ b/components/omnibox/browser/omnibox_field_trial_unittest.cc
@@ -358,11 +358,7 @@ base::test::ScopedFeatureList scoped_feature_list_; // Verify the default value. -#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) - const int expected_age_threshold_days = 60; -#else const int expected_age_threshold_days = 90; -#endif base::Time age_threshold = OmniboxFieldTrial::GetLocalHistoryZeroSuggestAgeThreshold(); EXPECT_EQ(expected_age_threshold_days,
diff --git a/components/omnibox/browser/shortcuts_backend.cc b/components/omnibox/browser/shortcuts_backend.cc index 25a704f..2b909aa 100644 --- a/components/omnibox/browser/shortcuts_backend.cc +++ b/components/omnibox/browser/shortcuts_backend.cc
@@ -289,7 +289,7 @@ if (AutocompleteMatch::IsSpecializedSearchType(match.type)) { DCHECK(match.search_terms_args); - temp = BaseSearchProvider::CreateSearchSuggestion( + temp = BaseSearchProvider::CreateShortcutSearchSuggestion( match.search_terms_args->search_terms, match_type, ui::PageTransitionCoreTypeIs(match.transition, ui::PAGE_TRANSITION_KEYWORD),
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc index 0e9d268..4bc2b81b 100644 --- a/components/omnibox/common/omnibox_features.cc +++ b/components/omnibox/common/omnibox_features.cc
@@ -199,7 +199,7 @@ // zero-prefix and prefix suggestions. BASE_FEATURE(kLocalHistorySuggestRevamp, "LocalHistorySuggestRevamp", - enabled_by_default_desktop_only); + base::FEATURE_ENABLED_BY_DEFAULT); // Enables local history zero-prefix suggestions in every context in which the // remote zero-prefix suggestions are enabled. @@ -214,7 +214,7 @@ // parameter, OmniboxFieldTrial::kOmniboxLocalZeroSuggestAgeThresholdParam. BASE_FEATURE(kOmniboxLocalZeroSuggestAgeThreshold, "OmniboxLocalZeroSuggestAgeThreshold", - enabled_by_default_desktop_only); + base::FEATURE_ENABLED_BY_DEFAULT); // Mainly used to enable sending INTERACTION_CLOBBER focus type for zero-prefix // requests with an empty input on Web/SRP on Mobile. Enabled by default on
diff --git a/components/pdf/browser/pdf_navigation_throttle.cc b/components/pdf/browser/pdf_navigation_throttle.cc index 619290d..3deb8ea 100644 --- a/components/pdf/browser/pdf_navigation_throttle.cc +++ b/components/pdf/browser/pdf_navigation_throttle.cc
@@ -73,6 +73,29 @@ params.is_renderer_initiated = false; params.is_pdf = true; + // Reset the source SiteInstance. This is a workaround for a lifetime bug: + // leaving the source SiteInstance in OpenURLParams could inadvertently + // prolong the SiteInstance's lifetime beyond the lifetime of the + // BrowserContext it's associated with. The BrowserContext could get + // destroyed after the task below is scheduled but before it runs (see + // https://crbug.com/1382761), and even though the task uses a WebContents + // WeakPtr to return early in that case, the task's OpenURLParams would only + // get destroyed and decrement the source SiteInstance's refcount at the time + // of that early return, which is already after the BrowserContext is + // destroyed. This can cause logic in the SiteInstance destructor to trip up + // if it tries to use the SiteInstance's BrowserContext. + // + // Fortunately, the source SiteInstance of this navigation should always + // correspond to the PDF extension loaded in the primary main frame of + // `contents`. Hence, if the navigation task does run and does not get + // canceled due to WebContents becoming null, we can restore the source + // SiteInstance at that point. + // + // TODO(crbug.com/1382761): This should be fixed in a more systematic way. + DCHECK_EQ(params.source_site_instance, + contents->GetPrimaryMainFrame()->GetSiteInstance()); + params.source_site_instance.reset(); + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce( @@ -80,11 +103,18 @@ const content::OpenURLParams& params) { if (!web_contents) return; + + // Restore the source SiteInstance that was cleared out of the + // original OpenURLParams. + content::OpenURLParams new_params = params; + new_params.source_site_instance = + web_contents->GetPrimaryMainFrame()->GetSiteInstance(); + // `MimeHandlerViewGuest` navigates its embedder for calls to // `WebContents::OpenURL()`, so use `LoadURLWithParams()` directly // instead. web_contents->GetController().LoadURLWithParams( - content::NavigationController::LoadURLParams(params)); + content::NavigationController::LoadURLParams(new_params)); // Note that we don't need to register the stream's URL loader as a // subresource, as `MimeHandlerViewGuest::ReadyToCommitNavigation()`
diff --git a/components/pdf/browser/pdf_navigation_throttle_unittest.cc b/components/pdf/browser/pdf_navigation_throttle_unittest.cc index 01605f95..2cdbd67 100644 --- a/components/pdf/browser/pdf_navigation_throttle_unittest.cc +++ b/components/pdf/browser/pdf_navigation_throttle_unittest.cc
@@ -48,6 +48,8 @@ url, render_frame_host); navigation_handle_->set_initiator_origin( render_frame_host->GetLastCommittedOrigin()); + navigation_handle_->set_source_site_instance( + render_frame_host->GetSiteInstance()); } std::unique_ptr<PdfNavigationThrottle> CreateNavigationThrottle(
diff --git a/components/power_bookmarks/core/BUILD.gn b/components/power_bookmarks/core/BUILD.gn index cb20ed7..acb1a88 100644 --- a/components/power_bookmarks/core/BUILD.gn +++ b/components/power_bookmarks/core/BUILD.gn
@@ -48,6 +48,7 @@ "powers/power.h", "powers/power_overview.cc", "powers/power_overview.h", + "powers/search_params.h", ] public_deps = [ ":proto" ]
diff --git a/components/power_bookmarks/core/power_bookmark_service.cc b/components/power_bookmarks/core/power_bookmark_service.cc index 44dd290..7322f93 100644 --- a/components/power_bookmarks/core/power_bookmark_service.cc +++ b/components/power_bookmarks/core/power_bookmark_service.cc
@@ -12,6 +12,7 @@ #include "components/power_bookmarks/core/power_bookmark_utils.h" #include "components/power_bookmarks/core/powers/power.h" #include "components/power_bookmarks/core/powers/power_overview.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "components/power_bookmarks/core/proto/power_bookmark_meta.pb.h" #include "components/power_bookmarks/storage/power_bookmark_backend.h" @@ -58,6 +59,13 @@ .Then(std::move(callback)); } +void PowerBookmarkService::Search(const SearchParams& search_params, + PowersCallback callback) { + backend_.AsyncCall(&PowerBookmarkBackend::Search) + .WithArgs(search_params) + .Then(std::move(callback)); +} + void PowerBookmarkService::CreatePower(std::unique_ptr<Power> power, SuccessCallback callback) { // Accept existing guids if they're explicitly set. @@ -155,4 +163,4 @@ SetNodePowerBookmarkMeta(model, node, std::move(meta)); } -} // namespace power_bookmarks \ No newline at end of file +} // namespace power_bookmarks
diff --git a/components/power_bookmarks/core/power_bookmark_service.h b/components/power_bookmarks/core/power_bookmark_service.h index 578e6d7c..6e31a947 100644 --- a/components/power_bookmarks/core/power_bookmark_service.h +++ b/components/power_bookmarks/core/power_bookmark_service.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_POWER_BOOKMARKS_CORE_POWER_BOOKMARK_SERVICE_H_ #define COMPONENTS_POWER_BOOKMARKS_CORE_POWER_BOOKMARK_SERVICE_H_ +#include <memory> #include <vector> #include "base/files/file_path.h" @@ -27,6 +28,7 @@ class PowerOverview; class PowerBookmarkDataProvider; class PowerBookmarkBackend; +struct SearchParams; using PowersCallback = base::OnceCallback<void(std::vector<std::unique_ptr<Power>> powers)>; @@ -69,6 +71,10 @@ void GetPowerOverviewsForType(const PowerType& power_type, PowerOverviewsCallback callback); + // Returns a vector of Powers matching the given `search_params`. The results + // are ordered by the url they're associated with. + void Search(const SearchParams& search_params, PowersCallback callback); + // Create the given `power` in the database. If it already exists, then it // will be updated. Success of the operation is returned through the given // `callback`. @@ -125,4 +131,4 @@ } // namespace power_bookmarks -#endif // COMPONENTS_POWER_BOOKMARKS_CORE_POWER_BOOKMARK_SERVICE_H_ \ No newline at end of file +#endif // COMPONENTS_POWER_BOOKMARKS_CORE_POWER_BOOKMARK_SERVICE_H_
diff --git a/components/power_bookmarks/core/power_bookmark_service_unittest.cc b/components/power_bookmarks/core/power_bookmark_service_unittest.cc index fab564f8..a9feb35 100644 --- a/components/power_bookmarks/core/power_bookmark_service_unittest.cc +++ b/components/power_bookmarks/core/power_bookmark_service_unittest.cc
@@ -12,7 +12,6 @@ #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" -#include "base/threading/sequenced_task_runner_handle.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/test/test_bookmark_client.h" #include "components/power_bookmarks/core/power_bookmark_data_provider.h" @@ -20,6 +19,7 @@ #include "components/power_bookmarks/core/power_bookmark_service.h" #include "components/power_bookmarks/core/powers/power.h" #include "components/power_bookmarks/core/powers/power_overview.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -29,21 +29,26 @@ using testing::IsTrue; using testing::SizeIs; +namespace power_bookmarks { + namespace { -std::unique_ptr<power_bookmarks::Power> MakePower( + +std::unique_ptr<Power> MakePower( GURL url, - power_bookmarks::PowerType power_type) { - std::unique_ptr<power_bookmarks::PowerSpecifics> power_specifics = - std::make_unique<power_bookmarks::PowerSpecifics>(); - std::unique_ptr<power_bookmarks::Power> power = - std::make_unique<power_bookmarks::Power>(std::move(power_specifics)); + PowerType power_type, + std::unique_ptr<PowerSpecifics> power_specifics) { + std::unique_ptr<Power> power = + std::make_unique<Power>(std::move(power_specifics)); power->set_url(url); power->set_power_type(power_type); return power; } -} // namespace -namespace power_bookmarks { +std::unique_ptr<Power> MakePower(GURL url, PowerType power_type) { + return MakePower(url, power_type, std::make_unique<PowerSpecifics>()); +} + +} // namespace // Tests for the power bookmark service. // In-depth tests for the actual storage can be found in @@ -184,6 +189,61 @@ RunUntilIdle(); } +TEST_F(PowerBookmarkServiceTest, Search) { + base::MockCallback<SuccessCallback> success_cb; + EXPECT_CALL(success_cb, Run(IsTrue())).Times(3); + + service()->CreatePower(MakePower(GURL("https://example.com/a1.html"), + PowerType::POWER_TYPE_MOCK), + success_cb.Get()); + service()->CreatePower(MakePower(GURL("https://example.com/b1.html"), + PowerType::POWER_TYPE_MOCK), + success_cb.Get()); + service()->CreatePower(MakePower(GURL("https://example.com/a2.html"), + PowerType::POWER_TYPE_MOCK), + success_cb.Get()); + RunUntilIdle(); + + base::MockCallback<PowersCallback> powers_cb; + EXPECT_CALL(powers_cb, Run(SizeIs(2))); + + SearchParams search_params{.query = "/a"}; + service()->Search(search_params, powers_cb.Get()); + RunUntilIdle(); +} + +TEST_F(PowerBookmarkServiceTest, SearchNoteText) { + base::MockCallback<SuccessCallback> success_cb; + EXPECT_CALL(success_cb, Run(IsTrue())).Times(2); + + { + std::unique_ptr<PowerSpecifics> note_specifics = + std::make_unique<PowerSpecifics>(); + note_specifics->mutable_note_specifics()->set_plain_text("lorem ipsum"); + service()->CreatePower( + MakePower(GURL("https://example.com/a1.html"), + PowerType::POWER_TYPE_NOTE, std::move(note_specifics)), + success_cb.Get()); + } + { + std::unique_ptr<PowerSpecifics> note_specifics = + std::make_unique<PowerSpecifics>(); + note_specifics->mutable_note_specifics()->set_plain_text("not a match"); + service()->CreatePower( + MakePower(GURL("https://example.com/a2.html"), + PowerType::POWER_TYPE_NOTE, std::move(note_specifics)), + success_cb.Get()); + } + RunUntilIdle(); + + base::MockCallback<PowersCallback> powers_cb; + EXPECT_CALL(powers_cb, Run(SizeIs(1))); + + SearchParams search_params{.query = "lorem"}; + service()->Search(search_params, powers_cb.Get()); + RunUntilIdle(); +} + TEST_F(PowerBookmarkServiceTest, CreatePower) { base::MockCallback<SuccessCallback> cb; EXPECT_CALL(cb, Run(IsTrue()));
diff --git a/components/power_bookmarks/core/power_bookmark_utils.cc b/components/power_bookmarks/core/power_bookmark_utils.cc index 4be46d4..af9e99b 100644 --- a/components/power_bookmarks/core/power_bookmark_utils.cc +++ b/components/power_bookmarks/core/power_bookmark_utils.cc
@@ -8,12 +8,10 @@ #include <vector> #include "base/base64.h" -#include "base/guid.h" #include "base/i18n/string_search.h" #include "base/notreached.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/bookmarks/browser/bookmark_utils.h"
diff --git a/components/power_bookmarks/core/power_bookmark_utils.h b/components/power_bookmarks/core/power_bookmark_utils.h index bdb30e41..ecd39db 100644 --- a/components/power_bookmarks/core/power_bookmark_utils.h +++ b/components/power_bookmarks/core/power_bookmark_utils.h
@@ -65,7 +65,7 @@ // tested against the text search query. Output is put into \nodes\. Bookmarks // that are returned will match all of the other query fields that are set. For // example: if |folder| and |type| are set, all returned bookmarks will be a -// descendant of |folder| and have a power bookmark typr of |type|. +// descendant of |folder| and have a power bookmark type of |type|. void GetBookmarksMatchingProperties( bookmarks::BookmarkModel* model, const PowerBookmarkQueryFields& query,
diff --git a/components/power_bookmarks/core/powers/search_params.h b/components/power_bookmarks/core/powers/search_params.h new file mode 100644 index 0000000..dffe3994 --- /dev/null +++ b/components/power_bookmarks/core/powers/search_params.h
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_POWER_BOOKMARKS_CORE_POWERS_SEARCH_PARAMS_H_ +#define COMPONENTS_POWER_BOOKMARKS_CORE_POWERS_SEARCH_PARAMS_H_ + +#include <string> + +namespace power_bookmarks { + +// Parameters for searching power bookmarks. Used as a parameter for +// PowerBookmarkService::Search() +struct SearchParams { + // Specifies a plain text query that will be matched against the contents of + // powers. The exact semantics of matching depend on the power type. + std::string query; +}; + +} // namespace power_bookmarks + +#endif // COMPONENTS_POWER_BOOKMARKS_CORE_POWERS_SEARCH_PARAMS_H_
diff --git a/components/power_bookmarks/storage/BUILD.gn b/components/power_bookmarks/storage/BUILD.gn index b9a24c4..b188019 100644 --- a/components/power_bookmarks/storage/BUILD.gn +++ b/components/power_bookmarks/storage/BUILD.gn
@@ -34,5 +34,6 @@ "//sql", "//sql:test_support", "//testing/gtest", + "//url", ] }
diff --git a/components/power_bookmarks/storage/empty_power_bookmark_database.cc b/components/power_bookmarks/storage/empty_power_bookmark_database.cc index 4c0202b7..790bdd95 100644 --- a/components/power_bookmarks/storage/empty_power_bookmark_database.cc +++ b/components/power_bookmarks/storage/empty_power_bookmark_database.cc
@@ -4,8 +4,9 @@ #include "components/power_bookmarks/storage/empty_power_bookmark_database.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "components/power_bookmarks/core/proto/power_bookmark_specifics.pb.h" -#include "url/origin.h" +#include "url/gurl.h" namespace power_bookmarks { @@ -33,6 +34,12 @@ return std::vector<std::unique_ptr<PowerOverview>>(); } +std::vector<std::unique_ptr<Power>> +EmptyPowerBookmarkDatabase::GetPowersForSearchParams( + const SearchParams& search_params) { + return std::vector<std::unique_ptr<Power>>(); +} + bool EmptyPowerBookmarkDatabase::CreatePower(std::unique_ptr<Power> power) { return false; }
diff --git a/components/power_bookmarks/storage/empty_power_bookmark_database.h b/components/power_bookmarks/storage/empty_power_bookmark_database.h index dd31e39..b52094e 100644 --- a/components/power_bookmarks/storage/empty_power_bookmark_database.h +++ b/components/power_bookmarks/storage/empty_power_bookmark_database.h
@@ -5,15 +5,15 @@ #ifndef COMPONENTS_POWER_BOOKMARKS_STORAGE_EMPTY_POWER_BOOKMARK_DATABASE_H_ #define COMPONENTS_POWER_BOOKMARKS_STORAGE_EMPTY_POWER_BOOKMARK_DATABASE_H_ -#include "base/files/file_path.h" #include "components/power_bookmarks/core/powers/power.h" #include "components/power_bookmarks/core/powers/power_overview.h" #include "components/power_bookmarks/storage/power_bookmark_database.h" #include "url/gurl.h" -#include "url/origin.h" namespace power_bookmarks { +struct SearchParams; + // Fake database to substitute when the feature is disabled. class EmptyPowerBookmarkDatabase : public PowerBookmarkDatabase { public: @@ -32,6 +32,8 @@ const PowerType& power_type) override; std::vector<std::unique_ptr<PowerOverview>> GetPowerOverviewsForType( const PowerType& power_type) override; + std::vector<std::unique_ptr<Power>> GetPowersForSearchParams( + const SearchParams& search_params) override; bool CreatePower(std::unique_ptr<Power> power) override; bool UpdatePower(std::unique_ptr<Power> power) override; bool DeletePower(const base::GUID& guid) override;
diff --git a/components/power_bookmarks/storage/power_bookmark_backend.cc b/components/power_bookmarks/storage/power_bookmark_backend.cc index 54050df5..0e11d1c 100644 --- a/components/power_bookmarks/storage/power_bookmark_backend.cc +++ b/components/power_bookmarks/storage/power_bookmark_backend.cc
@@ -4,6 +4,7 @@ #include "components/power_bookmarks/storage/power_bookmark_backend.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "components/power_bookmarks/storage/empty_power_bookmark_database.h" #include "components/power_bookmarks/storage/power_bookmark_database_impl.h" @@ -55,6 +56,12 @@ return db_->GetPowerOverviewsForType(power_type); } +std::vector<std::unique_ptr<Power>> PowerBookmarkBackend::Search( + const SearchParams& search_params) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return db_->GetPowersForSearchParams(search_params); +} + bool PowerBookmarkBackend::CreatePower(std::unique_ptr<Power> power) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return db_->CreatePower(std::move(power));
diff --git a/components/power_bookmarks/storage/power_bookmark_backend.h b/components/power_bookmarks/storage/power_bookmark_backend.h index ed62cf5b..c86e9f6 100644 --- a/components/power_bookmarks/storage/power_bookmark_backend.h +++ b/components/power_bookmarks/storage/power_bookmark_backend.h
@@ -13,6 +13,8 @@ namespace power_bookmarks { +struct SearchParams; + // Class responsible for marshalling calls from the browser thread which the // service is called from and the background thread which the database is // run on. Calls to this class should be posted on the background task_runner. @@ -40,6 +42,9 @@ std::vector<std::unique_ptr<PowerOverview>> GetPowerOverviewsForType( const PowerType& power_type); + // Returns a vector of Powers matching the given `search_params`. + std::vector<std::unique_ptr<Power>> Search(const SearchParams& search_params); + // Create the given `power` in the database. If it already exists, then it // will be updated. Returns whether the operation was successful. bool CreatePower(std::unique_ptr<Power> power);
diff --git a/components/power_bookmarks/storage/power_bookmark_database.h b/components/power_bookmarks/storage/power_bookmark_database.h index d2c752f..1547065b 100644 --- a/components/power_bookmarks/storage/power_bookmark_database.h +++ b/components/power_bookmarks/storage/power_bookmark_database.h
@@ -5,14 +5,17 @@ #ifndef COMPONENTS_POWER_BOOKMARKS_STORAGE_POWER_BOOKMARK_DATABASE_H_ #define COMPONENTS_POWER_BOOKMARKS_STORAGE_POWER_BOOKMARK_DATABASE_H_ -#include "base/files/file_path.h" +#include <memory> +#include <vector> + #include "components/power_bookmarks/core/powers/power.h" #include "components/power_bookmarks/core/powers/power_overview.h" #include "url/gurl.h" -#include "url/origin.h" namespace power_bookmarks { +struct SearchParams; + // Interface for the database layer of the Power Bookmark database. class PowerBookmarkDatabase { public: @@ -35,6 +38,10 @@ virtual std::vector<std::unique_ptr<PowerOverview>> GetPowerOverviewsForType( const PowerType& power_type) = 0; + // Returns a vector of Powers for the given `search_params`. + virtual std::vector<std::unique_ptr<Power>> GetPowersForSearchParams( + const SearchParams& search_params) = 0; + // Create the given `power` in the database. If it already exists, then it // will be updated. Returns whether the operation was successful. virtual bool CreatePower(std::unique_ptr<Power> power) = 0;
diff --git a/components/power_bookmarks/storage/power_bookmark_database_impl.cc b/components/power_bookmarks/storage/power_bookmark_database_impl.cc index fa95bd7..8bb89cb 100644 --- a/components/power_bookmarks/storage/power_bookmark_database_impl.cc +++ b/components/power_bookmarks/storage/power_bookmark_database_impl.cc
@@ -5,8 +5,10 @@ #include "components/power_bookmarks/storage/power_bookmark_database_impl.h" #include "base/files/file_util.h" -#include "base/json/values_util.h" #include "base/notreached.h" +#include "base/strings/pattern.h" +#include "base/strings/strcat.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "components/power_bookmarks/core/proto/power_bookmark_specifics.pb.h" #include "sql/error_delegate_util.h" #include "sql/meta_table.h" @@ -63,6 +65,28 @@ return count > 0; } +bool MatchesSearchParams(const PowerBookmarkSpecifics& specifics, + const SearchParams& search_params) { + if (search_params.query.empty()) + return true; + std::string pattern = base::StrCat({"*", search_params.query, "*"}); + if (base::MatchPattern(specifics.url(), pattern)) + return true; + + // A note can be matched by its contents. + switch (specifics.power_type()) { + case PowerType::POWER_TYPE_NOTE: + if (base::MatchPattern( + specifics.power_specifics().note_specifics().plain_text(), + pattern)) + return true; + break; + default: + break; + } + return false; +} + } // namespace PowerBookmarkDatabaseImpl::PowerBookmarkDatabaseImpl( @@ -212,7 +236,7 @@ static constexpr char kGetPowersForURLSql[] = // clang-format off - "SELECT blobs.id, blobs.specifics, saves.url as url " + "SELECT blobs.id, blobs.specifics, saves.url " "FROM blobs JOIN saves ON blobs.id=saves.id " "WHERE (url=?) AND (power_type=? OR ?=?)"; // clang-format on @@ -278,6 +302,41 @@ return power_overviews; } +std::vector<std::unique_ptr<Power>> +PowerBookmarkDatabaseImpl::GetPowersForSearchParams( + const SearchParams& search_params) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // TODO(crbug.com/1382855): Optimize this query to avoid SCAN TABLE. + static constexpr char kGetPowersForSearchParamsSql[] = + // clang-format off + "SELECT blobs.id, blobs.specifics " + "FROM blobs JOIN saves ON blobs.id=saves.id " + "ORDER BY url ASC"; + // clang-format on + DCHECK(db_.IsSQLValid(kGetPowersForSearchParamsSql)); + + sql::Statement statement( + db_.GetCachedStatement(SQL_FROM_HERE, kGetPowersForSearchParamsSql)); + + std::vector<std::unique_ptr<Power>> search_results; + while (statement.Step()) { + DCHECK_EQ(2, statement.ColumnCount()); + + absl::optional<PowerBookmarkSpecifics> specifics = DeserializeOrDelete( + statement.ColumnString(1), + base::GUID::ParseLowercase(statement.ColumnString(0))); + if (!specifics.has_value()) + continue; + if (!MatchesSearchParams(specifics.value(), search_params)) + continue; + + search_results.emplace_back(CreatePowerFromSpecifics(specifics.value())); + } + + return search_results; +} + bool PowerBookmarkDatabaseImpl::CreatePower(std::unique_ptr<Power> power) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/components/power_bookmarks/storage/power_bookmark_database_impl.h b/components/power_bookmarks/storage/power_bookmark_database_impl.h index 441bcba..561a8e6a 100644 --- a/components/power_bookmarks/storage/power_bookmark_database_impl.h +++ b/components/power_bookmarks/storage/power_bookmark_database_impl.h
@@ -11,10 +11,11 @@ #include "components/power_bookmarks/storage/power_bookmark_database.h" #include "sql/database.h" #include "url/gurl.h" -#include "url/origin.h" namespace power_bookmarks { +struct SearchParams; + constexpr base::FilePath::CharType kDatabaseName[] = FILE_PATH_LITERAL("PowerBookmarks.db"); @@ -36,6 +37,8 @@ const PowerType& power_type) override; std::vector<std::unique_ptr<PowerOverview>> GetPowerOverviewsForType( const PowerType& power_type) override; + std::vector<std::unique_ptr<Power>> GetPowersForSearchParams( + const SearchParams& search_params) override; bool CreatePower(std::unique_ptr<Power> power) override; bool UpdatePower(std::unique_ptr<Power> power) override; bool DeletePower(const base::GUID& guid) override;
diff --git a/components/power_bookmarks/storage/power_bookmark_database_impl_unittest.cc b/components/power_bookmarks/storage/power_bookmark_database_impl_unittest.cc index cb1745c..232c5d9f 100644 --- a/components/power_bookmarks/storage/power_bookmark_database_impl_unittest.cc +++ b/components/power_bookmarks/storage/power_bookmark_database_impl_unittest.cc
@@ -4,14 +4,13 @@ #include "components/power_bookmarks/storage/power_bookmark_database_impl.h" +#include <memory> #include <vector> -#include "base/containers/contains.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/path_service.h" -#include "base/ranges/algorithm.h" #include "build/build_config.h" +#include "components/power_bookmarks/core/powers/search_params.h" #include "components/power_bookmarks/core/proto/power_bookmark_specifics.pb.h" #include "sql/database.h" #include "sql/meta_table.h" @@ -19,22 +18,41 @@ #include "sql/statement.h" #include "sql/test/test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" +#include "url/origin.h" + +namespace power_bookmarks { namespace { -std::unique_ptr<power_bookmarks::Power> MakePower( + +std::unique_ptr<Power> MakePower( GURL url, - power_bookmarks::PowerType power_type) { - std::unique_ptr<power_bookmarks::PowerSpecifics> power_specifics = - std::make_unique<power_bookmarks::PowerSpecifics>(); - std::unique_ptr<power_bookmarks::Power> power = - std::make_unique<power_bookmarks::Power>(std::move(power_specifics)); + PowerType power_type, + std::unique_ptr<PowerSpecifics> power_specifics) { + std::unique_ptr<Power> power = + std::make_unique<Power>(std::move(power_specifics)); power->set_guid(base::GUID::GenerateRandomV4()); power->set_url(url); power->set_power_type(power_type); return power; } + +std::unique_ptr<Power> MakePower(GURL url, PowerType power_type) { + return MakePower(url, power_type, std::make_unique<PowerSpecifics>()); +} + +bool ContainsPower(const std::vector<std::unique_ptr<Power>>& list, + PowerType power_type, + GURL url) { + for (const std::unique_ptr<Power>& power : list) { + if (power->power_type() == power_type && power->url() == url) + return true; + } + return false; +} + } // namespace -namespace power_bookmarks { + class PowerBookmarkDatabaseImplTest : public testing::Test { public: PowerBookmarkDatabaseImplTest() = default; @@ -400,6 +418,60 @@ } } +TEST_F(PowerBookmarkDatabaseImplTest, GetPowersForSearchParams) { + std::unique_ptr<PowerBookmarkDatabaseImpl> pbdb = + std::make_unique<PowerBookmarkDatabaseImpl>(db_dir()); + EXPECT_TRUE(pbdb->Init()); + + EXPECT_TRUE(pbdb->CreatePower(MakePower(GURL("https://example.com/a1.html"), + PowerType::POWER_TYPE_MOCK))); + EXPECT_TRUE(pbdb->CreatePower(MakePower(GURL("https://example.com/b1.html"), + PowerType::POWER_TYPE_MOCK))); + EXPECT_TRUE(pbdb->CreatePower(MakePower(GURL("https://example.com/a2.html"), + PowerType::POWER_TYPE_MOCK))); + + SearchParams search_params{.query = "/a"}; + std::vector<std::unique_ptr<Power>> search_results = + pbdb->GetPowersForSearchParams(search_params); + + EXPECT_EQ(2u, search_results.size()); + EXPECT_TRUE(ContainsPower(search_results, PowerType::POWER_TYPE_MOCK, + GURL("https://example.com/a1.html"))); + EXPECT_TRUE(ContainsPower(search_results, PowerType::POWER_TYPE_MOCK, + GURL("https://example.com/a2.html"))); +} + +TEST_F(PowerBookmarkDatabaseImplTest, GetPowersForSearchParamsMatchNoteText) { + std::unique_ptr<PowerBookmarkDatabaseImpl> pbdb = + std::make_unique<PowerBookmarkDatabaseImpl>(db_dir()); + EXPECT_TRUE(pbdb->Init()); + + { + std::unique_ptr<PowerSpecifics> note_specifics = + std::make_unique<PowerSpecifics>(); + note_specifics->mutable_note_specifics()->set_plain_text("lorem ipsum"); + EXPECT_TRUE(pbdb->CreatePower(MakePower(GURL("https://example.com/a1.html"), + PowerType::POWER_TYPE_NOTE, + std::move(note_specifics)))); + } + { + std::unique_ptr<PowerSpecifics> note_specifics = + std::make_unique<PowerSpecifics>(); + note_specifics->mutable_note_specifics()->set_plain_text("not a match"); + EXPECT_TRUE(pbdb->CreatePower(MakePower(GURL("https://example.com/a2.html"), + PowerType::POWER_TYPE_NOTE, + std::move(note_specifics)))); + } + + SearchParams search_params{.query = "lorem"}; + std::vector<std::unique_ptr<Power>> search_results = + pbdb->GetPowersForSearchParams(search_params); + + EXPECT_EQ(1u, search_results.size()); + EXPECT_TRUE(ContainsPower(search_results, PowerType::POWER_TYPE_NOTE, + GURL("https://example.com/a1.html"))); +} + TEST_F(PowerBookmarkDatabaseImplTest, DeletePower) { std::unique_ptr<PowerBookmarkDatabaseImpl> pbdb = std::make_unique<PowerBookmarkDatabaseImpl>(db_dir()); @@ -462,4 +534,4 @@ EXPECT_EQ(0u, stored_powers.size()); } -} // namespace power_bookmarks \ No newline at end of file +} // namespace power_bookmarks
diff --git a/components/reading_list/core/reading_list_model_impl.cc b/components/reading_list/core/reading_list_model_impl.cc index 955153d2..7f0d9c0d 100644 --- a/components/reading_list/core/reading_list_model_impl.cc +++ b/components/reading_list/core/reading_list_model_impl.cc
@@ -19,8 +19,7 @@ std::unique_ptr<ReadingListModelStorage> storage, PrefService* pref_service, base::Clock* clock) - : entries_(std::make_unique<ReadingListEntries>()), - unread_entry_count_(0), + : unread_entry_count_(0), read_entry_count_(0), unseen_entry_count_(0), clock_(clock), @@ -40,15 +39,13 @@ ReadingListModelImpl::~ReadingListModelImpl() {} -void ReadingListModelImpl::StoreLoaded( - std::unique_ptr<ReadingListEntries> entries) { +void ReadingListModelImpl::StoreLoaded(ReadingListEntries entries) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(entries); entries_ = std::move(entries); - for (auto& iterator : *entries_) { + for (auto& iterator : entries_) { UpdateEntryStateCountersOnEntryInsertion(iterator.second); } - DCHECK(read_entry_count_ + unread_entry_count_ == entries_->size()); + DCHECK(read_entry_count_ + unread_entry_count_ == entries_.size()); loaded_ = true; base::UmaHistogramCounts1000("ReadingList.Unread.Count.OnModelLoaded", @@ -74,15 +71,15 @@ size_t ReadingListModelImpl::size() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(read_entry_count_ + unread_entry_count_ == entries_->size()); + DCHECK(read_entry_count_ + unread_entry_count_ == entries_.size()); if (!loaded()) return 0; - return entries_->size(); + return entries_.size(); } size_t ReadingListModelImpl::unread_size() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(read_entry_count_ + unread_entry_count_ == entries_->size()); + DCHECK(read_entry_count_ + unread_entry_count_ == entries_.size()); if (!loaded()) return 0; return unread_entry_count_; @@ -132,7 +129,7 @@ } std::unique_ptr<ReadingListModel::ScopedReadingListBatchUpdate> model_batch_updates = BeginBatchUpdates(); - for (auto& iterator : *entries_) { + for (auto& iterator : entries_) { ReadingListEntry& entry = iterator.second; if (entry.HasBeenSeen()) { continue; @@ -162,7 +159,7 @@ for (const auto& url : Keys()) { RemoveEntryByURL(url); } - return entries_->empty(); + return entries_.empty(); } void ReadingListModelImpl::UpdateEntryStateCountersOnEntryRemoval( @@ -191,7 +188,7 @@ const std::vector<GURL> ReadingListModelImpl::Keys() const { std::vector<GURL> keys; - for (const auto& iterator : *entries_) { + for (const auto& iterator : entries_) { keys.push_back(iterator.first); } return keys; @@ -201,7 +198,7 @@ const GURL& gurl) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - return GetMutableEntryFromURL(gurl); + return const_cast<ReadingListModelImpl*>(this)->GetMutableEntryFromURL(gurl); } const ReadingListEntry* ReadingListModelImpl::GetFirstUnreadEntry( @@ -215,8 +212,8 @@ const ReadingListEntry* first_entry_all = nullptr; int64_t update_time_distilled = 0; const ReadingListEntry* first_entry_distilled = nullptr; - for (auto& iterator : *entries_) { - ReadingListEntry& entry = iterator.second; + for (auto& iterator : entries_) { + const ReadingListEntry& entry = iterator.second; if (entry.IsRead()) { continue; } @@ -239,11 +236,11 @@ } ReadingListEntry* ReadingListModelImpl::GetMutableEntryFromURL( - const GURL& url) const { + const GURL& url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return nullptr; } return &(iterator->second); @@ -262,7 +259,7 @@ SetUnseenFlag(); } GURL url = entry->URL(); - entries_->insert(std::make_pair(url, std::move(*entry))); + entries_.emplace(url, std::move(*entry)); for (auto& observer : observers_) { observer.ReadingListDidAddEntry(this, url, reading_list::ADDED_VIA_SYNC); observer.ReadingListDidApplyChanges(this); @@ -321,7 +318,7 @@ } UpdateEntryStateCountersOnEntryRemoval(*entry); - entries_->erase(url); + entries_.erase(url); for (auto& observer : observers_) observer.ReadingListDidApplyChanges(this); } @@ -355,7 +352,7 @@ observer.ReadingListWillAddEntry(this, entry); UpdateEntryStateCountersOnEntryInsertion(entry); SetUnseenFlag(); - entries_->insert(std::make_pair(url, std::move(entry))); + entries_.emplace(url, std::move(entry)); if (storage_layer_) { storage_layer_->SaveEntry(*GetEntryByURL(url)); @@ -366,7 +363,7 @@ observer.ReadingListDidApplyChanges(this); } - return entries_->at(url); + return entries_.at(url); } const ReadingListEntry& ReadingListModelImpl::AddEntry( @@ -379,8 +376,8 @@ void ReadingListModelImpl::SetReadStatus(const GURL& url, bool read) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return; } ReadingListEntry& entry = iterator->second; @@ -408,8 +405,8 @@ const std::string& title) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return; } ReadingListEntry& entry = iterator->second; @@ -435,8 +432,8 @@ base::TimeDelta estimated_read_time) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return; } ReadingListEntry& entry = iterator->second; @@ -463,8 +460,8 @@ const base::Time& distillation_date) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return; } ReadingListEntry& entry = iterator->second; @@ -491,8 +488,8 @@ ReadingListEntry::DistillationState state) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(loaded()); - auto iterator = entries_->find(url); - if (iterator == entries_->end()) { + auto iterator = entries_.find(url); + if (iterator == entries_.end()) { return; } ReadingListEntry& entry = iterator->second;
diff --git a/components/reading_list/core/reading_list_model_impl.h b/components/reading_list/core/reading_list_model_impl.h index b19d5468..df7b595 100644 --- a/components/reading_list/core/reading_list_model_impl.h +++ b/components/reading_list/core/reading_list_model_impl.h
@@ -42,7 +42,7 @@ ~ReadingListModelImpl() override; - void StoreLoaded(std::unique_ptr<ReadingListEntries> entries) override; + void StoreLoaded(ReadingListEntries entries) override; // KeyedService implementation. void Shutdown() override; @@ -132,7 +132,7 @@ // Returns a mutable pointer to the entry with URL |url|. Return nullptr if // no entry is found. - ReadingListEntry* GetMutableEntryFromURL(const GURL& url) const; + ReadingListEntry* GetMutableEntryFromURL(const GURL& url); // Returns the |storage_layer_| of the model. ReadingListModelStorage* StorageLayer(); @@ -142,7 +142,7 @@ void RebuildIndex() const; - std::unique_ptr<ReadingListEntries> entries_; + ReadingListEntries entries_; size_t unread_entry_count_; size_t read_entry_count_; size_t unseen_entry_count_;
diff --git a/components/reading_list/core/reading_list_model_unittest.cc b/components/reading_list/core/reading_list_model_unittest.cc index bb26a27..2f42e65 100644 --- a/components/reading_list/core/reading_list_model_unittest.cc +++ b/components/reading_list/core/reading_list_model_unittest.cc
@@ -29,50 +29,41 @@ public: TestReadingListStorage(TestReadingListStorageObserver* observer, base::SimpleTestClock* clock) - : entries_(new ReadingListSyncBridgeDelegate::ReadingListEntries()), - observer_(observer), - clock_(clock) {} + : observer_(observer), clock_(clock) {} void AddSampleEntries() { // Adds timer and interlace read/unread entry creation to avoid having two // entries with the same creation timestamp. ReadingListEntry unread_a(GURL("http://unread_a.com"), "unread_a", AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://unread_a.com"), std::move(unread_a))); + entries_.emplace(GURL("http://unread_a.com"), std::move(unread_a)); ReadingListEntry read_a(GURL("http://read_a.com"), "read_a", AdvanceAndGetTime(clock_)); read_a.SetRead(true, AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://read_a.com"), std::move(read_a))); + entries_.emplace(GURL("http://read_a.com"), std::move(read_a)); ReadingListEntry unread_b(GURL("http://unread_b.com"), "unread_b", AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://unread_b.com"), std::move(unread_b))); + entries_.emplace(GURL("http://unread_b.com"), std::move(unread_b)); ReadingListEntry read_b(GURL("http://read_b.com"), "read_b", AdvanceAndGetTime(clock_)); read_b.SetRead(true, AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://read_b.com"), std::move(read_b))); + entries_.emplace(GURL("http://read_b.com"), std::move(read_b)); ReadingListEntry unread_c(GURL("http://unread_c.com"), "unread_c", AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://unread_c.com"), std::move(unread_c))); + entries_.emplace(GURL("http://unread_c.com"), std::move(unread_c)); ReadingListEntry read_c(GURL("http://read_c.com"), "read_c", AdvanceAndGetTime(clock_)); read_c.SetRead(true, AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://read_c.com"), std::move(read_c))); + entries_.emplace(GURL("http://read_c.com"), std::move(read_c)); ReadingListEntry unread_d(GURL("http://unread_d.com"), "unread_d", AdvanceAndGetTime(clock_)); - entries_->insert( - std::make_pair(GURL("http://unread_d.com"), std::move(unread_d))); + entries_.emplace(GURL("http://unread_d.com"), std::move(unread_d)); } void SetReadingListModel(ReadingListModel* model, @@ -104,7 +95,7 @@ } private: - std::unique_ptr<ReadingListSyncBridgeDelegate::ReadingListEntries> entries_; + ReadingListSyncBridgeDelegate::ReadingListEntries entries_; raw_ptr<TestReadingListStorageObserver> observer_; raw_ptr<base::SimpleTestClock> clock_; };
diff --git a/components/reading_list/core/reading_list_sync_bridge.cc b/components/reading_list/core/reading_list_sync_bridge.cc index a6939f4..c00773a 100644 --- a/components/reading_list/core/reading_list_sync_bridge.cc +++ b/components/reading_list/core/reading_list_sync_bridge.cc
@@ -127,8 +127,8 @@ change_processor()->ReportError(*error); return; } - auto loaded_entries = - std::make_unique<ReadingListSyncBridgeDelegate::ReadingListEntries>(); + + ReadingListSyncBridgeDelegate::ReadingListEntries loaded_entries; for (const syncer::ModelTypeStore::Record& r : *entries) { reading_list::ReadingListLocal proto; @@ -144,8 +144,8 @@ continue; } GURL url = entry->URL(); - DCHECK(!loaded_entries->count(url)); - loaded_entries->insert(std::make_pair(url, std::move(*entry))); + DCHECK(!loaded_entries.count(url)); + loaded_entries.emplace(url, std::move(*entry)); } delegate_->StoreLoaded(std::move(loaded_entries));
diff --git a/components/reading_list/core/reading_list_sync_bridge_delegate.h b/components/reading_list/core/reading_list_sync_bridge_delegate.h index d464038..6029745 100644 --- a/components/reading_list/core/reading_list_sync_bridge_delegate.h +++ b/components/reading_list/core/reading_list_sync_bridge_delegate.h
@@ -21,7 +21,7 @@ // These three methods handle callbacks from a ReadingListSyncBridge. // This method is called when the local store is loaded. |entries| contains // the ReadingListEntry present on the device before sync starts. - virtual void StoreLoaded(std::unique_ptr<ReadingListEntries> entries) = 0; + virtual void StoreLoaded(ReadingListEntries entries) = 0; // Handle sync events. // Called to add a new entry to the model. // |entry| must not already exist in the model.
diff --git a/components/reading_list/core/reading_list_sync_bridge_unittest.cc b/components/reading_list/core/reading_list_sync_bridge_unittest.cc index b57f7c0..ae794fc 100644 --- a/components/reading_list/core/reading_list_sync_bridge_unittest.cc +++ b/components/reading_list/core/reading_list_sync_bridge_unittest.cc
@@ -124,8 +124,8 @@ sync_merged_.clear(); } - // These three mathods handle callbacks from a ReadingListSyncBridge. - void StoreLoaded(std::unique_ptr<ReadingListEntries> entries) override {} + // These methods handle callbacks from a ReadingListSyncBridge. + void StoreLoaded(ReadingListEntries entries) override {} // Handle sync events. void SyncAddEntry(std::unique_ptr<ReadingListEntry> entry) override {
diff --git a/components/resources/safe_browsing_resources.grdp b/components/resources/safe_browsing_resources.grdp index 4ee1a4a..83d32ed0 100644 --- a/components/resources/safe_browsing_resources.grdp +++ b/components/resources/safe_browsing_resources.grdp
@@ -3,7 +3,7 @@ <include name="IDR_SAFE_BROWSING_HTML" file="..\..\components\safe_browsing\content\browser\web_ui\resources\safe_browsing.html" preprocess="true" type="BINDATA" /> <include name="IDR_SAFE_BROWSING_CSS" file="..\..\components\safe_browsing\content\browser\web_ui\resources\safe_browsing.css" type="BINDATA" /> <include name="IDR_SAFE_BROWSING_JS" file="..\..\components\safe_browsing\content\browser\web_ui\resources\safe_browsing.js" preprocess="true" type="BINDATA" /> - <include name="IDR_REAL_TIME_URL_CHECKS_ALLOWLIST_PB" file="..\..\components\safe_browsing\content\resources\real_time_url_checks_allowlist.pb" use_base_dir="false" type="BINDATA" compress="gzip" /> + <include name="IDR_REAL_TIME_URL_CHECKS_ALLOWLIST_PB" file="..\..\components\safe_browsing\content\resources\real_time_url_checks_allowlist.pb" type="BINDATA" compress="gzip" /> <if expr="safe_browsing_mode != 0"> <include name="IDR_DOWNLOAD_FILE_TYPES_PB" file="${root_gen_dir}\components\safe_browsing\content\resources\download_file_types.pb" use_base_dir="false" type="BINDATA" compress="gzip" /> </if>
diff --git a/components/safe_browsing/core/common/proto/csd.proto b/components/safe_browsing/core/common/proto/csd.proto index 9bc81a45..38d14d8 100644 --- a/components/safe_browsing/core/common/proto/csd.proto +++ b/components/safe_browsing/core/common/proto/csd.proto
@@ -1832,6 +1832,21 @@ // Bit positions are defined in extensions::disable_reason::DisableReason // (located in //extensions/browser/disable_reason.h) optional uint32 disable_reasons = 13; + + // Manifest.json file associated with the extension. Only populated for + // off-store extensions. + optional string manifest_json = 14; + + // Extension file names and hashes. + message FileInfo { + // Extension file name. + optional string name = 1; + // Extension file hash calculated with SHA256. + optional bytes hash = 2; + } + + // Only populated for off-store extensions. + repeated FileInfo file_infos = 15; } // Information about the various telemetry signals.
diff --git a/components/segmentation_platform/internal/metadata/metadata_utils_unittest.cc b/components/segmentation_platform/internal/metadata/metadata_utils_unittest.cc index 4f13574..fa3846a 100644 --- a/components/segmentation_platform/internal/metadata/metadata_utils_unittest.cc +++ b/components/segmentation_platform/internal/metadata/metadata_utils_unittest.cc
@@ -104,20 +104,6 @@ EXPECT_EQ(metadata_utils::ValidationResult::kValidationSuccess, metadata_utils::ValidateMetadata(metadata)); - // Verifying adding a single `output_label` in metadata. - auto* output_label1 = metadata.add_output_labels(); - output_label1->set_output_label("Share"); - EXPECT_EQ(metadata_utils::ValidationResult::kValidationSuccess, - metadata_utils::ValidateMetadata(metadata)); - EXPECT_EQ(1, metadata.output_labels_size()); - - // Verifying adding another `output_label` in metadata. - auto* output_label2 = metadata.add_output_labels(); - output_label2->set_output_label("Voice"); - EXPECT_EQ(metadata_utils::ValidationResult::kValidationSuccess, - metadata_utils::ValidateMetadata(metadata)); - EXPECT_EQ(2, metadata.output_labels_size()); - proto::VersionInfo* version_info = metadata.mutable_version_info(); version_info->set_metadata_min_version( proto::CurrentVersion::METADATA_VERSION + 1);
diff --git a/components/segmentation_platform/internal/proto/model_prediction.proto b/components/segmentation_platform/internal/proto/model_prediction.proto index 157d67d..fb457d8 100644 --- a/components/segmentation_platform/internal/proto/model_prediction.proto +++ b/components/segmentation_platform/internal/proto/model_prediction.proto
@@ -10,14 +10,34 @@ import "components/segmentation_platform/public/proto/model_metadata.proto"; import "components/segmentation_platform/public/proto/segmentation_platform.proto"; +// Corresponds to a single output in the model result. +message LabeledResult { + // The label associated with the output. + optional string label = 1; + + // The score represented by the output. + optional float result = 2; +} + // Result from the model evaluation for a given segment. message PredictionResult { // The result is the confidence rating from the model evaluation. + // This field will be deprecated going forward. repeated float result = 1; // The time when the prediction was made, in terms of the number of // microseconds since Windows epoch. optional int64 timestamp_us = 2; + + // The result is the list of scores from the model evaluation. + // `labeled_results` is set once the model execution is completed and results + // are ready. The result are merged with appropriate `label` and set to this + // field. Each entry tells what the result(score) is. The OutputConfig tells + // us how to interpret it. + repeated LabeledResult labeled_results = 3; + + // The output config from the metadata. + optional OutputConfig output_config = 4; } // Partial training data set with only inputs, used when observation period has
diff --git a/components/segmentation_platform/public/proto/model_metadata.proto b/components/segmentation_platform/public/proto/model_metadata.proto index 518ed46..529ebcf0 100644 --- a/components/segmentation_platform/public/proto/model_metadata.proto +++ b/components/segmentation_platform/public/proto/model_metadata.proto
@@ -283,17 +283,49 @@ optional uint64 duration = 2; } +// Defines what type of model is supplied. Results are based on which +// classifier the model is in. +message Classifier { + // A classifier to interpret model results as a boolean. + message BooleanClassifier { + // Limit to classify result as false/true. + optional float threshold = 1; + } + + // A classifier to interpret model results as one of multiple classes. Each + // output of the model corresponds to one of the classes. + message MultiClassClassifier { + // Number of top results the client is interested in. Must be less than + // or equal to the number of labels specified. + optional int64 top_k_outputs = 1; + } + + oneof ClassifierType { + // Model result is classified as boolean. + BooleanClassifier boolean_classifier = 2; + + // Model result is of multi-class type. + MultiClassClassifier multi_class_classifier = 3; + } +} + // Specified by client in the metadata on how to interpret the model results. -message OutputLabel { - // The label to which this output is associated with. Each OutputLabel - // corresponds to one output. - optional string output_label = 1; +message OutputConfig { + // Each `output_label` corresponds to one output. It signifies how to + // interpret the output. + repeated string output_label = 1; + + // Tells the return type of the result for model evaluation. + optional Classifier classifier = 2; } // Metadata about a segmentation model for a given segment. Contains information // on how to use the model such as collecting signals, interpreting results etc. // Next tag: 16 message SegmentationModelMetadata { + // Values for obsolete fields. + reserved 15; + // The version information needed to validate segmentation models. optional VersionInfo version_info = 9; @@ -375,10 +407,11 @@ // Model returns any integer value. RETURN_TYPE_INTEGER = 4; } - // TODO(ritikagup@): Move the field inside OutputLabel. + // TODO(ritikagup@): Deprecate the field. optional OutputDescription return_type = 14; - // List of output labels, each label is attached to one of the output result - // of the model, describing what that output signify. - repeated OutputLabel output_labels = 15; + // Contains information about the model results. Supplied by the client. It + // gives a description of how should the results look like and how to + // interpret them. + optional OutputConfig output_config = 16; }
diff --git a/components/viz/common/BUILD.gn b/components/viz/common/BUILD.gn index 243c19b..671097b6 100644 --- a/components/viz/common/BUILD.gn +++ b/components/viz/common/BUILD.gn
@@ -396,6 +396,7 @@ "quads/compositor_render_pass_unittest.cc", "quads/draw_quad_unittest.cc", "quads/render_pass_io_unittest.cc", + "resources/resource_format_utils_unittest.cc", "resources/resource_sizes_unittest.cc", "surfaces/child_local_surface_id_allocator_unittest.cc", "surfaces/local_surface_id_unittest.cc",
diff --git a/components/viz/common/resources/resource_format_utils.cc b/components/viz/common/resources/resource_format_utils.cc index b3e0f750..cd96ec25 100644 --- a/components/viz/common/resources/resource_format_utils.cc +++ b/components/viz/common/resources/resource_format_utils.cc
@@ -601,11 +601,56 @@ return static_cast<WGPUTextureFormat>(ToDawnFormat(format)); } -// TODO (hitawala): Add support for multiplanar formats. SkColorType ResourceFormatToClosestSkColorType(bool gpu_compositing, - SharedImageFormat format) { - return ResourceFormatToClosestSkColorType(gpu_compositing, - format.resource_format()); + SharedImageFormat format, + int plane_index) { + DCHECK(format.IsValidPlaneIndex(plane_index)); + if (!gpu_compositing) { + // TODO(crbug.com/986405): Remove this assumption and have clients tag + // resources with the correct format. + // In software compositing we lazily use RGBA_8888 throughout the system, + // but actual pixel encodings are the native skia bit ordering, which can be + // RGBA or BGRA. + return kN32_SkColorType; + } + if (format.is_single_plane()) { + return ResourceFormatToClosestSkColorType(gpu_compositing, + format.resource_format()); + } + + auto plane_config = format.plane_config(); + auto channel_format = format.channel_format(); + if (format.PrefersExternalSampler()) { + switch (channel_format) { + case SharedImageFormat::ChannelFormat::k8: + return plane_config == SharedImageFormat::PlaneConfig::kY_UV_A + ? kRGBA_8888_SkColorType + : kRGB_888x_SkColorType; + case SharedImageFormat::ChannelFormat::k10: + return kRGBA_1010102_SkColorType; + case SharedImageFormat::ChannelFormat::k16: + return kR16G16B16A16_unorm_SkColorType; + case SharedImageFormat::ChannelFormat::k16F: + return kRGBA_F16_SkColorType; + } + } else { + // No external sampling, format is per plane. + int num_channels = format.NumChannelsInPlane(plane_index); + DCHECK_GT(num_channels, 0); + DCHECK_LE(num_channels, 2); + switch (channel_format) { + case SharedImageFormat::ChannelFormat::k8: + return num_channels == 1 ? kAlpha_8_SkColorType + : kR8G8_unorm_SkColorType; + case SharedImageFormat::ChannelFormat::k10: + case SharedImageFormat::ChannelFormat::k16: + return num_channels == 1 ? kA16_unorm_SkColorType + : kR16G16_unorm_SkColorType; + case SharedImageFormat::ChannelFormat::k16F: + return num_channels == 1 ? kA16_float_SkColorType + : kR16G16_float_SkColorType; + } + } } } // namespace viz
diff --git a/components/viz/common/resources/resource_format_utils.h b/components/viz/common/resources/resource_format_utils.h index fadc8e6..cfe67e0b 100644 --- a/components/viz/common/resources/resource_format_utils.h +++ b/components/viz/common/resources/resource_format_utils.h
@@ -82,11 +82,14 @@ VIZ_RESOURCE_FORMAT_EXPORT unsigned int ToMTLPixelFormat(ResourceFormat format); #endif -// WARNING: The `format` must be single planar. -// TODO(hitawala): Add multiplanar format support. +// Gets the closest SkColorType for a given `format` and `plane_index`. For +// single planar formats (eg. RGBA) the plane_index is not required and is +// default to 0; in such cases the corresponding function with ResourceFormat is +// called. For multiplanar formats a plane_index is required. VIZ_RESOURCE_FORMAT_EXPORT SkColorType ResourceFormatToClosestSkColorType(bool gpu_compositing, - SharedImageFormat format); + SharedImageFormat format, + int plane_index = 0); } // namespace viz
diff --git a/components/viz/common/resources/resource_format_utils_unittest.cc b/components/viz/common/resources/resource_format_utils_unittest.cc new file mode 100644 index 0000000..c44ede6 --- /dev/null +++ b/components/viz/common/resources/resource_format_utils_unittest.cc
@@ -0,0 +1,122 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <vector> + +#include "components/viz/common/resources/resource_format_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace viz { +namespace { + +class ResourceFormatUtilTest : public testing::Test { + public: + void TestToClosestSkColorType(std::vector<SkColorType> expected_types, + SharedImageFormat format, + bool gpu_compositing) { + ASSERT_EQ(format.NumberOfPlanes(), static_cast<int>(expected_types.size())); + for (int plane_index = 0; plane_index < format.NumberOfPlanes(); + plane_index++) { + EXPECT_EQ(expected_types[plane_index], + ResourceFormatToClosestSkColorType(gpu_compositing, format, + plane_index)); + } + } +}; + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeMultiPlaneYUVBiplanar8bit) { + // 8-bit 4:2:0 Y_UV biplanar format (YUV_420_BIPLANAR) + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_UV, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k8); + std::vector<SkColorType> expected_types = {kAlpha_8_SkColorType, + kR8G8_unorm_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeMultiPlaneYVU) { + // 8-bit 4:2:0 Y_V_U format (YVU_420) + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_V_U, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k8); + std::vector<SkColorType> expected_types = { + kAlpha_8_SkColorType, kAlpha_8_SkColorType, kAlpha_8_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeMultiPlaneP010) { + // 10-bit 4:2:0 Y_UV biplanar format (P010) + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_UV, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k10); + std::vector<SkColorType> expected_types = {kA16_unorm_SkColorType, + kR16G16_unorm_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeMultiPlaneYUVBiplanar16bit) { + // 16-bit 4:2:0 Y_UV biplanar format + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_UV, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k16); + std::vector<SkColorType> expected_types = {kA16_unorm_SkColorType, + kR16G16_unorm_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeMultiPlaneYUVATriplanar) { + // 16-bit float 4:2:0 Y_UV_A triplanar format + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_UV_A, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k16F); + std::vector<SkColorType> expected_types = {kA16_float_SkColorType, + kR16G16_float_SkColorType, + kA16_float_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeSinglePlaneRGBX) { + // Single planar RGBX_8888 + SharedImageFormat format = + SharedImageFormat::SinglePlane(ResourceFormat::RGBX_8888); + std::vector<SkColorType> expected_types = {kRGB_888x_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeSinglePlaneAlpha) { + // Single planar ALPHA_8 + SharedImageFormat format = + SharedImageFormat::SinglePlane(ResourceFormat::ALPHA_8); + std::vector<SkColorType> expected_types = {kAlpha_8_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/true); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeSoftwareRGBX) { + // Software Compositing. + // Single planar RGBX_8888 + SharedImageFormat format = + SharedImageFormat::SinglePlane(ResourceFormat::RGBX_8888); + std::vector<SkColorType> expected_types = {kN32_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/false); +} + +TEST_F(ResourceFormatUtilTest, ToClosestSkColorTypeSoftwareYUV) { + // Software Compositing. + // 10-bit 4:2:0 Y_UV biplanar format (P010) + SharedImageFormat format = + SharedImageFormat::MultiPlane(SharedImageFormat::PlaneConfig::kY_UV, + SharedImageFormat::Subsampling::k420, + SharedImageFormat::ChannelFormat::k10); + std::vector<SkColorType> expected_types = {kN32_SkColorType, + kN32_SkColorType}; + TestToClosestSkColorType(expected_types, format, /*gpu_compositing=*/false); +} + +} // namespace +} // namespace viz
diff --git a/components/viz/service/display/overlay_candidate_factory.cc b/components/viz/service/display/overlay_candidate_factory.cc index d016121..f7c7c11 100644 --- a/components/viz/service/display/overlay_candidate_factory.cc +++ b/components/viz/service/display/overlay_candidate_factory.cc
@@ -478,15 +478,22 @@ if (quad->nearest_neighbor) return CandidateStatus::kFailNearFilter; - if (quad->background_color != SkColors::kTransparent && - (quad->background_color != SkColors::kBlack || - quad->ShouldDrawWithBlending())) { - // This path can also be used by other platforms like Ash/Chrome, which does - // not support overlays with background color. Only LaCros/Wayland supports - // that. - if (!is_delegated_context_) - return CandidateStatus::kFailBlending; + if (is_delegated_context_) { + // Always convey |background_color| even when transparent. This allows for + // the wayland server to make blending optimizations even when the quad is + // considered opaque. Specifically Exo will try to ensure the opaqueness of + // alpha formats by adding a black background which can cause difficulty in + // overlay promotion (see the code in the lines below). candidate.color = quad->background_color; + } else if (quad->background_color != SkColors::kTransparent && + (quad->background_color != SkColors::kBlack || + quad->ShouldDrawWithBlending())) { + // The condition above is very specific to the implementation of DRM/KMS + // scanout. An opaque plane with buffer that has buffer element component + // alpha will default black for the blend. Basically we can simulate a black + // background using the default color when blending an opaque overlay. This + // trick, of course, only works for black. + return CandidateStatus::kFailBlending; } candidate.uv_rect = BoundingRect(quad->uv_top_left, quad->uv_bottom_right);
diff --git a/components/viz/service/display/overlay_unittest.cc b/components/viz/service/display/overlay_unittest.cc index 102763a..49e9f2d4 100644 --- a/components/viz/service/display/overlay_unittest.cc +++ b/components/viz/service/display/overlay_unittest.cc
@@ -4652,6 +4652,39 @@ } } +// Transparent colors are important for delegating overlays. Overlays that have +// an alpha channel but are required to be drawn as opaque will have solid black +// placed behind them. This solid black can interfer with overlay +// promotion/blend optimizations. +TEST_F(DelegatedTest, ForwardBackgroundColor) { + auto pass = CreateRenderPass(); + + auto* quad = CreateCandidateQuadAt( + resource_provider_.get(), child_resource_provider_.get(), + child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), + kOverlayRect); + quad->background_color = SkColors::kTransparent; + // Check for potential candidates. + OverlayCandidateList candidate_list; + OverlayProcessorInterface::FilterOperationsMap render_pass_filters; + OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; + AggregatedRenderPassList pass_list; + // AggregatedRenderPass* main_pass = pass.get(); + SurfaceDamageRectList surface_damage_rect_list; + // Simplify by adding full root damage. + surface_damage_rect_list.push_back(pass->output_rect); + pass_list.push_back(std::move(pass)); + overlay_processor_->ProcessForOverlays( + resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), + render_pass_filters, render_pass_backdrop_filters, + std::move(surface_damage_rect_list), + overlay_processor_->GetDefaultPrimaryPlane(), &candidate_list, + &damage_rect_, &content_bounds_); + + EXPECT_RECTF_EQ(gfx::RectF(kOverlayRect), candidate_list[0].display_rect); + EXPECT_EQ(SkColors::kTransparent, candidate_list[0].color.value()); +} + TEST_F(DelegatedTest, DoNotDelegateCopyRequest) { auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(),
diff --git a/components/viz/service/gl/gpu_service_impl.cc b/components/viz/service/gl/gpu_service_impl.cc index 782921b..92e6058 100644 --- a/components/viz/service/gl/gpu_service_impl.cc +++ b/components/viz/service/gl/gpu_service_impl.cc
@@ -422,8 +422,8 @@ gl::DirectCompositionOverlayCapsMonitor::GetInstance()->AddObserver(this); #endif - gpu_memory_buffer_factory_ = - gpu::GpuMemoryBufferFactory::CreateNativeType(vulkan_context_provider()); + gpu_memory_buffer_factory_ = gpu::GpuMemoryBufferFactory::CreateNativeType( + vulkan_context_provider(), io_runner_); weak_ptr_ = weak_ptr_factory_.GetWeakPtr(); }
diff --git a/components/webxr/android/java/src/org/chromium/components/webxr/ArCoreInstallUtils.java b/components/webxr/android/java/src/org/chromium/components/webxr/ArCoreInstallUtils.java index b705122..3bbd001 100644 --- a/components/webxr/android/java/src/org/chromium/components/webxr/ArCoreInstallUtils.java +++ b/components/webxr/android/java/src/org/chromium/components/webxr/ArCoreInstallUtils.java
@@ -120,6 +120,10 @@ @CalledByNative private void onNativeDestroy() { mNativeArCoreInstallUtils = 0; + if (sInstallRequest != null) { + sInstallRequest.dispose(); + sInstallRequest = null; + } } private ArCoreInstallUtils(long nativeArCoreInstallUtils) { @@ -200,19 +204,8 @@ private void onArCoreRequestInstallReturned(Activity activity) { assert sInstallRequest != null; - try { - // Since |userRequestedInstall| parameter is false, the below call should - // throw if ARCore is still not installed - no need to check the result. - getArCoreShimInstance().requestInstall(activity, false); - maybeNotifyNativeOnRequestInstallSupportedArCoreResult(true); - } catch (ArCoreShim.UnavailableDeviceNotCompatibleException e) { - Log.w(TAG, "Exception thrown when trying to validate install state of ARCore: %s", - e.toString()); - maybeNotifyNativeOnRequestInstallSupportedArCoreResult(false); - } catch (ArCoreShim.UnavailableUserDeclinedInstallationException e) { - maybeNotifyNativeOnRequestInstallSupportedArCoreResult(false); - } - + maybeNotifyNativeOnRequestInstallSupportedArCoreResult( + getArCoreInstallStatus() == ArCoreAvailability.SUPPORTED_INSTALLED); sInstallRequest.dispose(); sInstallRequest = null; }
diff --git a/content/browser/accessibility/accessibility_win_browsertest.cc b/content/browser/accessibility/accessibility_win_browsertest.cc index 730b9dc..f0e9ff38 100644 --- a/content/browser/accessibility/accessibility_win_browsertest.cc +++ b/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -926,7 +926,7 @@ IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest, TestAlwaysFireFocusEventAfterNavigationComplete) { - testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.mode()); + testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.flags()); ASSERT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); @@ -962,7 +962,7 @@ IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest, TestLoadingAccessibilityTree) { - testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.mode()); + testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.flags()); ASSERT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); @@ -1071,9 +1071,9 @@ document_checker.CheckAccessible(GetRendererAccessible()); // Change the children of the document body. - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); ExecuteScript(u"document.body.innerHTML='<b>new text</b>'"); ASSERT_TRUE(waiter.WaitForNotification()); @@ -1096,9 +1096,9 @@ document_checker.CheckAccessible(GetRendererAccessible()); // Change the children of the document body. - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); ExecuteScript(u"document.body.children[0].style.visibility='visible'"); ASSERT_TRUE(waiter.WaitForNotification()); @@ -2093,9 +2093,9 @@ } // Delete the character in the input field. - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); ExecuteScript(u"document.querySelector('[contenteditable]').innerText='';"); ASSERT_TRUE(waiter.WaitForNotification()); @@ -2568,9 +2568,9 @@ base::win::ScopedVariant childid_self(CHILDID_SELF); base::win::ScopedBstr new_value(L"New value"); - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); EXPECT_HRESULT_SUCCEEDED( paragraph->put_accValue(childid_self, new_value.Get())); ASSERT_TRUE(waiter.WaitForNotification()); @@ -5341,7 +5341,7 @@ // (kAXModeBasic includes both kNativeAPIs and kWebContents). Importantly, // this combination of AXModes allows RenderFrameHostImpl to create // BrowserAccessibilityManagers. - ui::AXMode expected_mode = ui::kAXModeBasic.mode(); + ui::AXMode expected_mode = ui::kAXModeBasic.flags(); EXPECT_EQ(expected_mode, content::BrowserAccessibilityStateImpl::GetInstance() ->GetAccessibilityMode());
diff --git a/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc b/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc index bb65567..dff48b3 100644 --- a/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc +++ b/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc
@@ -1085,9 +1085,9 @@ // Now remove "Node 1" from the DOM and verify the text range created from // "Node 1" is still functional. { - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); EXPECT_TRUE( ExecJs(shell()->web_contents(), "document.getElementById('wrapper').removeChild(document." @@ -1104,9 +1104,9 @@ // Now remove all children from the DOM and verify the text range created from // "Node 1" is still valid (it got moved to a non-deleted ancestor node). { - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::CHILDREN_CHANGED); + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); EXPECT_TRUE(ExecJs(shell()->web_contents(), "while(document.body.childElementCount > 0) {" " document.body.removeChild(document.body.firstChild);" @@ -3296,7 +3296,7 @@ EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"Before frame"); AccessibilityNotificationWaiter waiter(web_contents, ui::kAXModeComplete, - ax::mojom::Event::kLayoutComplete); + ax::mojom::Event::kChildrenChanged); // Updating the style on that particular node is going to invalidate the // leaf text node and will replace it with a new one with the updated style. @@ -3324,7 +3324,7 @@ /*expected_count*/ 1); AccessibilityNotificationWaiter waiter(web_contents, ui::kAXModeComplete, - ax::mojom::Event::kLayoutComplete); + ax::mojom::Event::kChildrenChanged); // Updating the style on that particular node is going to invalidate the // leaf text node and will replace it with a new one with the updated style. @@ -3356,7 +3356,7 @@ /*expected_count*/ -1); AccessibilityNotificationWaiter waiter(web_contents, ui::kAXModeComplete, - ax::mojom::Event::kEndOfTest); + ax::mojom::Event::kChildrenChanged); // Updating the style on that particular node is going to invalidate the // leaf text node and will replace it with a new one with the updated style. @@ -3365,7 +3365,6 @@ web_contents, "document.getElementById('s2').style.outline = '1px solid black';")); - GetManager()->SignalEndOfTest(); ASSERT_TRUE(waiter.WaitForNotification()); EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"iframe\nAfter frame"); } @@ -3395,9 +3394,8 @@ // Reloading changes the tree id, triggering an AXTreeManager replacement. shell()->Reload(); - AccessibilityNotificationWaiter waiter( - web_contents, ui::kAXModeComplete, - ui::AXEventGenerator::Event::FOCUS_CHANGED); + AccessibilityNotificationWaiter waiter(web_contents, ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); // We do a style change here only to trigger an AXTree update - apparently, // a shell reload doesn't update the tree by itself. @@ -3435,14 +3433,13 @@ /*expected_count*/ 1); AccessibilityNotificationWaiter waiter(web_contents, ui::kAXModeComplete, - ax::mojom::Event::kEndOfTest); + ax::mojom::Event::kChildrenChanged); // We do a style change here only to trigger an AXTree update. EXPECT_TRUE(ExecJs( web_contents, "document.getElementById('s2').style.outline = '1px solid black';")); - GetManager()->SignalEndOfTest(); ASSERT_TRUE(waiter.WaitForNotification()); // If the previous observer was not removed correctly, this will cause a
diff --git a/content/browser/accessibility/browser_accessibility_state_impl.cc b/content/browser/accessibility/browser_accessibility_state_impl.cc index bcb347e..a840cc0 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl.cc
@@ -398,7 +398,7 @@ ui::AXPlatformNode::NotifyAddAXModeFlags(accessibility_mode_); // Retrieve only newly added modes for the purposes of logging. - int new_mode_flags = mode.mode() & (~previous_mode.mode()); + int new_mode_flags = mode.flags() & (~previous_mode.flags()); if (new_mode_flags & ui::AXMode::kNativeAPIs) RecordNewAccessibilityModeFlags( ui::AXMode::ModeFlagHistogramValue::UMA_AX_MODE_NATIVE_APIS); @@ -445,8 +445,8 @@ if (force_renderer_accessibility_ && mode == ui::kAXModeComplete) return; - int raw_flags = - accessibility_mode_.mode() ^ (mode.mode() & accessibility_mode_.mode()); + int raw_flags = accessibility_mode_.flags() ^ + (mode.flags() & accessibility_mode_.flags()); accessibility_mode_ = raw_flags; // Proxy the new AXMode to AXPlatformNode.
diff --git a/content/browser/accessibility/cross_platform_accessibility_browsertest.cc b/content/browser/accessibility/cross_platform_accessibility_browsertest.cc index 98cca66..07af6bd 100644 --- a/content/browser/accessibility/cross_platform_accessibility_browsertest.cc +++ b/content/browser/accessibility/cross_platform_accessibility_browsertest.cc
@@ -776,16 +776,13 @@ // If there is a popup, expand it and wait for it to appear. // If it's a list, it will simply click on the list. { - // Note: the kEndOfTextSignal actually represents the next step in the - // test, when a response is received from the SignalEndOfTest() call. - AccessibilityNotificationWaiter waiter(shell()->web_contents(), - ui::kAXModeComplete, - ax::mojom::Event::kEndOfTest); + AccessibilityNotificationWaiter waiter( + shell()->web_contents(), ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); ui::AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; select->AccessibilityPerformAction(action_data); - GetManager()->SignalEndOfTest(); ASSERT_TRUE(waiter.WaitForNotification()); } @@ -862,10 +859,10 @@ } // Open popup. + AccessibilityNotificationWaiter waiter(shell()->web_contents(), + ui::kAXModeComplete, + ax::mojom::Event::kChildrenChanged); { - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::EXPANDED); ui::AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; select->AccessibilityPerformAction(action_data); @@ -904,9 +901,6 @@ // Close the popup. { - AccessibilityNotificationWaiter waiter( - shell()->web_contents(), ui::kAXModeComplete, - ui::AXEventGenerator::Event::COLLAPSED); ui::AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; select->AccessibilityPerformAction(action_data);
diff --git a/content/browser/accessibility/web_contents_accessibility_android.cc b/content/browser/accessibility/web_contents_accessibility_android.cc index 1f6a6d8..551315c 100644 --- a/content/browser/accessibility/web_contents_accessibility_android.cc +++ b/content/browser/accessibility/web_contents_accessibility_android.cc
@@ -317,8 +317,8 @@ // Remove the mode flags present in kAXModeComplete but not in // kAXModeBasic, thereby reverting the mode to kAXModeBasic while // not touching any other flags. - ui::AXMode remove_mode_flags(ui::kAXModeComplete.mode() & - ~ui::kAXModeBasic.mode()); + ui::AXMode remove_mode_flags(ui::kAXModeComplete.flags() & + ~ui::kAXModeBasic.flags()); accessibility_state->RemoveAccessibilityModeFlags(remove_mode_flags); } }
diff --git a/content/browser/android/dialog_overlay_impl.cc b/content/browser/android/dialog_overlay_impl.cc index fe5958b..379bf3c 100644 --- a/content/browser/android/dialog_overlay_impl.cc +++ b/content/browser/android/dialog_overlay_impl.cc
@@ -124,6 +124,9 @@ // ever AndroidOverlayProviderImpl.MAX_OVERLAYS > 1. delegate->SetOverlayMode(true); + Java_DialogOverlayImpl_onWebContents(env, obj, + web_contents()->GetJavaWebContents()); + // Send the initial token, if there is one. The observer will notify us about // changes only. if (auto* window = web_contents()->GetNativeView()->GetWindowAndroid()) {
diff --git a/content/browser/attribution_reporting/attribution_data_host_manager.h b/content/browser/attribution_reporting/attribution_data_host_manager.h index 5440c33..1b80579 100644 --- a/content/browser/attribution_reporting/attribution_data_host_manager.h +++ b/content/browser/attribution_reporting/attribution_data_host_manager.h
@@ -9,6 +9,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "third_party/blink/public/common/tokens/tokens.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom-forward.h" namespace attribution_reporting { class SuitableOrigin; @@ -44,7 +45,8 @@ virtual bool RegisterNavigationDataHost( mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, const blink::AttributionSrcToken& attribution_src_token, - AttributionInputEvent input_event) = 0; + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType nav_type) = 0; // Notifies the manager that an attribution enabled navigation has registered // a source header. May be called multiple times for the same navigation. @@ -54,14 +56,16 @@ std::string header_value, attribution_reporting::SuitableOrigin reporting_origin, const attribution_reporting::SuitableOrigin& source_origin, - AttributionInputEvent input_event) = 0; + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType nav_type) = 0; // Notifies the manager that we have received a navigation for a given data // host. This may arrive before or after the attribution configuration is // available for a given data host. virtual void NotifyNavigationForDataHost( const blink::AttributionSrcToken& attribution_src_token, - const attribution_reporting::SuitableOrigin& source_origin) = 0; + const attribution_reporting::SuitableOrigin& source_origin, + blink::mojom::AttributionNavigationType nav_type) = 0; // Notifies the manager that a navigation associated with a data host failed // and should no longer be tracked.
diff --git a/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc b/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc index a8d52c4..a39fa06 100644 --- a/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc +++ b/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc
@@ -34,6 +34,7 @@ #include "third_party/abseil-cpp/absl/numeric/int128.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom.h" #include "url/origin.h" namespace content { @@ -42,6 +43,7 @@ using ::attribution_reporting::SuitableOrigin; using ::attribution_reporting::mojom::SourceRegistrationError; +using ::blink::mojom::AttributionNavigationType; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. @@ -99,11 +101,6 @@ constexpr size_t kMaxDelayedTriggers = 30; -void ReportBadMessageInsecureReportingOrigin() { - mojo::ReportBadMessage( - "AttributionDataHost: Reporting origin must be secure."); -} - absl::optional<attribution_reporting::AggregatableTriggerDataList> FromMojo( std::vector<blink::mojom::AttributionAggregatableTriggerDataPtr> mojo) { if (mojo.size() > @@ -175,6 +172,7 @@ // Input event associated with the navigation for navigation source data // hosts, `absl::nullopt` otherwise. absl::optional<AttributionInputEvent> input_event; + absl::optional<AttributionNavigationType> nav_type; }; struct AttributionDataHostManagerImpl::DelayedTrigger { @@ -198,6 +196,7 @@ mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host; base::TimeTicks register_time; AttributionInputEvent input_event; + AttributionNavigationType nav_type; }; struct AttributionDataHostManagerImpl::NavigationRedirectSourceRegistrations { @@ -219,6 +218,7 @@ // Input event associated with the navigation. AttributionInputEvent input_event; + AttributionNavigationType nav_type; }; AttributionDataHostManagerImpl::AttributionDataHostManagerImpl( @@ -249,12 +249,14 @@ bool AttributionDataHostManagerImpl::RegisterNavigationDataHost( mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, const blink::AttributionSrcToken& attribution_src_token, - AttributionInputEvent input_event) { + AttributionInputEvent input_event, + AttributionNavigationType nav_type) { auto [it, inserted] = navigation_data_host_map_.try_emplace( attribution_src_token, NavigationDataHost{.data_host = std::move(data_host), .register_time = base::TimeTicks::Now(), - .input_event = input_event}); + .input_event = input_event, + .nav_type = nav_type}); // Should only be possible with a misbehaving renderer. if (!inserted) return false; @@ -270,7 +272,8 @@ std::string header_value, SuitableOrigin reporting_origin, const SuitableOrigin& source_origin, - AttributionInputEvent input_event) { + AttributionInputEvent input_event, + AttributionNavigationType nav_type) { // Avoid costly isolated JSON parsing below if the header is obviously // invalid. if (header_value.empty()) { @@ -283,7 +286,8 @@ attribution_src_token, NavigationRedirectSourceRegistrations{ .source_origin = source_origin, .register_time = base::TimeTicks::Now(), - .input_event = input_event}); + .input_event = input_event, + .nav_type = nav_type}); DCHECK(!it->second.navigation_complete); // Treat ongoing redirect registrations within a chain as a data host for the @@ -299,12 +303,13 @@ header_value, base::BindOnce(&AttributionDataHostManagerImpl::OnRedirectSourceParsed, weak_factory_.GetWeakPtr(), attribution_src_token, - std::move(reporting_origin), header_value)); + std::move(reporting_origin), header_value, nav_type)); } void AttributionDataHostManagerImpl::NotifyNavigationForDataHost( const blink::AttributionSrcToken& attribution_src_token, - const SuitableOrigin& source_origin) { + const SuitableOrigin& source_origin, + AttributionNavigationType nav_type) { auto it = navigation_data_host_map_.find(attribution_src_token); if (it != navigation_data_host_map_.end()) { @@ -315,7 +320,8 @@ .source_type = AttributionSourceType::kNavigation, .register_time = it->second.register_time, .is_within_fenced_frame = false, - .input_event = it->second.input_event}); + .input_event = it->second.input_event, + .nav_type = nav_type}); navigation_data_host_map_.erase(it); RecordNavigationDataHostStatus(NavigationDataHostStatus::kProcessed); @@ -368,21 +374,9 @@ void AttributionDataHostManagerImpl::SourceDataAvailable( blink::mojom::AttributionSourceDataPtr data) { - auto reporting_origin = - SuitableOrigin::Create(std::move(data->reporting_origin)); - if (!reporting_origin) { - RecordSourceDataHandleStatus(DataHandleStatus::kUntrustworthyOrigin); - ReportBadMessageInsecureReportingOrigin(); - return; - } - - auto destination = SuitableOrigin::Create(std::move(data->destination)); - if (!destination) { - RecordSourceDataHandleStatus(DataHandleStatus::kUntrustworthyOrigin); - mojo::ReportBadMessage( - "AttributionDataHost: Destination origin must be secure."); - return; - } + // This is validated by the Mojo typemapping. + DCHECK(data->reporting_origin.IsValid()); + DCHECK(data->destination.IsValid()); FrozenContext& context = receivers_.current_context(); @@ -427,7 +421,8 @@ StorableSource storable_source( CommonSourceInfo( data->source_event_id, context.context_origin, - std::move(*destination), std::move(*reporting_origin), source_time, + std::move(data->destination), std::move(data->reporting_origin), + source_time, CommonSourceInfo::GetExpiryTime(data->expiry, source_time, context.source_type), data->event_report_window @@ -444,18 +439,18 @@ data->debug_key, std::move(*aggregation_keys)), context.is_within_fenced_frame, data->debug_reporting); + if (context.nav_type.has_value()) { + base::UmaHistogramEnumeration( + "Conversions.SourceRegistration.NavigationType.Background", + *context.nav_type); + } attribution_manager_->HandleSource(std::move(storable_source)); } void AttributionDataHostManagerImpl::TriggerDataAvailable( blink::mojom::AttributionTriggerDataPtr data) { - auto reporting_origin = - SuitableOrigin::Create(std::move(data->reporting_origin)); - if (!reporting_origin) { - RecordTriggerDataHandleStatus(DataHandleStatus::kUntrustworthyOrigin); - ReportBadMessageInsecureReportingOrigin(); - return; - } + // This is validated by the Mojo typemapping. + DCHECK(data->reporting_origin.IsValid()); FrozenContext& context = receivers_.current_context(); @@ -565,7 +560,7 @@ AttributionTrigger trigger( attribution_reporting::TriggerRegistration( - std::move(*reporting_origin), std::move(*filters), + std::move(data->reporting_origin), std::move(*filters), std::move(*not_filters), data->debug_key, data->aggregatable_dedup_key, std::move(*event_trigger_data_list), std::move(*aggregatable_trigger_data), @@ -698,6 +693,7 @@ const blink::AttributionSrcToken& attribution_src_token, SuitableOrigin reporting_origin, std::string header_value, + AttributionNavigationType nav_type, data_decoder::DataDecoder::ValueOrError result) { // TODO(johnidel): Add metrics regarding parsing failures / misconfigured // headers. @@ -728,6 +724,8 @@ } if (source.has_value()) { + base::UmaHistogramEnumeration( + "Conversions.SourceRegistration.NavigationType.Foreground", nav_type); attribution_manager_->HandleSource(std::move(*source)); } else { attribution_manager_->NotifyFailedSourceRegistration(
diff --git a/content/browser/attribution_reporting/attribution_data_host_manager_impl.h b/content/browser/attribution_reporting/attribution_data_host_manager_impl.h index 2ec7af2b..d3a6434 100644 --- a/content/browser/attribution_reporting/attribution_data_host_manager_impl.h +++ b/content/browser/attribution_reporting/attribution_data_host_manager_impl.h
@@ -59,16 +59,19 @@ bool RegisterNavigationDataHost( mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, const blink::AttributionSrcToken& attribution_src_token, - AttributionInputEvent input_event) override; + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType nav_type) override; void NotifyNavigationRedirectRegistration( const blink::AttributionSrcToken& attribution_src_token, std::string header_value, attribution_reporting::SuitableOrigin reporting_origin, const attribution_reporting::SuitableOrigin& source_origin, - AttributionInputEvent input_event) override; + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType nav_type) override; void NotifyNavigationForDataHost( const blink::AttributionSrcToken& attribution_src_token, - const attribution_reporting::SuitableOrigin& source_origin) override; + const attribution_reporting::SuitableOrigin& source_origin, + blink::mojom::AttributionNavigationType nav_type) override; void NotifyNavigationFailure( const blink::AttributionSrcToken& attribution_src_token) override; @@ -96,6 +99,7 @@ const blink::AttributionSrcToken& attribution_src_token, attribution_reporting::SuitableOrigin reporting_origin, std::string header_value, + blink::mojom::AttributionNavigationType nav_type, data_decoder::DataDecoder::ValueOrError result); void SetTriggerTimer(base::TimeDelta delay);
diff --git a/content/browser/attribution_reporting/attribution_data_host_manager_impl_unittest.cc b/content/browser/attribution_reporting/attribution_data_host_manager_impl_unittest.cc index ad60019..7c7b1ca 100644 --- a/content/browser/attribution_reporting/attribution_data_host_manager_impl_unittest.cc +++ b/content/browser/attribution_reporting/attribution_data_host_manager_impl_unittest.cc
@@ -50,6 +50,8 @@ using ::attribution_reporting::SuitableOrigin; using ::attribution_reporting::mojom::SourceRegistrationError; +using ::blink::mojom::AttributionNavigationType; + using AttributionFilters = ::attribution_reporting::Filters; using ::testing::_; @@ -232,79 +234,6 @@ } TEST_F(AttributionDataHostManagerImplTest, - SourceDataHost_OriginTrustworthyChecksPerformed) { - base::HistogramTester histograms; - - const char kLocalHost[] = "http://localhost"; - - struct { - const char* destination_origin; - const char* reporting_origin; - bool source_expected; - const char* bad_message = nullptr; - } kTestCases[] = { - {.destination_origin = kLocalHost, - .reporting_origin = kLocalHost, - .source_expected = true}, - {.destination_origin = "http://127.0.0.1", - .reporting_origin = "http://127.0.0.1", - .source_expected = true}, - {.destination_origin = kLocalHost, - .reporting_origin = "http://insecure.com", - .source_expected = false, - .bad_message = "AttributionDataHost: Reporting origin must be secure."}, - {.destination_origin = "http://insecure.com", - .reporting_origin = kLocalHost, - .source_expected = false, - .bad_message = - "AttributionDataHost: Destination origin must be secure."}, - {.destination_origin = "https://secure.com", - .reporting_origin = "https://secure.com", - .source_expected = true}, - }; - - for (const auto& test_case : kTestCases) { - EXPECT_CALL(mock_manager_, HandleSource).Times(test_case.source_expected); - - mojo::test::BadMessageObserver bad_message_observer; - - RemoteDataHost data_host_remote{.task_environment = - raw_ref(task_environment_)}; - data_host_manager_.RegisterDataHost( - data_host_remote.data_host.BindNewPipeAndPassReceiver(), - *SuitableOrigin::Deserialize("https://secure.com"), - /*is_within_fenced_frame=*/false); - - auto source_data = blink::mojom::AttributionSourceData::New(); - source_data->destination = - url::Origin::Create(GURL(test_case.destination_origin)); - source_data->reporting_origin = - url::Origin::Create(GURL(test_case.reporting_origin)); - source_data->filter_data = blink::mojom::AttributionFilterData::New(); - source_data->aggregation_keys = - blink::mojom::AttributionAggregationKeys::New(); - data_host_remote.data_host->SourceDataAvailable(std::move(source_data)); - data_host_remote.data_host.FlushForTesting(); - - Mock::VerifyAndClear(&mock_manager_); - - EXPECT_EQ(bad_message_observer.got_bad_message(), !!test_case.bad_message); - - if (test_case.bad_message) { - EXPECT_EQ(bad_message_observer.WaitForBadMessage(), - test_case.bad_message); - } - } - - histograms.ExpectUniqueSample("Conversions.RegisteredSourcesPerDataHost", 1, - 3); - // kSuccess = 0. - histograms.ExpectBucketCount(kSourceDataHandleStatusMetric, 0, 3); - // kUntrustworthyOrigin = 1. - histograms.ExpectBucketCount(kSourceDataHandleStatusMetric, 1, 2); -} - -TEST_F(AttributionDataHostManagerImplTest, SourceDataHost_FilterSizeCheckPerformed) { for (const auto& test_case : kAttributionFilterSizeTestCases) { base::HistogramTester histograms; @@ -322,9 +251,9 @@ auto source_data = blink::mojom::AttributionSourceData::New(); source_data->destination = - url::Origin::Create(GURL("https://trigger.example")); + *SuitableOrigin::Deserialize("https://trigger.example"); source_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); source_data->filter_data = blink::mojom::AttributionFilterData::New(test_case.AsMap()); source_data->aggregation_keys = @@ -382,9 +311,9 @@ auto source_data = blink::mojom::AttributionSourceData::New(); source_data->destination = - url::Origin::Create(GURL("https://trigger.example")); + *SuitableOrigin::Deserialize("https://trigger.example"); source_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); source_data->filter_data = blink::mojom::AttributionFilterData::New(test_case.filter_data); source_data->aggregation_keys = @@ -426,8 +355,9 @@ auto page_origin = *SuitableOrigin::Deserialize("https://page.example"); auto destination_origin = - url::Origin::Create(GURL("https://trigger.example")); - auto reporting_origin = url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://trigger.example"); + auto reporting_origin = + *SuitableOrigin::Deserialize("https://reporter.example"); { RemoteDataHost data_host_remote{.task_environment = @@ -453,7 +383,7 @@ checkpoint.Call(2); source_data->destination = - url::Origin::Create(GURL("https://other-trigger.example")); + *SuitableOrigin::Deserialize("https://other-trigger.example"); data_host_remote.data_host->SourceDataAvailable(source_data.Clone()); data_host_remote.data_host.FlushForTesting(); @@ -515,9 +445,9 @@ auto source_data = blink::mojom::AttributionSourceData::New(); source_data->destination = - url::Origin::Create(GURL("https://trigger.example")); + *SuitableOrigin::Deserialize("https://trigger.example"); source_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); source_data->filter_data = blink::mojom::AttributionFilterData::New(); source_data->aggregation_keys = blink::mojom::AttributionAggregationKeys::New( @@ -619,65 +549,6 @@ } TEST_F(AttributionDataHostManagerImplTest, - TriggerDataHost_OriginTrustworthyChecksPerformed) { - base::HistogramTester histograms; - - const char kLocalHost[] = "http://localhost"; - - struct { - const char* reporting_origin; - bool trigger_expected; - const char* bad_message = nullptr; - } kTestCases[] = { - {.reporting_origin = kLocalHost, .trigger_expected = true}, - {.reporting_origin = "http://127.0.0.1", .trigger_expected = true}, - {.reporting_origin = "http://insecure.com", - .trigger_expected = false, - .bad_message = "AttributionDataHost: Reporting origin must be secure."}, - {.reporting_origin = "https://secure.com", .trigger_expected = true}, - }; - - for (const auto& test_case : kTestCases) { - EXPECT_CALL(mock_manager_, HandleTrigger).Times(test_case.trigger_expected); - - mojo::test::BadMessageObserver bad_message_observer; - - RemoteDataHost data_host_remote{.task_environment = - raw_ref(task_environment_)}; - data_host_manager_.RegisterDataHost( - data_host_remote.data_host.BindNewPipeAndPassReceiver(), - *SuitableOrigin::Deserialize("https://secure.com"), - /*is_within_fenced_frame=*/false); - - auto trigger_data = blink::mojom::AttributionTriggerData::New(); - trigger_data->reporting_origin = - url::Origin::Create(GURL(test_case.reporting_origin)); - - trigger_data->filters = blink::mojom::AttributionFilters::New(); - trigger_data->not_filters = blink::mojom::AttributionFilters::New(); - - data_host_remote.data_host->TriggerDataAvailable(std::move(trigger_data)); - data_host_remote.data_host.FlushForTesting(); - - EXPECT_EQ(bad_message_observer.got_bad_message(), !!test_case.bad_message); - - if (test_case.bad_message) { - EXPECT_EQ(bad_message_observer.WaitForBadMessage(), - test_case.bad_message); - } - - Mock::VerifyAndClear(&mock_manager_); - } - - histograms.ExpectUniqueSample("Conversions.RegisteredTriggersPerDataHost", 1, - 3); - // kSuccess = 0. - histograms.ExpectBucketCount(kTriggerDataHandleStatusMetric, 0, 3); - // kUntrustworthyOrigin = 1. - histograms.ExpectBucketCount(kTriggerDataHandleStatusMetric, 1, 1); -} - -TEST_F(AttributionDataHostManagerImplTest, TriggerDataHost_TopLevelFilterSizeCheckPerformed) { for (const auto& test_case : kAttributionFilterSizeTestCases) { base::HistogramTester histograms; @@ -695,7 +566,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); trigger_data->filters = blink::mojom::AttributionFilters::New(test_case.AsMap()); @@ -737,7 +608,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -785,7 +656,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -841,7 +712,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); for (size_t i = 0; i < test_case.size; ++i) { trigger_data->event_triggers.push_back( @@ -899,7 +770,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -955,7 +826,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -1173,12 +1044,14 @@ raw_ref(task_environment_)}; data_host_manager_.RegisterNavigationDataHost( data_host_remote.data_host.BindNewPipeAndPassReceiver(), - attribution_src_token, AttributionInputEvent()); + attribution_src_token, AttributionInputEvent(), + AttributionNavigationType::kContextMenu); task_environment_.FastForwardBy(base::Milliseconds(1)); - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - page_origin); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, page_origin, + AttributionNavigationType::kContextMenu); auto source_data = blink::mojom::AttributionSourceData::New(); source_data->source_event_id = 10; @@ -1201,7 +1074,7 @@ // This should succeed even though the destination site doesn't match the // final navigation site. source_data->destination = - url::Origin::Create(GURL("https://trigger2.example")); + *SuitableOrigin::Deserialize("https://trigger2.example"); data_host_remote.data_host->SourceDataAvailable(std::move(source_data)); data_host_remote.data_host.FlushForTesting(); } @@ -1216,6 +1089,10 @@ // kSuccess = 0, kContextError = 2 histograms.ExpectBucketCount(kSourceDataHandleStatusMetric, 0, 2); histograms.ExpectBucketCount(kSourceDataHandleStatusMetric, 2, 0); + + // kContextMenu = 2. + histograms.ExpectBucketCount( + "Conversions.SourceRegistration.NavigationType.Background", 2, 2); } // Ensures correct behavior in @@ -1271,7 +1148,7 @@ // should be delayed. auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1316,7 +1193,8 @@ mojo::Remote<blink::mojom::AttributionDataHost> source_data_host_remote; data_host_manager_.RegisterNavigationDataHost( source_data_host_remote.BindNewPipeAndPassReceiver(), - attribution_src_token, AttributionInputEvent()); + attribution_src_token, AttributionInputEvent(), + AttributionNavigationType::kAnchor); mojo::Remote<blink::mojom::AttributionDataHost> trigger_data_host_remote; data_host_manager_.RegisterDataHost( @@ -1328,7 +1206,7 @@ // be delayed. auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1358,14 +1236,14 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); // Wait for parsing to finish. task_environment_.FastForwardBy(base::TimeDelta()); data_host_manager_.NotifyNavigationFailure(attribution_src_token); - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - source_site); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, source_site, AttributionNavigationType::kAnchor); } TEST_F(AttributionDataHostManagerImplTest, @@ -1378,7 +1256,7 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); data_host_manager_.NotifyNavigationFailure(attribution_src_token); // Wait for parsing to finish. @@ -1396,16 +1274,16 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); // Wait for parsing to finish. task_environment_.FastForwardBy(base::TimeDelta()); data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - source_site); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, source_site, AttributionNavigationType::kAnchor); // Wait for parsing to finish. task_environment_.FastForwardBy(base::TimeDelta()); @@ -1425,16 +1303,16 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, "!!!invalid json", reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); // Wait for parsing to finish. task_environment_.FastForwardBy(base::TimeDelta()); data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - source_site); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, source_site, AttributionNavigationType::kAnchor); // Wait for parsing to finish. task_environment_.FastForwardBy(base::TimeDelta()); @@ -1459,7 +1337,7 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); mojo::Remote<blink::mojom::AttributionDataHost> trigger_data_host_remote; data_host_manager_.RegisterDataHost( @@ -1510,15 +1388,15 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); // Wait for parsing. task_environment_.FastForwardBy(base::TimeDelta()); - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - source_site); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, source_site, AttributionNavigationType::kAnchor); checkpoint.Call(1); @@ -1530,7 +1408,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1559,14 +1437,14 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); data_host_manager_.NotifyNavigationRedirectRegistration( attribution_src_token, kRegisterSourceJson, reporter, source_site, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); // Wait for parsing. - data_host_manager_.NotifyNavigationForDataHost(attribution_src_token, - source_site); + data_host_manager_.NotifyNavigationForDataHost( + attribution_src_token, source_site, AttributionNavigationType::kAnchor); task_environment_.FastForwardBy(base::TimeDelta()); checkpoint.Call(1); @@ -1579,7 +1457,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1610,7 +1488,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1638,7 +1516,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -1674,7 +1552,8 @@ mojo::Remote<blink::mojom::AttributionDataHost> source_data_host_remote; data_host_manager_.RegisterNavigationDataHost( source_data_host_remote.BindNewPipeAndPassReceiver(), - attribution_src_token, AttributionInputEvent()); + attribution_src_token, AttributionInputEvent(), + AttributionNavigationType::kAnchor); mojo::Remote<blink::mojom::AttributionDataHost> trigger_data_host_remote; data_host_manager_.RegisterDataHost( @@ -1688,7 +1567,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1795,7 +1674,7 @@ auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report.test")); + *SuitableOrigin::Deserialize("https://report.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1902,9 +1781,9 @@ /*is_within_fenced_frame=*/false); auto source_data = blink::mojom::AttributionSourceData::New(); - source_data->destination = url::Origin::Create(GURL("https://dest.test")); + source_data->destination = *SuitableOrigin::Deserialize("https://dest.test"); source_data->reporting_origin = - url::Origin::Create(GURL("https://report1.test")); + *SuitableOrigin::Deserialize("https://report1.test"); source_data->filter_data = blink::mojom::AttributionFilterData::New(); source_data->aggregation_keys = blink::mojom::AttributionAggregationKeys::New(); @@ -1915,7 +1794,7 @@ // should be delayed. auto trigger_data = blink::mojom::AttributionTriggerData::New(); trigger_data->reporting_origin = - url::Origin::Create(GURL("https://report2.test")); + *SuitableOrigin::Deserialize("https://report2.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); trigger_data_host_remote->TriggerDataAvailable(std::move(trigger_data)); @@ -1941,7 +1820,8 @@ const blink::AttributionSrcToken attribution_src_token; data_host_manager_.NotifyNavigationForDataHost( attribution_src_token, - *SuitableOrigin::Deserialize("https://page.example")); + *SuitableOrigin::Deserialize("https://page.example"), + AttributionNavigationType::kAnchor); // kNotFound = 1. histograms.ExpectUniqueSample("Conversions.NavigationDataHostStatus", 1, 1); @@ -1996,15 +1876,17 @@ mojo::Remote<blink::mojom::AttributionDataHost> data_host_remote; data_host_manager_.RegisterNavigationDataHost( data_host_remote.BindNewPipeAndPassReceiver(), attribution_src_token, - AttributionInputEvent()); + AttributionInputEvent(), AttributionNavigationType::kAnchor); data_host_manager_.NotifyNavigationForDataHost( - attribution_src_token, *SuitableOrigin::Deserialize("https://s.test")); + attribution_src_token, *SuitableOrigin::Deserialize("https://s.test"), + AttributionNavigationType::kAnchor); mojo::test::BadMessageObserver bad_message_observer; auto trigger_data = blink::mojom::AttributionTriggerData::New(); - trigger_data->reporting_origin = url::Origin::Create(GURL("https://r.test")); + trigger_data->reporting_origin = + *SuitableOrigin::Deserialize("https://r.test"); trigger_data->filters = blink::mojom::AttributionFilters::New(); trigger_data->not_filters = blink::mojom::AttributionFilters::New(); @@ -2033,30 +1915,31 @@ EXPECT_TRUE(data_host_manager_.RegisterNavigationDataHost( data_host_remote1.BindNewPipeAndPassReceiver(), attribution_src_token, - AttributionInputEvent())); + AttributionInputEvent(), AttributionNavigationType::kAnchor)); // This one should not be registered, as `attribution_src_token` is already // associated with a receiver. EXPECT_FALSE(data_host_manager_.RegisterNavigationDataHost( data_host_remote2.BindNewPipeAndPassReceiver(), attribution_src_token, - AttributionInputEvent())); + AttributionInputEvent(), AttributionNavigationType::kAnchor)); // kRegistered = 0. histograms.ExpectUniqueSample("Conversions.NavigationDataHostStatus", 0, 1); } - const url::Origin destination_origin = - url::Origin::Create(GURL("https://trigger.example")); + const auto destination_origin = + *SuitableOrigin::Deserialize("https://trigger.example"); data_host_manager_.NotifyNavigationForDataHost( attribution_src_token, - *SuitableOrigin::Deserialize("https://page.example")); + *SuitableOrigin::Deserialize("https://page.example"), + AttributionNavigationType::kAnchor); auto source_data = blink::mojom::AttributionSourceData::New(); source_data->source_event_id = 1; source_data->destination = destination_origin; source_data->reporting_origin = - url::Origin::Create(GURL("https://reporter.example")); + *SuitableOrigin::Deserialize("https://reporter.example"); source_data->filter_data = blink::mojom::AttributionFilterData::New(); source_data->aggregation_keys = blink::mojom::AttributionAggregationKeys::New();
diff --git a/content/browser/attribution_reporting/attribution_host.cc b/content/browser/attribution_reporting/attribution_host.cc index aaac71a7..da2c3420 100644 --- a/content/browser/attribution_reporting/attribution_host.cc +++ b/content/browser/attribution_reporting/attribution_host.cc
@@ -112,7 +112,6 @@ !AttributionManager::FromWebContents(web_contents())) { return; } - RenderFrameHostImpl* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? RenderFrameHostImpl::FromFrameToken( @@ -193,10 +192,11 @@ if (!reporting_origin) return; + auto impression = navigation_handle->GetImpression(); data_host_manager->NotifyNavigationRedirectRegistration( navigation_handle->GetImpression()->attribution_src_token, std::move(source_header), std::move(*reporting_origin), - it->second.source_origin, it->second.input_event); + it->second.source_origin, it->second.input_event, impression->nav_type); } void AttributionHost::DidFinishNavigation(NavigationHandle* navigation_handle) { @@ -255,7 +255,7 @@ if (SuitableOrigin::IsSuitable(destination_origin)) { data_host_manager->NotifyNavigationForDataHost( - impression.attribution_src_token, source_origin); + impression.attribution_src_token, source_origin, impression.nav_type); } else { data_host_manager->NotifyNavigationFailure( impression.attribution_src_token); @@ -352,7 +352,8 @@ void AttributionHost::RegisterNavigationDataHost( mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, - const blink::AttributionSrcToken& attribution_src_token) { + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType nav_type) { // If there is no attribution manager available, ignore any registrations. AttributionManager* attribution_manager = AttributionManager::FromWebContents(web_contents()); @@ -369,7 +370,7 @@ if (!data_host_manager->RegisterNavigationDataHost( std::move(data_host), attribution_src_token, - GetMostRecentNavigationInputEvent())) { + GetMostRecentNavigationInputEvent(), nav_type)) { mojo::ReportBadMessage( "Renderer attempted to register a data host with a duplicate " "AttribtionSrcToken.");
diff --git a/content/browser/attribution_reporting/attribution_host.h b/content/browser/attribution_reporting/attribution_host.h index c0b3aa5..f7e9af5 100644 --- a/content/browser/attribution_reporting/attribution_host.h +++ b/content/browser/attribution_reporting/attribution_host.h
@@ -66,7 +66,8 @@ data_host) override; void RegisterNavigationDataHost( mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, - const blink::AttributionSrcToken& attribution_src_token) override; + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType nav_type) override; // WebContentsObserver: void DidStartNavigation(NavigationHandle* navigation_handle) override;
diff --git a/content/browser/attribution_reporting/attribution_host_unittest.cc b/content/browser/attribution_reporting/attribution_host_unittest.cc index 04847be4e..0ea026ef 100644 --- a/content/browser/attribution_reporting/attribution_host_unittest.cc +++ b/content/browser/attribution_reporting/attribution_host_unittest.cc
@@ -52,6 +52,8 @@ using testing::_; using testing::Return; +using ::blink::mojom::AttributionNavigationType; + const char kConversionUrl[] = "https://b.com"; class AttributionHostTest : public RenderViewHostTestHarness { @@ -122,12 +124,13 @@ TEST_F(AttributionHostTest, ValidAttributionSrc_ForwardedToManager) { blink::Impression impression; + impression.nav_type = AttributionNavigationType::kWindowOpen; - EXPECT_CALL( - *mock_data_host_manager(), - NotifyNavigationForDataHost( - impression.attribution_src_token, - *SuitableOrigin::Deserialize("https://secure_impression.com"))); + EXPECT_CALL(*mock_data_host_manager(), + NotifyNavigationForDataHost( + impression.attribution_src_token, + *SuitableOrigin::Deserialize("https://secure_impression.com"), + impression.nav_type)); contents()->NavigateAndCommit(GURL("https://secure_impression.com")); auto navigation = NavigationSimulatorImpl::CreateRendererInitiated( @@ -367,7 +370,7 @@ mojo::Remote<blink::mojom::AttributionDataHost> data_host_remote; conversion_host_mojom()->RegisterNavigationDataHost( data_host_remote.BindNewPipeAndPassReceiver(), - blink::AttributionSrcToken()); + blink::AttributionSrcToken(), AttributionNavigationType::kAnchor); EXPECT_EQ( "blink.mojom.ConversionHost can only be used with a secure top-level " @@ -389,7 +392,7 @@ mojo::Remote<blink::mojom::AttributionDataHost> data_host_remote; conversion_host_mojom()->RegisterNavigationDataHost( data_host_remote.BindNewPipeAndPassReceiver(), - blink::AttributionSrcToken()); + blink::AttributionSrcToken(), AttributionNavigationType::kAnchor); EXPECT_EQ( "Renderer attempted to register a data host with a duplicate "
diff --git a/content/browser/attribution_reporting/attribution_internals.mojom b/content/browser/attribution_reporting/attribution_internals.mojom index be26521f..e7ba6a4 100644 --- a/content/browser/attribution_reporting/attribution_internals.mojom +++ b/content/browser/attribution_reporting/attribution_internals.mojom
@@ -77,6 +77,18 @@ WebUIReportData data; }; +union DebugReportStatus { + int32 http_response_code; + string network_error; +}; + +struct WebUIDebugReport { + url.mojom.Url url; + double time; + string body; + DebugReportStatus status; +}; + struct DebugKey { uint64 value; }; @@ -218,6 +230,9 @@ // Called when a report is sent, regardless of success. OnReportSent(WebUIReport report); + // Called when a verbose debug report is sent, regardless of success. + OnDebugReportSent(WebUIDebugReport report); + // Called when a report is dropped from storage or prevented from being // created in the first place. OnReportDropped(WebUIReport report);
diff --git a/content/browser/attribution_reporting/attribution_internals_browsertest.cc b/content/browser/attribution_reporting/attribution_internals_browsertest.cc index 8ad00fb..90aaf61 100644 --- a/content/browser/attribution_reporting/attribution_internals_browsertest.cc +++ b/content/browser/attribution_reporting/attribution_internals_browsertest.cc
@@ -22,6 +22,7 @@ #include "components/attribution_reporting/source_registration_error.mojom.h" #include "components/attribution_reporting/suitable_origin.h" #include "components/attribution_reporting/trigger_registration.h" +#include "content/browser/attribution_reporting/attribution_debug_report.h" #include "content/browser/attribution_reporting/attribution_manager.h" #include "content/browser/attribution_reporting/attribution_observer_types.h" #include "content/browser/attribution_reporting/attribution_report.h" @@ -1315,4 +1316,43 @@ } } +IN_PROC_BROWSER_TEST_F(AttributionInternalsWebUiBrowserTest, + VerboseDebugReport) { + ASSERT_TRUE(NavigateToURL(shell(), GURL(kAttributionInternalsUrl))); + + absl::optional<AttributionDebugReport> report = + AttributionDebugReport::Create( + SourceBuilder().SetDebugReporting(true).Build(), + /*is_debug_cookie_set=*/true, + AttributionStorage::StoreSourceResult( + StorableSource::Result::kInternalError)); + ASSERT_TRUE(report); + + static constexpr char wait_script[] = R"( + const table = document.querySelector('#debugReportTable') + .shadowRoot.querySelector('tbody'); + + const url = 'https://report.test/.well-known/attribution-reporting/debug/verbose'; + + let obs = new MutationObserver((_, obs) => { + if (table.children.length === 1 && + table.children[0].children.length >= 4 && + table.children[0].children[1].innerText === url && + table.children[0].children[2].innerText === 'HTTP 200' && + table.children[0].children[3].innerText.includes('source-unknown-error') + ) { + obs.disconnect(); + document.title = $1; + } + }); + obs.observe(table, {'childList': true});)"; + + ASSERT_TRUE(ExecJsInWebUI(JsReplace(wait_script, kCompleteTitle))); + + TitleWatcher title_watcher(shell()->web_contents(), kCompleteTitle); + + manager()->NotifyDebugReportSent(*report, /*status=*/200, base::Time::Now()); + EXPECT_EQ(kCompleteTitle, title_watcher.WaitAndGetTitle()); +} + } // namespace content
diff --git a/content/browser/attribution_reporting/attribution_internals_handler_impl.cc b/content/browser/attribution_reporting/attribution_internals_handler_impl.cc index 8f2df9a2..b11b808 100644 --- a/content/browser/attribution_reporting/attribution_internals_handler_impl.cc +++ b/content/browser/attribution_reporting/attribution_internals_handler_impl.cc
@@ -26,6 +26,7 @@ #include "components/attribution_reporting/suitable_origin.h" #include "components/attribution_reporting/trigger_registration.h" #include "content/browser/attribution_reporting/aggregatable_attribution_utils.h" +#include "content/browser/attribution_reporting/attribution_debug_report.h" #include "content/browser/attribution_reporting/attribution_info.h" #include "content/browser/attribution_reporting/attribution_internals.mojom.h" #include "content/browser/attribution_reporting/attribution_observer_types.h" @@ -60,6 +61,8 @@ using ReportStatus = ::attribution_internals::mojom::ReportStatus; using ReportStatusPtr = ::attribution_internals::mojom::ReportStatusPtr; +using ::attribution_internals::mojom::WebUIDebugReport; + attribution_internals::mojom::DebugKeyPtr WebUIDebugKey( absl::optional<uint64_t> debug_key) { return debug_key ? attribution_internals::mojom::DebugKey::New(*debug_key) @@ -373,6 +376,30 @@ } } +void AttributionInternalsHandlerImpl::OnDebugReportSent( + const AttributionDebugReport& report, + int status, + base::Time time) { + if (observers_.empty()) + return; + + auto web_report = WebUIDebugReport::New(); + web_report->url = report.ReportURL(); + web_report->time = time.ToJsTime(); + web_report->body = + SerializeAttributionJson(report.ReportBody(), /*pretty_print=*/true); + + web_report->status = + status > 0 + ? attribution_internals::mojom::DebugReportStatus:: + NewHttpResponseCode(status) + : attribution_internals::mojom::DebugReportStatus::NewNetworkError( + net::ErrorToShortString(status)); + + for (auto& observer : observers_) + observer->OnDebugReportSent(web_report.Clone()); +} + // TODO(crbug/1351843): Consider surfacing this error in devtools instead of // internals, currently however this error is associated with a redirect // navigation, rather than a specific committed page.
diff --git a/content/browser/attribution_reporting/attribution_internals_handler_impl.h b/content/browser/attribution_reporting/attribution_internals_handler_impl.h index 5b5d181..6109f4f2 100644 --- a/content/browser/attribution_reporting/attribution_internals_handler_impl.h +++ b/content/browser/attribution_reporting/attribution_internals_handler_impl.h
@@ -81,6 +81,9 @@ void OnReportSent(const AttributionReport& report, bool is_debug_report, const SendResult& info) override; + void OnDebugReportSent(const AttributionDebugReport&, + int status, + base::Time) override; void OnTriggerHandled(const AttributionTrigger& trigger, absl::optional<uint64_t> cleared_debug_key, const CreateReportResult& result) override;
diff --git a/content/browser/attribution_reporting/attribution_manager_impl.cc b/content/browser/attribution_reporting/attribution_manager_impl.cc index 95fedf2..931ca34 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl.cc
@@ -945,6 +945,15 @@ observer.OnReportSent(report, /*is_debug_report=*/is_debug_report, info); } +void AttributionManagerImpl::NotifyDebugReportSent( + const AttributionDebugReport report, + const int status) { + // Use the same time for all observers. + const base::Time time = base::Time::Now(); + for (auto& observer : observers_) + observer.OnDebugReportSent(report, status, time); +} + void AttributionManagerImpl::AssembleAggregatableReport( AttributionReport report, bool is_debug_report, @@ -1042,7 +1051,10 @@ if (absl::optional<AttributionDebugReport> debug_report = AttributionDebugReport::Create(source, is_debug_cookie_set, result)) { - report_sender_->SendReport(std::move(*debug_report)); + report_sender_->SendReport( + std::move(*debug_report), + base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent, + weak_factory_.GetWeakPtr())); } } @@ -1065,7 +1077,10 @@ if (absl::optional<AttributionDebugReport> debug_report = AttributionDebugReport::Create(trigger, is_debug_cookie_set, result)) { - report_sender_->SendReport(std::move(*debug_report)); + report_sender_->SendReport( + std::move(*debug_report), + base::BindOnce(&AttributionManagerImpl::NotifyDebugReportSent, + weak_factory_.GetWeakPtr())); } }
diff --git a/content/browser/attribution_reporting/attribution_manager_impl.h b/content/browser/attribution_reporting/attribution_manager_impl.h index 7438530..d67c400 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl.h +++ b/content/browser/attribution_reporting/attribution_manager_impl.h
@@ -50,6 +50,7 @@ class AggregatableReportRequest; class AttributionCookieChecker; class AttributionDataHostManager; +class AttributionDebugReport; class AttributionStorage; class AttributionStorageDelegate; class CreateReportResult; @@ -231,6 +232,7 @@ void NotifySourcesChanged(); void NotifyReportsChanged(AttributionReport::Type report_type); void NotifyReportSent(bool is_debug_report, AttributionReport, SendResult); + void NotifyDebugReportSent(AttributionDebugReport, int status); bool IsReportAllowed(const AttributionReport&) const;
diff --git a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc index 12abc7c..4a1240f 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc
@@ -139,8 +139,9 @@ callbacks_.emplace_back(std::move(report), std::move(callback)); } - void SendReport(AttributionDebugReport report) override { - verbose_debug_calls_.push_back(std::move(report)); + void SendReport(AttributionDebugReport report, + DebugReportSentCallback callback) override { + verbose_debug_calls_.emplace_back(std::move(report), std::move(callback)); } const std::vector<AttributionReport>& calls() const { return calls_; } @@ -149,7 +150,8 @@ return debug_calls_; } - const std::vector<AttributionDebugReport>& verbose_debug_calls() const { + const std::vector<std::pair<AttributionDebugReport, DebugReportSentCallback>>& + verbose_debug_calls() const { return verbose_debug_calls_; } @@ -182,11 +184,25 @@ Reset(); } + void RunVerboseDebugCallbacks(std::initializer_list<int> statuses) { + ASSERT_THAT(verbose_debug_calls_, SizeIs(statuses.size())); + + const auto* status_it = statuses.begin(); + + for (auto& callback : verbose_debug_calls_) { + std::move(callback.second).Run(std::move(callback.first), *status_it); + status_it++; + } + + verbose_debug_calls_.clear(); + } + private: std::vector<AttributionReport> calls_; std::vector<AttributionReport> debug_calls_; std::vector<std::pair<AttributionReport, ReportSentCallback>> callbacks_; - std::vector<AttributionDebugReport> verbose_debug_calls_; + std::vector<std::pair<AttributionDebugReport, DebugReportSentCallback>> + verbose_debug_calls_; }; class MockCookieChecker : public AttributionCookieChecker { @@ -2236,7 +2252,7 @@ EXPECT_THAT(report_sender_->verbose_debug_calls(), SizeIs(1)); base::Value::List report_body = - report_sender_->verbose_debug_calls().front().ReportBody(); + report_sender_->verbose_debug_calls().front().first.ReportBody(); ASSERT_EQ(report_body.size(), 1u); ASSERT_TRUE(report_body.front().is_dict()); const base::Value::Dict* report_data = @@ -2291,6 +2307,14 @@ TEST_F(AttributionManagerImplCookieBasedDebugReportTest, VerboseDebugReport_ReportSent) { + MockAttributionObserver observer; + base::ScopedObservation<AttributionManager, AttributionObserver> observation( + &observer); + observation.Observe(attribution_manager_.get()); + + const int kExpectedStatus = 200; + EXPECT_CALL(observer, OnDebugReportSent(_, kExpectedStatus, _)); + url::Origin reporting_origin = url::Origin::Create(GURL("https://r1.test")); cookie_checker_->AddOriginWithDebugCookieSet(reporting_origin); @@ -2330,6 +2354,8 @@ .Build()); task_environment_.RunUntilIdle(); EXPECT_THAT(report_sender_->verbose_debug_calls(), SizeIs(1)); + + report_sender_->RunVerboseDebugCallbacks({kExpectedStatus}); } } // namespace content
diff --git a/content/browser/attribution_reporting/attribution_observer.h b/content/browser/attribution_reporting/attribution_observer.h index 7e878783..9cacb8d 100644 --- a/content/browser/attribution_reporting/attribution_observer.h +++ b/content/browser/attribution_reporting/attribution_observer.h
@@ -19,6 +19,7 @@ namespace content { +class AttributionDebugReport; class AttributionTrigger; class CreateReportResult; @@ -47,6 +48,13 @@ bool is_debug_report, const SendResult& info) {} + // Called when a verbose debug report is sent, regardless of success. + // If `status` is positive, it is the HTTP response code. Otherwise, it is the + // network error. + virtual void OnDebugReportSent(const AttributionDebugReport&, + int status, + base::Time) {} + // Called when a trigger is registered, regardless of success. virtual void OnTriggerHandled(const AttributionTrigger& trigger, absl::optional<uint64_t> cleared_debug_key,
diff --git a/content/browser/attribution_reporting/attribution_report_network_sender.cc b/content/browser/attribution_reporting/attribution_report_network_sender.cc index 0d3b2500..bf4bbd5 100644 --- a/content/browser/attribution_reporting/attribution_report_network_sender.cc +++ b/content/browser/attribution_reporting/attribution_report_network_sender.cc
@@ -65,12 +65,16 @@ is_debug_report, std::move(sent_callback))); } -void AttributionReportNetworkSender::SendReport(AttributionDebugReport report) { +void AttributionReportNetworkSender::SendReport( + AttributionDebugReport report, + DebugReportSentCallback callback) { GURL url = report.ReportURL(); base::Value::List body = report.ReportBody(); - SendReport(std::move(url), body, - base::BindOnce(&AttributionReportNetworkSender::OnDebugReportSent, - base::Unretained(this))); + SendReport( + std::move(url), body, + base::BindOnce(&AttributionReportNetworkSender::OnDebugReportSent, + base::Unretained(this), + base::BindOnce(std::move(callback), std::move(report)))); } void AttributionReportNetworkSender::SendReport(GURL url, @@ -228,9 +232,13 @@ } void AttributionReportNetworkSender::OnDebugReportSent( + base::OnceCallback<void(int status)> callback, UrlLoaderList::iterator it, scoped_refptr<net::HttpResponseHeaders> headers) { + // HTTP statuses are positive; network errors are negative. + int status = headers ? headers->response_code() : (*it)->NetError(); loaders_in_progress_.erase(it); + std::move(callback).Run(status); // TODO(crbug.com/1371970): Consider recording metric for debug report // sending.
diff --git a/content/browser/attribution_reporting/attribution_report_network_sender.h b/content/browser/attribution_reporting/attribution_report_network_sender.h index e8ef642..22b8d5c 100644 --- a/content/browser/attribution_reporting/attribution_report_network_sender.h +++ b/content/browser/attribution_reporting/attribution_report_network_sender.h
@@ -53,7 +53,8 @@ void SendReport(AttributionReport report, bool is_debug_report, ReportSentCallback sent_callback) override; - void SendReport(AttributionDebugReport report) override; + void SendReport(AttributionDebugReport report, + DebugReportSentCallback) override; private: // This is a std::list so that iterators remain valid during modifications. @@ -75,7 +76,8 @@ scoped_refptr<net::HttpResponseHeaders> headers); // Called when headers are available for a sent debug report. - void OnDebugReportSent(UrlLoaderList::iterator it, + void OnDebugReportSent(base::OnceCallback<void(int status)> callback, + UrlLoaderList::iterator it, scoped_refptr<net::HttpResponseHeaders> headers); // Reports that are actively being sent.
diff --git a/content/browser/attribution_reporting/attribution_report_network_sender_unittest.cc b/content/browser/attribution_reporting/attribution_report_network_sender_unittest.cc index a6d0ed8e..80a490c 100644 --- a/content/browser/attribution_reporting/attribution_report_network_sender_unittest.cc +++ b/content/browser/attribution_reporting/attribution_report_network_sender_unittest.cc
@@ -43,6 +43,7 @@ using ::attribution_reporting::SuitableOrigin; +using ::testing::_; using ::testing::Field; using ::testing::InSequence; using ::testing::Mock; @@ -970,7 +971,10 @@ /*max_destinations_per_source_site_reporting_origin=*/3)); ASSERT_TRUE(report); - network_sender_->SendReport(std::move(*report)); + base::MockCallback<AttributionReportSender::DebugReportSentCallback> callback; + EXPECT_CALL(callback, Run(_, 200)); + + network_sender_->SendReport(std::move(*report), callback.Get()); const network::ResourceRequest* pending_request; EXPECT_TRUE( @@ -980,4 +984,34 @@ kErrorReportUrl, "")); } +TEST_F(AttributionReportNetworkSenderTest, + ErrorReportSent_CallbackInvokedWithNetworkError) { + static constexpr char kErrorReportUrl[] = + "https://report.test/.well-known/attribution-reporting/debug/verbose"; + + absl::optional<AttributionDebugReport> report = + AttributionDebugReport::Create( + SourceBuilder().SetDebugReporting(true).Build(), + /*is_debug_cookie_set=*/false, + AttributionStorage::StoreSourceResult( + StorableSource::Result::kInsufficientUniqueDestinationCapacity, + /*min_fake_report_time=*/absl::nullopt, + /*max_destinations_per_source_site_reporting_origin=*/3)); + ASSERT_TRUE(report); + + base::MockCallback<AttributionReportSender::DebugReportSentCallback> callback; + EXPECT_CALL(callback, Run(_, net::ERR_CONNECTION_ABORTED)); + + network_sender_->SendReport(std::move(*report), callback.Get()); + + const network::ResourceRequest* pending_request; + EXPECT_TRUE( + test_url_loader_factory_.IsPending(kErrorReportUrl, &pending_request)); + + test_url_loader_factory_.SimulateResponseForPendingRequest( + GURL(kErrorReportUrl), + network::URLLoaderCompletionStatus(net::ERR_CONNECTION_ABORTED), + network::mojom::URLResponseHead::New(), ""); +} + } // namespace content
diff --git a/content/browser/attribution_reporting/attribution_report_sender.h b/content/browser/attribution_reporting/attribution_report_sender.h index cdf884f..d6cf22a8 100644 --- a/content/browser/attribution_reporting/attribution_report_sender.h +++ b/content/browser/attribution_reporting/attribution_report_sender.h
@@ -24,12 +24,17 @@ using ReportSentCallback = base::OnceCallback<void(AttributionReport, SendResult)>; + // If `status` is positive, it is the HTTP response code. Otherwise, it is the + // network error. + using DebugReportSentCallback = + base::OnceCallback<void(AttributionDebugReport, int status)>; + // Sends `report` and runs `sent_callback` when done. virtual void SendReport(AttributionReport report, bool is_debug_report, ReportSentCallback sent_callback) = 0; - virtual void SendReport(AttributionDebugReport report) = 0; + virtual void SendReport(AttributionDebugReport, DebugReportSentCallback) = 0; }; } // namespace content
diff --git a/content/browser/attribution_reporting/attribution_src_browsertest.cc b/content/browser/attribution_reporting/attribution_src_browsertest.cc index 7a9000b..0c59942c 100644 --- a/content/browser/attribution_reporting/attribution_src_browsertest.cc +++ b/content/browser/attribution_reporting/attribution_src_browsertest.cc
@@ -10,6 +10,8 @@ #include "base/strings/strcat.h" #include "base/strings/string_piece.h" #include "base/test/scoped_feature_list.h" +#include "components/attribution_reporting/suitable_origin.h" +#include "components/attribution_reporting/test_utils.h" #include "content/browser/attribution_reporting/attribution_manager_impl.h" #include "content/browser/attribution_reporting/attribution_test_utils.h" #include "content/public/browser/navigation_handle.h" @@ -42,6 +44,7 @@ namespace { +using ::attribution_reporting::SuitableOrigin; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Field; @@ -142,7 +145,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.front()->source_event_id, 5UL); EXPECT_EQ(source_data.front()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_EQ(source_data.front()->priority, 0); EXPECT_EQ(source_data.front()->expiry, absl::nullopt); EXPECT_FALSE(source_data.front()->debug_key); @@ -189,7 +192,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.front()->source_event_id, 5UL); EXPECT_EQ(source_data.front()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_EQ(source_data.front()->priority, 0); EXPECT_EQ(source_data.front()->expiry, absl::nullopt); EXPECT_FALSE(source_data.front()->debug_key); @@ -252,9 +255,12 @@ EXPECT_CALL(mock_attribution_host(), RegisterNavigationDataHost) .WillOnce( [&](mojo::PendingReceiver<blink::mojom::AttributionDataHost> host, - const blink::AttributionSrcToken& attribution_src_token) { + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType nav_type) { data_host = GetRegisteredDataHost(std::move(host)); expected_token = attribution_src_token; + EXPECT_EQ(nav_type, + blink::mojom::AttributionNavigationType::kAnchor); }); GURL register_url = @@ -269,6 +275,8 @@ // Verify we received the correct token for this source. EXPECT_EQ(last_impression.attribution_src_token, expected_token); + EXPECT_EQ(last_impression.nav_type, + blink::mojom::AttributionNavigationType::kAnchor); // Verify the attributionsrc data was registered with the browser process. EXPECT_TRUE(data_host); @@ -291,9 +299,12 @@ EXPECT_CALL(mock_attribution_host(), RegisterNavigationDataHost) .WillOnce( [&](mojo::PendingReceiver<blink::mojom::AttributionDataHost> host, - const blink::AttributionSrcToken& attribution_src_token) { + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType nav_type) { data_host = GetRegisteredDataHost(std::move(host)); expected_token = attribution_src_token; + EXPECT_EQ(nav_type, + blink::mojom::AttributionNavigationType::kWindowOpen); }); GURL register_url = @@ -307,6 +318,8 @@ // Verify we received the correct token for this source. EXPECT_EQ(last_impression.attribution_src_token, expected_token); + EXPECT_EQ(last_impression.nav_type, + blink::mojom::AttributionNavigationType::kWindowOpen); // Verify the attributionsrc data was registered with the browser process. EXPECT_TRUE(data_host); @@ -477,7 +490,8 @@ EXPECT_CALL(mock_attribution_host(), RegisterNavigationDataHost) .WillOnce( [&](mojo::PendingReceiver<blink::mojom::AttributionDataHost> host, - const blink::AttributionSrcToken& attribution_src_token) { + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType nav_type) { data_host = GetRegisteredDataHost(std::move(host)); expected_token = attribution_src_token; }); @@ -522,7 +536,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.front()->source_event_id, 5UL); EXPECT_EQ(source_data.front()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_EQ(source_data.front()->priority, 10); EXPECT_EQ(source_data.front()->expiry, base::Seconds(1000)); EXPECT_EQ(source_data.front()->debug_key, 789u); @@ -561,7 +575,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.front()->source_event_id, 5UL); EXPECT_EQ(source_data.front()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_EQ(source_data.front()->priority, 0); EXPECT_EQ(source_data.front()->expiry, absl::nullopt); EXPECT_FALSE(source_data.front()->debug_key); @@ -599,10 +613,10 @@ EXPECT_EQ(source_data.size(), 2u); EXPECT_EQ(source_data.front()->source_event_id, 1UL); EXPECT_EQ(source_data.front()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_EQ(source_data.back()->source_event_id, 5UL); EXPECT_EQ(source_data.back()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); } IN_PROC_BROWSER_TEST_F(AttributionSrcBrowserTest, @@ -634,7 +648,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.back()->source_event_id, 5UL); EXPECT_EQ(source_data.back()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); } IN_PROC_BROWSER_TEST_F(AttributionSrcBrowserTest, @@ -695,7 +709,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.back()->source_event_id, 5UL); EXPECT_EQ(source_data.back()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); } IN_PROC_BROWSER_TEST_F(AttributionSrcBrowserTest, @@ -923,7 +937,7 @@ EXPECT_EQ(trigger_data.size(), 1u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT(trigger_data.front()->filters->filter_values, IsEmpty()); EXPECT_FALSE(trigger_data.front()->debug_key); EXPECT_EQ(trigger_data.front()->event_triggers.size(), 1u); @@ -985,7 +999,7 @@ EXPECT_EQ(trigger_data.size(), 1u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT( trigger_data.front()->filters->filter_values, ElementsAre(Pair("w", IsEmpty()), Pair("x", ElementsAre("y", "z")))); @@ -1049,7 +1063,7 @@ EXPECT_EQ(trigger_data.size(), 1u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT(trigger_data.front()->event_triggers, IsEmpty()); EXPECT_THAT( @@ -1101,7 +1115,7 @@ EXPECT_EQ(trigger_data.size(), 1u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_EQ(trigger_data.front()->event_triggers.size(), 1u); EXPECT_EQ(trigger_data.front()->event_triggers.front()->data, 7u); } @@ -1190,7 +1204,7 @@ EXPECT_EQ(trigger_data.size(), 2u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); // Both triggers should be processed. EXPECT_EQ(trigger_data.front()->event_triggers.front()->data, 5u); @@ -1254,7 +1268,7 @@ EXPECT_EQ(source_data.size(), 1u); EXPECT_EQ(source_data.back()->source_event_id, 5UL); EXPECT_EQ(source_data.back()->destination, - url::Origin::Create(GURL("https://d.test"))); + *SuitableOrigin::Deserialize("https://d.test")); EXPECT_THAT(source_data.back()->aggregation_keys->keys, SizeIs(2)); }
diff --git a/content/browser/attribution_reporting/attribution_test_utils.cc b/content/browser/attribution_reporting/attribution_test_utils.cc index 249291d..a411da43 100644 --- a/content/browser/attribution_reporting/attribution_test_utils.cc +++ b/content/browser/attribution_reporting/attribution_test_utils.cc
@@ -412,6 +412,14 @@ observer.OnTriggerHandled(trigger, cleared_debug_key, result); } +void MockAttributionManager::NotifyDebugReportSent( + const AttributionDebugReport& report, + const int status, + const base::Time time) { + for (auto& observer : observers_) + observer.OnDebugReportSent(report, status, time); +} + void MockAttributionManager::SetDataHostManager( std::unique_ptr<AttributionDataHostManager> manager) { data_host_manager_ = std::move(manager);
diff --git a/content/browser/attribution_reporting/attribution_test_utils.h b/content/browser/attribution_reporting/attribution_test_utils.h index 23d6935..9b0d369 100644 --- a/content/browser/attribution_reporting/attribution_test_utils.h +++ b/content/browser/attribution_reporting/attribution_test_utils.h
@@ -116,7 +116,8 @@ void, RegisterNavigationDataHost, (mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, - const blink::AttributionSrcToken& attribution_src_token), + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType), (override)); private: @@ -181,7 +182,8 @@ RegisterNavigationDataHost, (mojo::PendingReceiver<blink::mojom::AttributionDataHost> data_host, const blink::AttributionSrcToken& attribution_src_token, - AttributionInputEvent input_event), + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType), (override)); MOCK_METHOD(void, @@ -190,13 +192,15 @@ std::string header_value, attribution_reporting::SuitableOrigin reporting_origin, const attribution_reporting::SuitableOrigin& source_origin, - AttributionInputEvent input_event), + AttributionInputEvent input_event, + blink::mojom::AttributionNavigationType), (override)); MOCK_METHOD(void, NotifyNavigationForDataHost, (const blink::AttributionSrcToken& attribution_src_token, - const attribution_reporting::SuitableOrigin& source_origin), + const attribution_reporting::SuitableOrigin& source_origin, + blink::mojom::AttributionNavigationType), (override)); MOCK_METHOD(void, @@ -352,6 +356,9 @@ const std::string& header_value, const attribution_reporting::SuitableOrigin& reporting_origin, attribution_reporting::mojom::SourceRegistrationError); + void NotifyDebugReportSent(const AttributionDebugReport&, + int status, + base::Time time); void SetDataHostManager(std::unique_ptr<AttributionDataHostManager> manager); @@ -390,6 +397,13 @@ (override)); MOCK_METHOD(void, + OnDebugReportSent, + (const AttributionDebugReport& report, + int status, + base::Time time), + (override)); + + MOCK_METHOD(void, OnTriggerHandled, (const AttributionTrigger& trigger, absl::optional<uint64_t> cleared_debug_key,
diff --git a/content/browser/attribution_reporting/trigger_registration_browsertest.cc b/content/browser/attribution_reporting/trigger_registration_browsertest.cc index 52ecafcd..985f30ef 100644 --- a/content/browser/attribution_reporting/trigger_registration_browsertest.cc +++ b/content/browser/attribution_reporting/trigger_registration_browsertest.cc
@@ -5,6 +5,8 @@ #include <memory> #include "base/bind.h" +#include "components/attribution_reporting/suitable_origin.h" +#include "components/attribution_reporting/test_utils.h" #include "content/browser/attribution_reporting/attribution_manager_impl.h" #include "content/browser/attribution_reporting/attribution_test_utils.h" #include "content/browser/web_contents/web_contents_impl.h" @@ -27,6 +29,7 @@ namespace { +using ::attribution_reporting::SuitableOrigin; using ::testing::ElementsAre; using ::testing::Field; using ::testing::Pointee; @@ -105,7 +108,7 @@ EXPECT_EQ(trigger_data.size(), 1u); EXPECT_EQ(trigger_data.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT( trigger_data.front()->event_triggers, ElementsAre(Pointee(Field(&blink::mojom::EventTriggerData::data, 1)), @@ -143,7 +146,7 @@ EXPECT_EQ(trigger_data1.size(), 1u); EXPECT_EQ(trigger_data1.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT( trigger_data1.front()->event_triggers, ElementsAre(Pointee(Field(&blink::mojom::EventTriggerData::data, 5)))); @@ -153,7 +156,7 @@ EXPECT_EQ(trigger_data2.size(), 1u); EXPECT_EQ(trigger_data2.front()->reporting_origin, - url::Origin::Create(register_url)); + *SuitableOrigin::Create(register_url)); EXPECT_THAT( trigger_data2.front()->event_triggers, ElementsAre(Pointee(Field(&blink::mojom::EventTriggerData::data, 7))));
diff --git a/content/browser/devtools/web_contents_devtools_agent_host.cc b/content/browser/devtools/web_contents_devtools_agent_host.cc index 20976a4..fb8e10a1 100644 --- a/content/browser/devtools/web_contents_devtools_agent_host.cc +++ b/content/browser/devtools/web_contents_devtools_agent_host.cc
@@ -318,6 +318,7 @@ // TODO(caseq): figure out if this can be a CHECK(). if (!web_contents()) return false; + session->SetBrowserOnly(true); const bool may_attach_to_brower = session->GetClient()->IsTrusted(); session->CreateAndAddHandler<protocol::TargetHandler>( may_attach_to_brower
diff --git a/content/browser/file_system_access/file_system_access_handle_base.cc b/content/browser/file_system_access/file_system_access_handle_base.cc index 1e5e4ba..c9b892d 100644 --- a/content/browser/file_system_access/file_system_access_handle_base.cc +++ b/content/browser/file_system_access/file_system_access_handle_base.cc
@@ -32,9 +32,13 @@ #include "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom-forward.h" namespace features { +// TODO(crbug.com/1381621): This feature was disabled since it does not match +// standard POSIX behavior. We should explore adding a flag to allow opting in +// to overwriting moves. See discussion at +// https://github.com/whatwg/fs/pull/10#issuecomment-1322993643. BASE_FEATURE(kFileSystemAccessDoNotOverwriteOnMove, "FileSystemAccessDoNotOverwriteOnMove", - base::FEATURE_ENABLED_BY_DEFAULT); + base::FEATURE_DISABLED_BY_DEFAULT); } // namespace features namespace content {
diff --git a/content/browser/file_system_access/file_system_access_handle_base.h b/content/browser/file_system_access/file_system_access_handle_base.h index cee1cb4..7ff6d3c 100644 --- a/content/browser/file_system_access/file_system_access_handle_base.h +++ b/content/browser/file_system_access/file_system_access_handle_base.h
@@ -19,7 +19,7 @@ #include "third_party/blink/public/mojom/permissions/permission_status.mojom.h" namespace features { -// TODO(crbug.com/1366652): Remove this flag eventually. +// TODO(crbug.com/1381621): Remove this flag eventually. // When enabled, move() will result in a promise rejection when the specified // destination to move to exists. BASE_DECLARE_FEATURE(kFileSystemAccessDoNotOverwriteOnMove);
diff --git a/content/browser/first_party_sets/database/first_party_sets_database.cc b/content/browser/first_party_sets/database/first_party_sets_database.cc index 77ea4b71..effb5cf 100644 --- a/content/browser/first_party_sets/database/first_party_sets_database.cc +++ b/content/browser/first_party_sets/database/first_party_sets_database.cc
@@ -366,12 +366,35 @@ return true; } +std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> +FirstPartySetsDatabase::GetGlobalSetsAndConfig( + const std::string& browser_context_id) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!browser_context_id.empty()); + if (!LazyInit()) + return {}; + + sql::Transaction transaction(db_.get()); + if (!transaction.Begin()) + return {}; + + net::GlobalFirstPartySets global_sets = GetGlobalSets(browser_context_id); + + net::FirstPartySetsContextConfig config = + FetchPolicyConfigurations(browser_context_id); + + if (!transaction.Commit()) + return {}; + + return std::make_pair(std::move(global_sets), std::move(config)); +} + net::GlobalFirstPartySets FirstPartySetsDatabase::GetGlobalSets( const std::string& browser_context_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!LazyInit()) - return {}; + DCHECK(db_->HasActiveTransactions()); + DCHECK_EQ(db_status_, InitStatus::kSuccess); + DCHECK(!browser_context_id.empty()); // Query public sets entries. std::vector<std::pair<net::SchemefulSite, net::FirstPartySetEntry>> entries; @@ -543,9 +566,9 @@ FirstPartySetsDatabase::FetchPolicyConfigurations( const std::string& browser_context_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!LazyInit()) - return {}; + DCHECK(db_->HasActiveTransactions()); + DCHECK_EQ(db_status_, InitStatus::kSuccess); + DCHECK(!browser_context_id.empty()); std::vector< std::pair<net::SchemefulSite, absl::optional<net::FirstPartySetEntry>>> @@ -616,9 +639,9 @@ FirstPartySetsDatabase::FetchManualConfiguration( const std::string& browser_context_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (!LazyInit()) - return {}; + DCHECK(db_->HasActiveTransactions()); + DCHECK_EQ(db_status_, InitStatus::kSuccess); + DCHECK(!browser_context_id.empty()); std::vector< std::pair<net::SchemefulSite, absl::optional<net::FirstPartySetEntry>>>
diff --git a/content/browser/first_party_sets/database/first_party_sets_database.h b/content/browser/first_party_sets/database/first_party_sets_database.h index 3d4fc35..65a875d78 100644 --- a/content/browser/first_party_sets/database/first_party_sets_database.h +++ b/content/browser/first_party_sets/database/first_party_sets_database.h
@@ -14,7 +14,6 @@ #include "base/containers/flat_map.h" #include "base/containers/flat_set.h" #include "base/files/file_path.h" -#include "base/gtest_prod_util.h" #include "base/sequence_checker.h" #include "base/thread_annotations.h" #include "content/common/content_export.h" @@ -90,9 +89,11 @@ // TODO(crbug.com/1219656): Consider returning absl::nullopt for all the // fetching methods when having query errors - // Gets the global First-Party Sets used by `browser_context_id`. - [[nodiscard]] net::GlobalFirstPartySets GetGlobalSets( - const std::string& browser_context_id); + // Gets the global First-Party Sets and the config used by + // `browser_context_id`. + [[nodiscard]] std::pair<net::GlobalFirstPartySets, + net::FirstPartySetsContextConfig> + GetGlobalSetsAndConfig(const std::string& browser_context_id); // Gets the sites to clear filters. The first filter holds the list of sites // that haven't had their cookies/storage cleared, the second filter is the @@ -103,11 +104,6 @@ net::FirstPartySetsCacheFilter> GetSitesToClearFilters(const std::string& browser_context_id); - // Gets the previously-stored policy configurations for the - // `browser_context_id`. - [[nodiscard]] net::FirstPartySetsContextConfig FetchPolicyConfigurations( - const std::string& browser_context_id); - // Check whether the `browser_context_id` has performed clearing. [[nodiscard]] bool HasEntryInBrowserContextsClearedForTesting( const std::string& browser_context_id); @@ -133,11 +129,20 @@ const std::string& browser_context_id, const net::FirstPartySetsContextConfig& policy_config); + // Gets the global First-Party Sets used by `browser_context_id`. + [[nodiscard]] net::GlobalFirstPartySets GetGlobalSets( + const std::string& browser_context_id); + // Gets the previously-stored manual configuration for the // `browser_context_id`. [[nodiscard]] net::FirstPartySetsContextConfig FetchManualConfiguration( const std::string& browser_context_id); + // Gets the previously-stored policy configuration for the + // `browser_context_id`. + [[nodiscard]] net::FirstPartySetsContextConfig FetchPolicyConfigurations( + const std::string& browser_context_id); + // Gets the list of sites to clear for the `browser_context_id`. [[nodiscard]] std::vector<net::SchemefulSite> FetchSitesToClear( const std::string& browser_context_id);
diff --git a/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc b/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc index f83c865..f5449a0 100644 --- a/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc +++ b/content/browser/first_party_sets/database/first_party_sets_database_unittest.cc
@@ -932,42 +932,15 @@ EXPECT_EQ(res.second, cache_filter); } -TEST_F(FirstPartySetsDatabaseTest, FetchPolicyConfigurations_NoPreExistingDB) { +TEST_F(FirstPartySetsDatabaseTest, GetSets_NoPreExistingDB) { OpenDatabase(); - EXPECT_TRUE(db()->FetchPolicyConfigurations("b").empty()); + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> res = + db()->GetGlobalSetsAndConfig("b"); + EXPECT_TRUE(res.first.empty()); + EXPECT_TRUE(res.second.empty()); } -TEST_F(FirstPartySetsDatabaseTest, FetchPolicyConfigurations) { - ASSERT_TRUE(sql::test::CreateDatabaseFromSQL(db_path(), - GetCurrentVersionSqlFilePath())); - - // Verify data in the pre-existing DB. - { - sql::Database db; - EXPECT_TRUE(db.Open(db_path())); - EXPECT_EQ(kTableCount, sql::test::CountSQLTables(&db)); - EXPECT_EQ(2u, CountPolicyConfigurationsEntries(&db)); - } - net::FirstPartySetsContextConfig res({ - {net::SchemefulSite(GURL("https://member1.test")), - net::FirstPartySetEntry( - {net::SchemefulSite(GURL("https://example.test"))}, - net::SiteType::kAssociated, absl::nullopt)}, - {net::SchemefulSite(GURL("https://member2.test")), absl::nullopt}, - }); - OpenDatabase(); - EXPECT_EQ(db()->FetchPolicyConfigurations("b2"), res); -} - -TEST_F(FirstPartySetsDatabaseTest, GetGlobalSets_NoPreExistingDB) { - OpenDatabase(); - EXPECT_THAT(db()->GetGlobalSets("b").FindEntries( - {net::SchemefulSite(GURL("https://example.test"))}, - net::FirstPartySetsContextConfig()), - IsEmpty()); -} - -TEST_F(FirstPartySetsDatabaseTest, GetGlobalSets_NoPublicSets) { +TEST_F(FirstPartySetsDatabaseTest, GetSets_NoPublicSets) { const std::string browser_context_id = "b"; const net::SchemefulSite site(GURL("https://site.test")); const net::SchemefulSite primary(GURL("https://primary.test")); @@ -997,10 +970,13 @@ // that public sets will not be persisted. ASSERT_TRUE(db()->PersistSets(browser_context_id, global_sets, net::FirstPartySetsContextConfig())); + + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> res = + db()->GetGlobalSetsAndConfig(browser_context_id); + EXPECT_THAT( - db()->GetGlobalSets(browser_context_id) - .FindEntries({manual_site, manual_primary}, - net::FirstPartySetsContextConfig()), + res.first.FindEntries({manual_site, manual_primary}, + net::FirstPartySetsContextConfig()), UnorderedElementsAre( Pair(manual_site, net::FirstPartySetEntry( @@ -1008,9 +984,10 @@ Pair(manual_primary, net::FirstPartySetEntry(manual_primary, net::SiteType::kPrimary, absl::nullopt)))); + EXPECT_TRUE(res.second.empty()); } -TEST_F(FirstPartySetsDatabaseTest, GetGlobalSets) { +TEST_F(FirstPartySetsDatabaseTest, GetSets) { ASSERT_TRUE(sql::test::CreateDatabaseFromSQL(db_path(), GetCurrentVersionSqlFilePath())); @@ -1020,15 +997,19 @@ EXPECT_TRUE(db.Open(db_path())); EXPECT_EQ(2u, CountPublicSetsEntries(&db)); EXPECT_EQ(3u, CountBrowserContextSetsVersionEntries(&db)); + EXPECT_EQ(2u, CountPolicyConfigurationsEntries(&db)); } const net::SchemefulSite aaa(GURL("https://aaa.test")); const net::SchemefulSite bbb(GURL("https://bbb.test")); const net::SchemefulSite ccc(GURL("https://ccc.test")); const net::SchemefulSite ddd(GURL("https://ddd.test")); OpenDatabase(); + + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> res = + db()->GetGlobalSetsAndConfig("b0"); EXPECT_THAT( - db()->GetGlobalSets("b0").FindEntries({aaa, bbb, ccc, ddd}, - net::FirstPartySetsContextConfig()), + res.first.FindEntries({aaa, bbb, ccc, ddd}, + net::FirstPartySetsContextConfig()), UnorderedElementsAre( Pair(aaa, net::FirstPartySetEntry(bbb, net::SiteType::kAssociated, absl::nullopt)), @@ -1038,6 +1019,7 @@ absl::nullopt)), Pair(ddd, net::FirstPartySetEntry(ddd, net::SiteType::kPrimary, absl::nullopt)))); + EXPECT_EQ(res.second, net::FirstPartySetsContextConfig()); } TEST_F(FirstPartySetsDatabaseTest, @@ -1109,8 +1091,10 @@ // Trigger the lazy-initialization. EXPECT_TRUE(db()->PersistSets(browser_context_id, global_sets, config)); - EXPECT_EQ(db()->GetGlobalSets(browser_context_id), global_sets); - EXPECT_EQ(db()->FetchPolicyConfigurations(browser_context_id), config); + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> res = + db()->GetGlobalSetsAndConfig(browser_context_id); + EXPECT_EQ(res.first, global_sets); + EXPECT_EQ(res.second, config); } class FirstPartySetsDatabaseMigrationsTest : public FirstPartySetsDatabaseTest { @@ -1120,7 +1104,7 @@ void MigrateDatabase() { FirstPartySetsDatabase db(db_path()); // Trigger the lazy-initialization. - std::ignore = db.FetchPolicyConfigurations("b"); + std::ignore = db.GetGlobalSetsAndConfig("b"); } static int VersionFromDatabase(sql::Database* db) { @@ -1137,7 +1121,7 @@ { FirstPartySetsDatabase db(db_path()); // Trigger the lazy-initialization. - std::ignore = db.FetchPolicyConfigurations("b"); + std::ignore = db.GetGlobalSetsAndConfig("b"); } // Verify schema is current.
diff --git a/content/browser/first_party_sets/first_party_sets_handler_database_helper.cc b/content/browser/first_party_sets/first_party_sets_handler_database_helper.cc index 0a7775b..c3c6804 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_database_helper.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_database_helper.cc
@@ -6,7 +6,6 @@ #include "base/containers/contains.h" #include "base/logging.h" -#include "base/version.h" #include "content/browser/first_party_sets/database/first_party_sets_database.h" #include "net/base/schemeful_site.h" #include "net/first_party_sets/first_party_set_entry.h" @@ -64,9 +63,10 @@ const net::FirstPartySetsContextConfig& current_config) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!browser_context_id.empty()); + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> + old_sets_with_config = db_->GetGlobalSetsAndConfig(browser_context_id); base::flat_set<net::SchemefulSite> diff = - ComputeSetsDiff(db_->GetGlobalSets(browser_context_id), - db_->FetchPolicyConfigurations(browser_context_id), + ComputeSetsDiff(old_sets_with_config.first, old_sets_with_config.second, current_sets, current_config); if (!db_->InsertSitesToClear(browser_context_id, diff)) { @@ -96,12 +96,12 @@ DVLOG(1) << "Failed to write sets into the database."; } -net::GlobalFirstPartySets -FirstPartySetsHandlerDatabaseHelper::GetPersistedGlobalSets( +std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> +FirstPartySetsHandlerDatabaseHelper::GetGlobalSetsAndConfigForTesting( const std::string& browser_context_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!browser_context_id.empty()); - return db_->GetGlobalSets(browser_context_id); + return db_->GetGlobalSetsAndConfig(browser_context_id); } // Wraps FirstPartySetsDatabase::HasEntryInBrowserContextsClearedForTesting.
diff --git a/content/browser/first_party_sets/first_party_sets_handler_database_helper.h b/content/browser/first_party_sets/first_party_sets_handler_database_helper.h index a0a0674..5fd8359b 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_database_helper.h +++ b/content/browser/first_party_sets/first_party_sets_handler_database_helper.h
@@ -10,12 +10,10 @@ #include <utility> #include <vector> -#include "base/containers/flat_map.h" #include "base/containers/flat_set.h" #include "base/files/file_path.h" #include "base/sequence_checker.h" #include "content/common/content_export.h" -#include "third_party/abseil-cpp/absl/types/optional.h" namespace net { class FirstPartySetsCacheFilter; @@ -84,9 +82,8 @@ const net::GlobalFirstPartySets& sets, const net::FirstPartySetsContextConfig& config); - // Wraps FirstPartySetsDatabase::GetGlobalSets. - net::GlobalFirstPartySets GetPersistedGlobalSets( - const std::string& browser_context_id); + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig> + GetGlobalSetsAndConfigForTesting(const std::string& browser_context_id); // Wraps FirstPartySetsDatabase::HasEntryInBrowserContextClearedForTesting. bool HasEntryInBrowserContextsClearedForTesting(
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl.cc b/content/browser/first_party_sets/first_party_sets_handler_impl.cc index c0ea195..3c457c85 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_impl.cc
@@ -210,9 +210,11 @@ sets_loader_->SetComponentSets(version, std::move(sets_file)); } -void FirstPartySetsHandlerImpl::GetPersistedGlobalSetsForTesting( +void FirstPartySetsHandlerImpl::GetPersistedSetsForTesting( const std::string& browser_context_id, - base::OnceCallback<void(absl::optional<net::GlobalFirstPartySets>)> + base::OnceCallback< + void(absl::optional<std::pair<net::GlobalFirstPartySets, + net::FirstPartySetsContextConfig>>)> callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!browser_context_id.empty()); @@ -221,7 +223,8 @@ return; } db_helper_ - .AsyncCall(&FirstPartySetsHandlerDatabaseHelper::GetPersistedGlobalSets) + .AsyncCall(&FirstPartySetsHandlerDatabaseHelper:: + GetGlobalSetsAndConfigForTesting) // IN-TEST .WithArgs(browser_context_id) .Then(std::move(callback)); }
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl.h b/content/browser/first_party_sets/first_party_sets_handler_impl.h index 69800147..041d3ac4 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl.h +++ b/content/browser/first_party_sets/first_party_sets_handler_impl.h
@@ -136,9 +136,11 @@ const net::FirstPartySetsContextConfig& config, base::OnceCallback<void(net::FirstPartySetMetadata)> callback) override; - void GetPersistedGlobalSetsForTesting( + void GetPersistedSetsForTesting( const std::string& browser_context_id, - base::OnceCallback<void(absl::optional<net::GlobalFirstPartySets>)> + base::OnceCallback< + void(absl::optional<std::pair<net::GlobalFirstPartySets, + net::FirstPartySetsContextConfig>>)> callback); void HasBrowserContextClearedForTesting( const std::string& browser_context_id,
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc index bdc395f..4141e52e 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc
@@ -197,12 +197,15 @@ run_loop.Run(); } - absl::optional<net::GlobalFirstPartySets> GetPersistedGlobalSetsAndWait( - FirstPartySetsHandlerImpl& handler, - const std::string& browser_context_id) { - base::test::TestFuture<absl::optional<net::GlobalFirstPartySets>> future; - handler.GetPersistedGlobalSetsForTesting(browser_context_id, - future.GetCallback()); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + GetPersistedSetsAndWait(FirstPartySetsHandlerImpl& handler, + const std::string& browser_context_id) { + base::test::TestFuture<absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>>> + future; + handler.GetPersistedSetsForTesting(browser_context_id, + future.GetCallback()); return future.Take(); } @@ -227,9 +230,10 @@ handler(), context, browser_context_id, std::move(context_config)); } - absl::optional<net::GlobalFirstPartySets> GetPersistedGlobalSetsAndWait( - const std::string& browser_context_id) { - return GetPersistedGlobalSetsAndWait(handler(), browser_context_id); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + GetPersistedSetsAndWait(const std::string& browser_context_id) { + return GetPersistedSetsAndWait(handler(), browser_context_id); } absl::optional<bool> HasEntryInBrowserContextsClearedAndWait( @@ -306,9 +310,12 @@ ClearSiteDataOnChangedSetsForContextAndWait( context(), browser_context_id, net::FirstPartySetsContextConfig()); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + persisted = GetPersistedSetsAndWait(browser_context_id); + EXPECT_TRUE(persisted.has_value()); EXPECT_THAT( - GetPersistedGlobalSetsAndWait(browser_context_id) - ->FindEntries({foo, associated}, net::FirstPartySetsContextConfig()), + persisted->first.FindEntries({foo, associated}, persisted->second), IsEmpty()); // Should not be recorded. histogram.ExpectTotalCount(kFirstPartySetsClearSiteDataOutcomeHistogram, 0); @@ -343,9 +350,12 @@ handler, context(), browser_context_id, net::FirstPartySetsContextConfig()); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + persisted = GetPersistedSetsAndWait(handler, browser_context_id); + EXPECT_TRUE(persisted.has_value()); EXPECT_THAT( - GetPersistedGlobalSetsAndWait(handler, browser_context_id) - ->FindEntries({foo, associated}, net::FirstPartySetsContextConfig()), + persisted->first.FindEntries({foo, associated}, persisted->second), UnorderedElementsAre( Pair(foo, net::FirstPartySetEntry(foo, net::SiteType::kPrimary, absl::nullopt)), @@ -392,16 +402,18 @@ ClearSiteDataOnChangedSetsForContextAndWait( handler, context(), browser_context_id, net::FirstPartySetsContextConfig()); - - EXPECT_THAT(GetPersistedGlobalSetsAndWait(handler, browser_context_id) - ->FindEntries({foo, associated}, - net::FirstPartySetsContextConfig()), - UnorderedElementsAre( - Pair(foo, net::FirstPartySetEntry( - foo, net::SiteType::kPrimary, absl::nullopt)), - Pair(associated, - net::FirstPartySetEntry( - foo, net::SiteType::kAssociated, absl::nullopt)))); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + persisted = GetPersistedSetsAndWait(handler, browser_context_id); + EXPECT_TRUE(persisted.has_value()); + EXPECT_THAT( + persisted->first.FindEntries({foo, associated}, persisted->second), + UnorderedElementsAre( + Pair(foo, net::FirstPartySetEntry(foo, net::SiteType::kPrimary, + absl::nullopt)), + Pair(associated, + net::FirstPartySetEntry(foo, net::SiteType::kAssociated, + absl::nullopt)))); EXPECT_THAT( HasEntryInBrowserContextsClearedAndWait(handler, browser_context_id), Optional(true)); @@ -435,16 +447,18 @@ ClearSiteDataOnChangedSetsForContextAndWait( handler, context(), browser_context_id, net::FirstPartySetsContextConfig()); - - EXPECT_THAT(GetPersistedGlobalSetsAndWait(handler, browser_context_id) - ->FindEntries({foo, associated2}, - net::FirstPartySetsContextConfig()), - UnorderedElementsAre( - Pair(foo, net::FirstPartySetEntry( - foo, net::SiteType::kPrimary, absl::nullopt)), - Pair(associated2, - net::FirstPartySetEntry( - foo, net::SiteType::kAssociated, absl::nullopt)))); + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + persisted = GetPersistedSetsAndWait(handler, browser_context_id); + EXPECT_TRUE(persisted.has_value()); + EXPECT_THAT( + persisted->first.FindEntries({foo, associated2}, persisted->second), + UnorderedElementsAre( + Pair(foo, net::FirstPartySetEntry(foo, net::SiteType::kPrimary, + absl::nullopt)), + Pair(associated2, + net::FirstPartySetEntry(foo, net::SiteType::kAssociated, + absl::nullopt)))); EXPECT_THAT( HasEntryInBrowserContextsClearedAndWait(handler, browser_context_id), Optional(true)); @@ -488,7 +502,7 @@ ClearSiteDataOnChangedSetsForContextAndWait( context(), browser_context_id, net::FirstPartySetsContextConfig()); - EXPECT_EQ(GetPersistedGlobalSetsAndWait(browser_context_id), absl::nullopt); + EXPECT_EQ(GetPersistedSetsAndWait(browser_context_id), absl::nullopt); // Should not be recorded. histogram.ExpectTotalCount(kFirstPartySetsClearSiteDataOutcomeHistogram, 0); } @@ -523,9 +537,13 @@ net::SchemefulSite foo(GURL("https://foo.test")); net::SchemefulSite associated(GURL("https://associatedsite.test")); + + absl::optional< + std::pair<net::GlobalFirstPartySets, net::FirstPartySetsContextConfig>> + persisted = GetPersistedSetsAndWait(browser_context_id); + EXPECT_TRUE(persisted.has_value()); EXPECT_THAT( - GetPersistedGlobalSetsAndWait(browser_context_id) - ->FindEntries({foo, associated}, net::FirstPartySetsContextConfig()), + persisted->first.FindEntries({foo, associated}, persisted->second), UnorderedElementsAre( Pair(foo, net::FirstPartySetEntry(foo, net::SiteType::kPrimary, absl::nullopt)),
diff --git a/content/browser/interest_group/interest_group_browsertest.cc b/content/browser/interest_group/interest_group_browsertest.cc index 08d2c9d..6790788 100644 --- a/content/browser/interest_group/interest_group_browsertest.cc +++ b/content/browser/interest_group/interest_group_browsertest.cc
@@ -404,9 +404,13 @@ GetInterestGroup(owner, name); if (result == kSuccess) { - // On success, the user should have joined the interest group, which - // should have been overwritten with the new interest group. - EXPECT_TRUE(final_interest_group); + // On or after success, the user should have joined the interest group, + // which should have been overwritten with the new interest group. + while (!final_interest_group) { + base::RunLoop().RunUntilIdle(); + final_interest_group = GetInterestGroup(owner, name); + } + if (final_interest_group) { if (!initial_interest_group) { EXPECT_EQ(1, @@ -517,9 +521,8 @@ // If `execution_target` is non-null, uses it as the target. Otherwise, uses // shell(). - EvalJsResult UpdateInterestGroupsInJS( - const absl::optional<ToRenderFrameHost> execution_target = - absl::nullopt) { + EvalJsResult UpdateInterestGroupsInJS(const absl::optional<ToRenderFrameHost> + execution_target = absl::nullopt) { return EvalJs(execution_target ? *execution_target : shell(), R"( (function() { try { @@ -566,7 +569,13 @@ std::string result = LeaveInterestGroup(owner, name, execution_target); int final_count = GetJoinCount(owner, name); if (result == kSuccess) { - // On success, the user should no longer be in the interest group. + // On or after success, the user should no longer be in the interest + // group. + while (final_count > 0) { + base::RunLoop().RunUntilIdle(); + final_count = GetJoinCount(owner, name); + } + EXPECT_EQ(0, final_count); } else { // On failure, nothing should have changed. @@ -603,8 +612,8 @@ return interest_groups; } - std::vector<std::pair<url::Origin, std::string>> GetAllInterestGroups() { - std::vector<std::pair<url::Origin, std::string>> interest_groups; + std::vector<blink::InterestGroupKey> GetAllInterestGroups() { + std::vector<blink::InterestGroupKey> interest_groups; for (const auto& owner : GetAllInterestGroupsOwners()) { for (const auto& storage_group : GetInterestGroupsForOwner(owner)) { interest_groups.emplace_back(storage_group.interest_group.owner, @@ -617,12 +626,17 @@ absl::optional<StorageInterestGroup> GetInterestGroup( const url::Origin& owner, const std::string& name) { - for (auto& storage_group : GetInterestGroupsForOwner(owner)) { - if (storage_group.interest_group.name == name) { - return std::move(storage_group); - } - } - return absl::nullopt; + absl::optional<StorageInterestGroup> result; + base::RunLoop run_loop; + manager_->GetInterestGroup( + owner, name, + base::BindLambdaForTesting( + [&run_loop, &result](absl::optional<StorageInterestGroup> group) { + result = std::move(group); + run_loop.Quit(); + })); + run_loop.Run(); + return result; } int GetJoinCount(const url::Origin& owner, const std::string& name) { @@ -907,7 +921,8 @@ } void ExpectNotAllowedToJoinOrUpdateInterestGroup( - const url::Origin& origin, RenderFrameHost* execution_target) { + const url::Origin& origin, + RenderFrameHost* execution_target) { EXPECT_EQ( "NotAllowedError: Failed to execute 'joinAdInterestGroup' on " "'Navigator': Feature join-ad-interest-group is not enabled by " @@ -1493,9 +1508,9 @@ // Check that only the a.test and b.test interest groups were added to // the database. - std::vector<std::pair<url::Origin, std::string>> expected_groups = { + std::vector<blink::InterestGroupKey> expected_groups = { {test_origin_a, "cars"}, {test_origin_b, "trucks"}}; - std::vector<std::pair<url::Origin, std::string>> received_groups; + std::vector<blink::InterestGroupKey> received_groups; received_groups = GetAllInterestGroups(); EXPECT_THAT(received_groups, testing::UnorderedElementsAreArray(expected_groups)); @@ -1786,7 +1801,7 @@ EXPECT_EQ(kSuccess, LeaveInterestGroup(allow_leave_origin, kGroup2)); // The user should still be in kGroup2, but not kGroup1, for both origins. - std::vector<std::pair<url::Origin, std::string>> expected_groups = { + std::vector<blink::InterestGroupKey> expected_groups = { {allow_join_origin, kGroup2}, {allow_leave_origin, kGroup2}}; EXPECT_THAT(GetAllInterestGroups(), testing::UnorderedElementsAreArray(expected_groups)); @@ -4201,7 +4216,7 @@ // The ad should have left the "cars" interest group when the page was shown. auto groups = GetAllInterestGroups(); ASSERT_EQ(1u, groups.size()); - EXPECT_EQ("trucks", groups[0].second); + EXPECT_EQ("trucks", groups[0].name); } // Runs ad auction with fenced frames enabled. The auction should succeed and @@ -6890,28 +6905,27 @@ WaitForInterestGroupsSatisfying( test_origin, - base::BindLambdaForTesting( - [](const std::vector<StorageInterestGroup>& groups) { - if (groups.size() != 1) - return false; - const auto& group = groups[0].interest_group; - return group.name == "cars" && group.priority == 0.0 && - group.execution_mode == blink::InterestGroup::ExecutionMode:: - kGroupedByOriginMode && - group.bidding_url.has_value() && - group.bidding_url->path() == - "/interest_group/new_bidding_logic.js" && - group.trusted_bidding_signals_url.has_value() && - group.trusted_bidding_signals_url->path() == - "/interest_group/new_trusted_bidding_signals_url.json" && - group.trusted_bidding_signals_keys.has_value() && - group.trusted_bidding_signals_keys->size() == 1 && - group.trusted_bidding_signals_keys.value()[0] == "new_key" && - group.ads.has_value() && group.ads->size() == 1 && - group.ads.value()[0].render_url.path() == - "/new_ad_render_url" && - group.ads.value()[0].metadata == "{\"new_a\":\"b\"}"; - })); + base::BindLambdaForTesting([](const std::vector<StorageInterestGroup>& + groups) { + if (groups.size() != 1) + return false; + const auto& group = groups[0].interest_group; + return group.name == "cars" && group.priority == 0.0 && + group.execution_mode == + blink::InterestGroup::ExecutionMode::kGroupedByOriginMode && + group.bidding_url.has_value() && + group.bidding_url->path() == + "/interest_group/new_bidding_logic.js" && + group.trusted_bidding_signals_url.has_value() && + group.trusted_bidding_signals_url->path() == + "/interest_group/new_trusted_bidding_signals_url.json" && + group.trusted_bidding_signals_keys.has_value() && + group.trusted_bidding_signals_keys->size() == 1 && + group.trusted_bidding_signals_keys.value()[0] == "new_key" && + group.ads.has_value() && group.ads->size() == 1 && + group.ads.value()[0].render_url.path() == "/new_ad_render_url" && + group.ads.value()[0].metadata == "{\"new_a\":\"b\"}"; + })); } // Updates can proceed even if the page that started the update isn't running @@ -8228,8 +8242,7 @@ // Features join-ad-interest-group and run-ad-auction can be disabled by HTTP // headers, and they cannot be enabled again by container policy in that case. -IN_PROC_BROWSER_TEST_F(InterestGroupBrowserTest, - FeaturesDisabledByHttpHeader) { +IN_PROC_BROWSER_TEST_F(InterestGroupBrowserTest, FeaturesDisabledByHttpHeader) { GURL test_url = https_server_->GetURL( "a.test", "/interest_group/page-with-fledge-permissions-policy-disabled.html"); @@ -8425,9 +8438,8 @@ // Features join-ad-interest-group and run-ad-auction can be enabled/disabled // separately. -IN_PROC_BROWSER_TEST_F( - InterestGroupRestrictedPermissionsPolicyBrowserTest, - EnableOneOfInterestGroupAPIsAndAuctionAPIForIframe) { +IN_PROC_BROWSER_TEST_F(InterestGroupRestrictedPermissionsPolicyBrowserTest, + EnableOneOfInterestGroupAPIsAndAuctionAPIForIframe) { GURL other_url = https_server_->GetURL("b.test", "/echo"); url::Origin other_origin = url::Origin::Create(other_url); // clang-format off
diff --git a/content/browser/preloading/prerender/prerender_commit_deferring_condition.cc b/content/browser/preloading/prerender/prerender_commit_deferring_condition.cc index 899e658..759cec4 100644 --- a/content/browser/preloading/prerender/prerender_commit_deferring_condition.cc +++ b/content/browser/preloading/prerender/prerender_commit_deferring_condition.cc
@@ -103,9 +103,11 @@ // PrerenderNavigationThrottle disallows another navigation after the // initial commit, there should not be another navigation starting. // - // The old navigation might not yet have cleaned up yet, so try that - // first. - prerender_frame_tree_node->render_manager()->MaybeCleanUpNavigation( + // There might be an unused speculative RenderFrameHost at this point, so try + // discarding that first. + // TODO(https://crbug.com/1220337): We can probably remove this now that + // prerender activations are synchronous. + prerender_frame_tree_node->render_manager()->DiscardSpeculativeRFHIfUnused( NavigationDiscardReason::kCancelled); DCHECK(!prerender_frame_tree_node->HasNavigation());
diff --git a/content/browser/renderer_host/accessibility_object_lifetime_win_browsertest.cc b/content/browser/renderer_host/accessibility_object_lifetime_win_browsertest.cc index 3be39559..d4af7b0 100644 --- a/content/browser/renderer_host/accessibility_object_lifetime_win_browsertest.cc +++ b/content/browser/renderer_host/accessibility_object_lifetime_win_browsertest.cc
@@ -59,7 +59,7 @@ IN_PROC_BROWSER_TEST_F(AccessibilityObjectLifetimeWinBrowserTest, RootDoesNotLeak) { - testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.mode()); + testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.flags()); EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); @@ -173,7 +173,7 @@ IN_PROC_BROWSER_TEST_F(AccessibilityObjectLifetimeUiaWinBrowserTest, RootDoesNotLeak) { - testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.mode()); + testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.flags()); EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
diff --git a/content/browser/renderer_host/accessibility_tree_linkage_win_browsertest.cc b/content/browser/renderer_host/accessibility_tree_linkage_win_browsertest.cc index 8205dde..12e7e84a 100644 --- a/content/browser/renderer_host/accessibility_tree_linkage_win_browsertest.cc +++ b/content/browser/renderer_host/accessibility_tree_linkage_win_browsertest.cc
@@ -73,7 +73,7 @@ }; IN_PROC_BROWSER_TEST_P(AccessibilityTreeLinkageWinBrowserTest, Linkage) { - testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.mode()); + testing::ScopedContentAXModeSetter ax_mode_setter(ui::kAXModeBasic.flags()); EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
diff --git a/content/browser/renderer_host/frame_tree.cc b/content/browser/renderer_host/frame_tree.cc index 38509a0..bea98b0 100644 --- a/content/browser/renderer_host/frame_tree.cc +++ b/content/browser/renderer_host/frame_tree.cc
@@ -888,7 +888,8 @@ // destroyed. root_manager->current_frame_host()->RenderFrameDeleted(); - root_manager->current_frame_host()->ResetNavigationRequests(); + root_manager->current_frame_host()->ResetOwnedNavigationRequests( + NavigationDiscardReason::kWillRemoveFrame); // Do not update state as the FrameTree::Delegate (possibly a WebContents) is // being destroyed.
diff --git a/content/browser/renderer_host/frame_tree_node.cc b/content/browser/renderer_host/frame_tree_node.cc index e5b6f899..0754cd3 100644 --- a/content/browser/renderer_host/frame_tree_node.cc +++ b/content/browser/renderer_host/frame_tree_node.cc
@@ -541,7 +541,8 @@ bool was_previously_loading = frame_tree()->LoadingTree()->IsLoadingIncludingInnerFrameTrees(); - // There's no need to reset the state: there's still an ongoing load, and the + // Reset the previous NavigationRequest owned by `this`. However, there's no + // need to reset the state: there's still an ongoing load, and the // RenderFrameHostManager will take care of updates to the speculative // RenderFrameHost in DidCreateNavigationRequest below. if (was_previously_loading) { @@ -574,7 +575,11 @@ // The RenderFrameHostManager should clean up any speculative RenderFrameHost // it created for the navigation. Also register that the load stopped. DidStopLoading(); - render_manager_.CleanUpNavigation(reason); + // TODO(https://crbug.com/1220337): This might accidentally delete an + // unrelated speculative RenderFrameHost that is pending commit. Check if the + // speculative RenderFrameHost is really associated with the deleted + // NavigationRequest first before deleting. + render_manager_.DiscardSpeculativeRFHIfUnused(reason); } void FrameTreeNode::ResetNavigationRequestButKeepState() {
diff --git a/content/browser/renderer_host/frame_tree_node.h b/content/browser/renderer_host/frame_tree_node.h index 5f502ae2..078436b2 100644 --- a/content/browser/renderer_host/frame_tree_node.h +++ b/content/browser/renderer_host/frame_tree_node.h
@@ -317,11 +317,14 @@ void CreatedNavigationRequest( std::unique_ptr<NavigationRequest> navigation_request); - // Resets the current navigation request and any state created by it, - // including the speculative RenderFrameHost. + // Resets the navigation request owned by `this` (which shouldn't have reached + // the "pending commit" stage yet) and any state created by it, including the + // speculative RenderFrameHost. Note that this does not affect navigations + // that have reached the "pending commit" stage, which are owned by their + // corresponding RenderFrameHosts instead. void ResetNavigationRequest(NavigationDiscardReason reason); - // Resets the current navigation request, but keeping state created by the + // Similar to `ResetNavigationRequest()`, but keeps the state created by the // NavigationRequest (e.g. speculative RenderFrameHost, loading state). void ResetNavigationRequestButKeepState();
diff --git a/content/browser/renderer_host/navigation_discard_reason.h b/content/browser/renderer_host/navigation_discard_reason.h index f11e61a..efb5885 100644 --- a/content/browser/renderer_host/navigation_discard_reason.h +++ b/content/browser/renderer_host/navigation_discard_reason.h
@@ -5,9 +5,9 @@ #ifndef CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_DISCARD_REASON_H_ #define CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_DISCARD_REASON_H_ -// Used to annotate the reason for calling into CleanUpNavigation() / -// ResetNavigationRequest(). Purely informational for now, but in the future, -// intended to serve as a signal for how a caller of the aforementioned +// Used to annotate the reason for calling into methods that delete speculative +// RenderFrameHosts or ongoing NavigationRequests. Purely informational for now, +// but in the future, intended to serve as a signal for how a caller of the // functions should handle cases when the speculative RenderFrameHost cannot be // promptly discarded. See https://crbug.com/1220337 for more info. enum class NavigationDiscardReason { @@ -26,6 +26,11 @@ kCommittedNavigation, // The render process is gone, typically due to a crash. kRenderProcessGone, + // The RenderFrameHost containing the NavigationRequest is destructed. + // This is only used by the RenderFrameHost destructor, and typically other + // navigation cancellations will cancel the navigations on the RFH separately + // with a more specific reason before destructing the RenderFrameHost. + kRenderFrameHostDestruction, }; #endif // CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_DISCARD_REASON_H_
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index 8c193c6e..1b0c65f7 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -5884,13 +5884,8 @@ // variables to avoid a use-after-free. FrameTreeNode* frame_tree_node = frame_tree_node_; render_frame_host_->NavigationRequestCancelled(this); - // Ensure that the speculative RFH, if any, is also cleaned up. In theory, - // `ResetNavigationRequest()` should handle this; however, it early-returns - // if there is no navigation request associated with the FrameTreeNode. - // Changing it to no longer early return breaks a bunch of other code that - // runs in `CommitPendingIfNecessary()` that expects `DidStopLoading()` - // won't be called if `FrameTreeNode::navigation_request()` is null... - frame_tree_node->render_manager()->MaybeCleanUpNavigation( + // Ensure that the speculative RFH, if any, is also cleaned up. + frame_tree_node->render_manager()->DiscardSpeculativeRFHIfUnused( NavigationDiscardReason::kCancelled); }
diff --git a/content/browser/renderer_host/navigator.h b/content/browser/renderer_host/navigator.h index d355013c..0708ad9 100644 --- a/content/browser/renderer_host/navigator.h +++ b/content/browser/renderer_host/navigator.h
@@ -190,7 +190,10 @@ void RestartNavigationAsCrossDocument( std::unique_ptr<NavigationRequest> navigation_request); - // Cancel a NavigationRequest for |frame_tree_node|. + // Cancels the NavigationRequest owned by |frame_tree_node|. Note that this + // will only cancel NavigationRequests that haven't reached the "pending + // commit" stage yet, as after that the NavigationRequests will no longer be + // owned by the FrameTreeNode. void CancelNavigation(FrameTreeNode* frame_tree_node, NavigationDiscardReason reason);
diff --git a/content/browser/renderer_host/render_frame_host_android.cc b/content/browser/renderer_host/render_frame_host_android.cc index 23df34c..d5fa543 100644 --- a/content/browser/renderer_host/render_frame_host_android.cc +++ b/content/browser/renderer_host/render_frame_host_android.cc
@@ -240,12 +240,4 @@ return static_cast<jint>(render_frame_host_->GetLifecycleState()); } -void RenderFrameHostAndroid::InsertVisualStateCallback( - JNIEnv* env, - const JavaParamRef<jobject>& jcallback) { - render_frame_host()->InsertVisualStateCallback( - base::BindOnce(&base::android::RunBooleanCallbackAndroid, - base::android::ScopedJavaGlobalRef<jobject>(jcallback))); -} - } // namespace content
diff --git a/content/browser/renderer_host/render_frame_host_android.h b/content/browser/renderer_host/render_frame_host_android.h index d2435115..d2a7b9b 100644 --- a/content/browser/renderer_host/render_frame_host_android.h +++ b/content/browser/renderer_host/render_frame_host_android.h
@@ -100,10 +100,6 @@ jint GetLifecycleState(JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; - void InsertVisualStateCallback( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& jcallback); - RenderFrameHostImpl* render_frame_host() const { return render_frame_host_; } private:
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 149786f9..9f12d2a 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -1609,7 +1609,8 @@ // Destroying NavigationRequests may call into delegates/observers, // so we do it early while |this| object is still in a sane state. - ResetNavigationRequests(); + ResetOwnedNavigationRequests( + NavigationDiscardReason::kRenderFrameHostDestruction); // Release the WebUI instances before all else as the WebUI may accesses the // RenderFrameHost during cleanup. @@ -3004,7 +3005,7 @@ owned_render_widget_host_->RendererExited(); // The renderer process is gone, so this frame can no longer be loading. - ResetNavigationRequests(); + ResetOwnedNavigationRequests(NavigationDiscardReason::kRenderProcessGone); ResetLoadingState(); // Any future UpdateState or UpdateTitle messages from this or a recreated @@ -4171,8 +4172,8 @@ // and the speculative / pending commit RenderFrameHost (which is still // strongly owned by the RenderFrameHostManager via unique_ptr) will be torn // down then. If we do proceed, this ends up with a use-after-free, since - // StartPendingDeletionOnSubtree() will ResetNavigationsForPendingDeletion(), - // which deletes `this`. + // StartPendingDeletionOnSubtree() will call + // ResetAllNavigationsInSubtreeForPendingDeletion(), which deletes `this`. if (lifecycle_state() == LifecycleStateImpl::kSpeculative || lifecycle_state() == LifecycleStateImpl::kPendingCommit) { return; @@ -4570,7 +4571,16 @@ : request->second.get(); } -void RenderFrameHostImpl::ResetNavigationRequests() { +void RenderFrameHostImpl::ResetOwnedNavigationRequests( + NavigationDiscardReason reason) { + if (base::FeatureList::IsEnabled(kQueueNavigationsWhileWaitingForCommit)) { + // With navigation queueing, pending commit navigations shouldn't get + // canceled, unless the FrameTreeNode, RenderFrameHost, or renderer process + // is gone/will be gone soon. + CHECK(reason == NavigationDiscardReason::kRenderProcessGone || + reason == NavigationDiscardReason::kWillRemoveFrame || + reason == NavigationDiscardReason::kRenderFrameHostDestruction); + } // Move the NavigationRequests to new maps first before deleting them. This // avoids issues if a re-entrant call is made when a NavigationRequest is // being deleted (e.g., if the process goes away as the tab is closing). @@ -8473,7 +8483,7 @@ void RenderFrameHostImpl::StartPendingDeletionOnSubtree() { DCHECK(IsPendingDeletion()); - ResetNavigationsForPendingDeletion(); + ResetAllNavigationsInSubtreeForPendingDeletion(); for (std::unique_ptr<FrameTreeNode>& child_frame : children_) { for (FrameTreeNode* node : frame_tree()->SubtreeNodes(child_frame.get())) { @@ -8556,10 +8566,12 @@ } } -void RenderFrameHostImpl::ResetNavigationsForPendingDeletion() { - for (auto& child : children_) - child->current_frame_host()->ResetNavigationsForPendingDeletion(); - ResetNavigationRequests(); +void RenderFrameHostImpl::ResetAllNavigationsInSubtreeForPendingDeletion() { + for (auto& child : children_) { + child->current_frame_host() + ->ResetAllNavigationsInSubtreeForPendingDeletion(); + } + ResetOwnedNavigationRequests(NavigationDiscardReason::kWillRemoveFrame); // TODO(https://crbug.com/1220337): This has an interesting interaction with // the experimental implementations of navigation queueing: if the speculative // RenderFrameHost is in pending commit when a new navigation tries to start, @@ -8569,7 +8581,7 @@ // clobbers the navigation request that was specifically queueing... frame_tree_node_->ResetNavigationRequest( NavigationDiscardReason::kWillRemoveFrame); - frame_tree_node_->render_manager()->CleanUpNavigation( + frame_tree_node_->render_manager()->DiscardSpeculativeRFH( NavigationDiscardReason::kWillRemoveFrame); } @@ -9405,14 +9417,14 @@ GetRemoteAssociatedInterfaces()->GetInterface(&render_accessibility_); DCHECK(render_accessibility_); } - render_accessibility_->SetMode(ax_mode.mode()); + render_accessibility_->SetMode(ax_mode.flags()); } else { // Resetting the Remote signals the renderer to shutdown accessibility // in the renderer. render_accessibility_.reset(); } - if (!ax_mode.has_mode(ui::kAXModeBasic.mode()) && + if (!ax_mode.has_mode(ui::kAXModeBasic.flags()) && browser_accessibility_manager_) { // Missing either kWebContents and kNativeAPIs, so // BrowserAccessibilityManager is no longer necessary. @@ -9428,7 +9440,7 @@ size_t max_nodes, const base::TimeDelta& timeout) { auto params = mojom::SnapshotAccessibilityTreeParams::New(); - params->ax_mode = ax_mode.mode(); + params->ax_mode = ax_mode.flags(); params->exclude_offscreen = exclude_offscreen; params->max_nodes = max_nodes; params->timeout = timeout;
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 7b3be29..1e423b2 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -54,6 +54,7 @@ #include "content/browser/renderer_host/keep_alive_handle_factory.h" #include "content/browser/renderer_host/media/render_frame_audio_input_stream_factory.h" #include "content/browser/renderer_host/media/render_frame_audio_output_stream_factory.h" +#include "content/browser/renderer_host/navigation_discard_reason.h" #include "content/browser/renderer_host/page_impl.h" #include "content/browser/renderer_host/pending_beacon_host.h" #include "content/browser/renderer_host/policy_container_host.h" @@ -988,8 +989,16 @@ NavigationRequest* GetSameDocumentNavigationRequest( const base::UnguessableToken& token); - // Resets the NavigationRequests stored in this RenderFrameHost. - void ResetNavigationRequests(); + // Resets the NavigationRequests stored in this RenderFrameHost, which are all + // "pending commit". Note this won't affect navigations that are "pending + // commit" but not owned by this RenderFrameHost, and any navigation that + // hasn't reached the "pending commit" stage yet, which would still be owned + // by the FrameTreeNode. + // TODO(https://crbug.com/1220337): Don't allow this to be called when there + // are pending cross-document navigations except for FrameTreeNode detach, + // RFH destruction, or when the renderer process is gone, so that we don't + // have to "undo" the commit that already happens in the renderer. + void ResetOwnedNavigationRequests(NavigationDiscardReason reason); // Called when a navigation is ready to commit in this // RenderFrameHost. Transfers ownership of the NavigationRequest associated @@ -3430,10 +3439,11 @@ // this frame's subtree. void PendingDeletionCheckCompletedOnSubtree(); - // In this frame and its children, removes every: - // - NavigationRequest. - // - Speculative RenderFrameHost. - void ResetNavigationsForPendingDeletion(); + // In this RenderFrameHost and its children, removes every: + // - Non-pending commit NavigationRequest owned by the FrameTreeNode + // - Pending commit NavigationRequest owned by the RenderFrameHost + // - Speculative RenderFrameHost (and its pending commit NavigationRequests). + void ResetAllNavigationsInSubtreeForPendingDeletion(); // Called on an unloading frame when its unload timeout is reached. This // immediately deletes the RenderFrameHost.
diff --git a/content/browser/renderer_host/render_frame_host_manager.cc b/content/browser/renderer_host/render_frame_host_manager.cc index e41f24fe2..27556a1 100644 --- a/content/browser/renderer_host/render_frame_host_manager.cc +++ b/content/browser/renderer_host/render_frame_host_manager.cc
@@ -35,6 +35,7 @@ #include "content/browser/renderer_host/frame_tree.h" #include "content/browser/renderer_host/frame_tree_node.h" #include "content/browser/renderer_host/navigation_controller_impl.h" +#include "content/browser/renderer_host/navigation_discard_reason.h" #include "content/browser/renderer_host/navigation_entry_impl.h" #include "content/browser/renderer_host/navigation_request.h" #include "content/browser/renderer_host/navigator.h" @@ -573,9 +574,9 @@ // If we're about to close the tab and there's a speculative RFH, cancel it. // Otherwise, if the navigation in the speculative RFH completes before the // close in the current RFH, we'll lose the tab close. - if (speculative_render_frame_host_) - CleanUpNavigation(NavigationDiscardReason::kWillRemoveFrame); - + if (speculative_render_frame_host_) { + DiscardSpeculativeRFH(NavigationDiscardReason::kWillRemoveFrame); + } render_frame_host_->render_view_host()->ClosePage(); } } @@ -662,7 +663,9 @@ was_caused_by_user_gesture) { frame_tree_node_->ResetNavigationRequest( NavigationDiscardReason::kCommittedNavigation); - CleanUpNavigation(NavigationDiscardReason::kCommittedNavigation); + // TODO(https://crbug.com/1220337): Don't discard the speculative + // RenderFrameHost if it's pending commit. + DiscardSpeculativeRFH(NavigationDiscardReason::kCommittedNavigation); } if (render_frame_host_->is_local_root() && render_frame_host_->GetView()) { @@ -850,7 +853,13 @@ // Reset any NavigationRequest in the RenderFrameHost. An unloaded // RenderFrameHost should not be trying to commit a navigation. - old_render_frame_host->ResetNavigationRequests(); + // TODO(https://crbug.com/1220337): Ensure that there are no pending commit + // cross-document NavigationRequests at this point. With navigation queuing, + // this will be guaranteed because there will be only 1 pending commit + // navigation at a time, which will be the navigation in the speculative + // RenderFrameHost that replaced `old_render_frame_host`. + old_render_frame_host->ResetOwnedNavigationRequests( + NavigationDiscardReason::kCommittedNavigation); // Sends out all pending beacons on navigation away. // Whether or not `old_render_frame_host` is put into BackForwardCache is not @@ -1094,7 +1103,9 @@ // Cleanup existing pending RenderFrameHost. This corresponds to what is // done inside GetFrameHostForNavigation(request), but we avoid calling that // method for navigations which will be forced into the current document. - CleanUpNavigation(NavigationDiscardReason::kNewNavigation); + // TODO(https://crbug.com/1220337): Don't delete the speculative + // RenderFrameHost when it is pending commit. + DiscardSpeculativeRFH(NavigationDiscardReason::kNewNavigation); request->set_associated_rfh_type( NavigationRequest::AssociatedRenderFrameHostType::CURRENT); } else { @@ -1211,8 +1222,10 @@ // navigation (currently twice, on request and when it's about to commit in // the renderer). In the follow up calls an existing pending WebUI should // not be recreated if the URL didn't change. So instead of calling - // CleanUpNavigation just discard the speculative RenderFrameHost if one + // DiscardSpeculativeRFH just discard the speculative RenderFrameHost if one // exists. + // TODO(https://crbug.com/1220337): Don't delete the speculative + // RenderFrameHost when it is pending commit. if (speculative_render_frame_host_) { DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost( NavigationDiscardReason::kNewNavigation)); @@ -1276,7 +1289,9 @@ // If a previous speculative RenderFrameHost didn't exist or if its // SiteInstance differs from the one for the current URL, a new one needs // to be created. - CleanUpNavigation(NavigationDiscardReason::kNewNavigation); + // TODO(https://crbug.com/1220337): Don't delete the speculative + // RenderFrameHost when it is pending commit. + DiscardSpeculativeRFH(NavigationDiscardReason::kNewNavigation); bool success = CreateSpeculativeRenderFrameHost( current_site_instance, dest_site_instance.get(), recovering_without_early_commit); @@ -1427,7 +1442,7 @@ return navigation_rfh; } -void RenderFrameHostManager::MaybeCleanUpNavigation( +void RenderFrameHostManager::DiscardSpeculativeRFHIfUnused( NavigationDiscardReason reason) { // This is called when a renderer aborts a NavigationRequest // that was in the READY_TO_COMMIT state. The caller has already @@ -1435,7 +1450,7 @@ // which may or may not have been the speculative one. Either way, // if there are no remaining NavigationRequests associated with // |speculative_render_frame_host_|, then it is safe to call - // CleanUpNavigation() to discard |speculative_render_frame_host_|. + // DiscardSpeculativeRFH() to discard |speculative_render_frame_host_|. if (!speculative_render_frame_host_ || speculative_render_frame_host_->HasPendingCommitNavigation()) { return; @@ -1447,11 +1462,12 @@ NavigationRequest::AssociatedRenderFrameHostType::SPECULATIVE) { return; } - CleanUpNavigation(reason); + DiscardSpeculativeRFH(reason); } -void RenderFrameHostManager::CleanUpNavigation(NavigationDiscardReason reason) { - TRACE_EVENT("navigation", "RenderFrameHostManager::CleanUpNavigation", +void RenderFrameHostManager::DiscardSpeculativeRFH( + NavigationDiscardReason reason) { + TRACE_EVENT("navigation", "RenderFrameHostManager::DiscardSpeculativeRFH", ChromeTrackEvent::kFrameTreeNodeInfo, *frame_tree_node_); if (speculative_render_frame_host_) { bool was_loading = speculative_render_frame_host_->is_loading(); @@ -1479,7 +1495,13 @@ ChromeTrackEvent::kFrameTreeNodeInfo, *frame_tree_node_); if (base::FeatureList::IsEnabled(kQueueNavigationsWhileWaitingForCommit)) { - CHECK(reason != NavigationDiscardReason::kNewNavigation); + if (HasPendingCommitForCrossDocumentNavigation()) { + // With navigation queueing, pending commit navigations in speculative + // RenderFrameHosts shouldn't get deleted, unless the FrameTreeNode or + // renderer process is gone/will be gone soon. + CHECK(reason == NavigationDiscardReason::kRenderProcessGone || + reason == NavigationDiscardReason::kWillRemoveFrame); + } } speculative_render_frame_host_->GetProcess()->RemovePendingView(); @@ -1619,6 +1641,9 @@ // TODO(nasko, clamy): This should just clean up the speculative RFH // without canceling the request. See https://crbug.com/636119. if (frame_tree_node_->navigation_request()) { + // TODO(https://crbug.com/636119): This might cancel an unrelated + // NavigationRequest. Maybe check if the navigation request uses the + // speculative RFH first? frame_tree_node_->navigation_request()->set_net_error(net::ERR_ABORTED); frame_tree_node_->ResetNavigationRequest( NavigationDiscardReason::kRenderProcessGone); @@ -1627,7 +1652,7 @@ // TransferNavigationRequestOwnership has already been called then the // FrameTreeNode no longer owns the NavigationRequest and we need to clean // up the speculative RenderFrameHost. - CleanUpNavigation(NavigationDiscardReason::kRenderProcessGone); + DiscardSpeculativeRFH(NavigationDiscardReason::kRenderProcessGone); } } } @@ -4244,7 +4269,12 @@ DCHECK(is_attaching_inner_delegate()); // Remove all navigations and any speculative frames which might interfere // with the loading state. - current_frame_host()->ResetNavigationRequests(); + // TODO(https://crbug.com/1220337): Ensure that there are no pending commit + // cross-document NavigationRequests at this point. Maybe wait for all + // navigations to finish from PrepareForInnerDelegateAttach() before + // continuing instead of cancelling the navigations from here? + current_frame_host()->ResetOwnedNavigationRequests( + NavigationDiscardReason::kNewNavigation); current_frame_host()->ResetLoadingState(); // Remove any speculative frames first and ongoing navigation state. This // should reset the loading state for good. @@ -4253,7 +4283,7 @@ if (speculative_render_frame_host_) { // The FrameTreeNode::ResetNavigationRequest call above may not have cleaned // up the speculative RenderFrameHost if the NavigationRequest had already - // been transferred to RenderFrameHost. Ensure it is cleaned up now. + // been transferred to RenderFrameHost. Ensure it is cleaned up now. DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost( NavigationDiscardReason::kNewNavigation)); }
diff --git a/content/browser/renderer_host/render_frame_host_manager.h b/content/browser/renderer_host/render_frame_host_manager.h index 99cf2ea..9617c47 100644 --- a/content/browser/renderer_host/render_frame_host_manager.h +++ b/content/browser/renderer_host/render_frame_host_manager.h
@@ -399,12 +399,18 @@ RenderFrameHostImpl* GetFrameHostForNavigation(NavigationRequest* request, std::string* reason = nullptr); - // Clean up any state for any ongoing navigation. - void CleanUpNavigation(NavigationDiscardReason reason); + // Discards `speculative_render_frame_host_` if it exists, even if there are + // NavigationRequests associated with it, including pending commit + // navigations. + // TODO(https://crbug.com/1220337): Don't allow this to be called when there + // are pending commit cross-document navigations except for FrameTreeNode + // detach or when the renderer process is gone, so that we don't have to + // "undo" the commit that already happens in the renderer. + void DiscardSpeculativeRFH(NavigationDiscardReason reason); // Determines whether any active navigations are associated with - // |speculative_render_frame_host_| and if not, discards it. - void MaybeCleanUpNavigation(NavigationDiscardReason reason); + // `speculative_render_frame_host_` and if not, discards it. + void DiscardSpeculativeRFHIfUnused(NavigationDiscardReason reason); // Clears the speculative RFH when a navigation is cancelled (for example, by // being replaced by a new navigation), returning ownership of the
diff --git a/content/browser/renderer_host/render_widget_host_delegate.cc b/content/browser/renderer_host/render_widget_host_delegate.cc index 0c6a78a..6858566 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.cc +++ b/content/browser/renderer_host/render_widget_host_delegate.cc
@@ -149,8 +149,4 @@ return false; } -int RenderWidgetHostDelegate::GetVirtualKeyboardResizeHeight() { - return 0; -} - } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_delegate.h b/content/browser/renderer_host/render_widget_host_delegate.h index 780b2014..5f1eea55 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.h +++ b/content/browser/renderer_host/render_widget_host_delegate.h
@@ -314,11 +314,6 @@ const gfx::Rect& initial_anchor_rect_in_dips) { } - // Returns the amount that this view has been resized by a showing virtual - // keyboard or 0 if the virtual keyboard is hidden or in a mode that doesn't - // resize the view. - virtual int GetVirtualKeyboardResizeHeight(); - protected: virtual ~RenderWidgetHostDelegate() {} };
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 0e38398..5a5a4f6 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -1094,8 +1094,6 @@ gfx::Rect(view_->GetCompositorViewportPixelSize()); visual_properties.window_controls_overlay_rect = delegate_->GetWindowsControlsOverlayRect(); - visual_properties.virtual_keyboard_resize_height_physical_px = - delegate_->GetVirtualKeyboardResizeHeight(); } else { visual_properties.compositor_viewport_pixel_rect = properties_from_parent_local_root_.compositor_viewport;
diff --git a/content/browser/resources/attribution_reporting/attribution_internals.html b/content/browser/resources/attribution_reporting/attribution_internals.html index 9c91bb4..f203e187 100644 --- a/content/browser/resources/attribution_reporting/attribution_internals.html +++ b/content/browser/resources/attribution_reporting/attribution_internals.html
@@ -29,6 +29,7 @@ <div id="event-level-reports-tab" slot="tab">Event-Level Reports</div> <div id="aggregatable-reports-tab" slot="tab">Aggregatable Reports</div> <div id="logs-tab" slot="tab">Logs</div> + <div id="debug-reports-tab" slot="tab">Verbose Debug Reports</div> <div slot="panel"> <h2>Sources</h2> <div class="content"> @@ -72,6 +73,13 @@ </attribution-internals-table> </div> </div> + <div slot="panel"> + <h2>Verbose Debug Reports</h2> + <div class="content"> + <attribution-internals-table id="debugReportTable"> + </attribution-internals-table> + </div> + </div> </cr-tab-box> </main> </body>
diff --git a/content/browser/resources/attribution_reporting/attribution_internals.ts b/content/browser/resources/attribution_reporting/attribution_internals.ts index 3e8f19e..12421994 100644 --- a/content/browser/resources/attribution_reporting/attribution_internals.ts +++ b/content/browser/resources/attribution_reporting/attribution_internals.ts
@@ -9,7 +9,7 @@ import {getTrustedHTML} from 'chrome://resources/js/static_types.js'; import {Origin} from 'chrome://resources/mojo/url/mojom/origin.mojom-webui.js'; -import {ClearedDebugKey, ClearedDebugKey_Type, FailedSourceRegistration, Handler as AttributionInternalsHandler, HandlerRemote as AttributionInternalsHandlerRemote, ObserverInterface, ObserverReceiver, ReportID, WebUIReport, WebUISource, WebUISource_Attributability, WebUITrigger, WebUITrigger_Status} from './attribution_internals.mojom-webui.js'; +import {ClearedDebugKey, ClearedDebugKey_Type, FailedSourceRegistration, Handler as AttributionInternalsHandler, HandlerRemote as AttributionInternalsHandlerRemote, ObserverInterface, ObserverReceiver, ReportID, WebUIDebugReport, WebUIReport, WebUISource, WebUISource_Attributability, WebUITrigger, WebUITrigger_Status} from './attribution_internals.mojom-webui.js'; import {AttributionInternalsTableElement} from './attribution_internals_table.js'; import {ReportType, SourceType} from './attribution_reporting.mojom-webui.js'; import {SourceRegistrationError} from './source_registration_error.mojom-webui.js'; @@ -711,6 +711,69 @@ } } +class DebugReport { + body: string; + url: string; + time: Date; + status: string; + + constructor(mojo: WebUIDebugReport) { + this.body = mojo.body; + this.url = mojo.url.url; + this.time = new Date(mojo.time); + + if (mojo.status.httpResponseCode !== undefined) { + this.status = `HTTP ${mojo.status.httpResponseCode}`; + } else if (mojo.status.networkError !== undefined) { + this.status = `Network error: ${mojo.status.networkError}`; + } else { + throw new Error('invalid DebugReportStatus union'); + } + } +} + +class DebugReportTableModel extends TableModel<DebugReport> { + debugReports: DebugReport[] = []; + + constructor() { + super(); + + this.cols = [ + new DateColumn<DebugReport>('Time', (e) => e.time), + new ValueColumn<DebugReport, string>('URL', (e) => e.url), + new ValueColumn<DebugReport, string>('Status', (e) => e.status), + new CodeColumn<DebugReport>('Body', (e) => e.body), + ]; + + // Sort by report time by default. + this.sortIdx = 0; + + this.emptyRowText = 'No verbose debug reports.'; + } + + // TODO(apaseltiner): Style error rows like `ReportTableModel` + + override getRows() { + return this.debugReports; + } + + add(report: DebugReport) { + // Prevent the page from consuming ever more memory if the user leaves the + // page open for a long time. + if (this.debugReports.length >= 1000) { + this.debugReports = []; + } + + this.debugReports.push(report); + this.notifyRowsChanged(); + } + + clear() { + this.debugReports = []; + this.notifyRowsChanged(); + } +} + abstract class Log { readonly timestamp: Date; readonly reportTo: string; @@ -922,6 +985,8 @@ let aggregatableAttributionReportTableModel: AggregatableAttributionReportTableModel|null = null; +let debugReportTableModel: DebugReportTableModel|null = null; + /** * Converts a mojo origin into a user-readable string, omitting default ports. * @param origin Origin to convert @@ -1105,6 +1170,8 @@ aggregatableAttributionReportTableModel.clear(); assert(logTableModel); logTableModel.clear(); + assert(debugReportTableModel); + debugReportTableModel.clear(); assert(pageHandler); pageHandler.clearStorage(); } @@ -1139,6 +1206,11 @@ addSentOrDroppedReport(mojo); } + onDebugReportSent(mojo: WebUIDebugReport) { + assert(debugReportTableModel); + debugReportTableModel.add(new DebugReport(mojo)); + } + onReportDropped(mojo: WebUIReport) { addSentOrDroppedReport(mojo); } @@ -1193,6 +1265,7 @@ new AggregatableAttributionReportTableModel( showDebugAggregatableReports, sendAggregatableReports); logTableModel = new LogTableModel(); + debugReportTableModel = new DebugReportTableModel(); const tabBox = document.querySelector('cr-tab-box'); assert(tabBox); @@ -1213,6 +1286,9 @@ document.querySelector<HTMLElement>('#aggregatable-reports-tab')); installUnreadIndicator( logTableModel, document.querySelector<HTMLElement>('#logs-tab')); + installUnreadIndicator( + debugReportTableModel, + document.querySelector<HTMLElement>('#debug-reports-tab')); const refresh = document.querySelector('#refresh'); assert(refresh); @@ -1226,27 +1302,37 @@ '#sourceTable'); assert(sourceTable); sourceTable.setModel(sourceTableModel!); + const triggerTable = document.querySelector<AttributionInternalsTableElement<Trigger>>( '#triggerTable'); assert(triggerTable); triggerTable.setModel(triggerTableModel!); + const reportTable = document.querySelector<AttributionInternalsTableElement<Report>>( '#reportTable'); assert(reportTable); reportTable.setModel(eventLevelReportTableModel!); + const aggregatableReportTable = document.querySelector<AttributionInternalsTableElement<Report>>( '#aggregatableReportTable'); assert(aggregatableReportTable); aggregatableReportTable.setModel(aggregatableAttributionReportTableModel!); + const logTable = document.querySelector<AttributionInternalsTableElement<Log>>( '#logTable'); assert(logTable); logTable.setModel(logTableModel); + const debugReportTable = + document.querySelector<AttributionInternalsTableElement<DebugReport>>( + '#debugReportTable'); + assert(debugReportTable); + debugReportTable.setModel(debugReportTableModel); + tabBox.hidden = false; const receiver = new ObserverReceiver(new Observer());
diff --git a/content/browser/speech/tts_controller_impl.cc b/content/browser/speech/tts_controller_impl.cc index 0afa6b83..dd93675 100644 --- a/content/browser/speech/tts_controller_impl.cc +++ b/content/browser/speech/tts_controller_impl.cc
@@ -67,15 +67,7 @@ // VoiceData // -VoiceData::VoiceData() - : remote(false), - native(false) -#if BUILDFLAG(IS_CHROMEOS_ASH) - , - from_crosapi(false) -#endif -{ -} +VoiceData::VoiceData() : remote(false), native(false) {} VoiceData::VoiceData(const VoiceData& other) = default; @@ -235,9 +227,19 @@ } void TtsControllerImpl::StopCurrentUtterance() { + bool spoken_by_remote_engine = false; + if (current_utterance_ && !current_utterance_->GetEngineId().empty()) { + TtsUtteranceImpl* utterance_impl = + AsUtteranceImpl(current_utterance_.get()); + spoken_by_remote_engine = utterance_impl->spoken_by_remote_engine(); + } + if (engine_delegate_ && current_utterance_ && - !current_utterance_->GetEngineId().empty()) { + !current_utterance_->GetEngineId().empty() && !spoken_by_remote_engine) { engine_delegate_->Stop(current_utterance_.get()); + } else if (current_utterance_ && !current_utterance_->GetEngineId().empty() && + spoken_by_remote_engine && remote_engine_delegate_) { + remote_engine_delegate_->Stop(current_utterance_.get()); } else if (TtsPlatformReady()) { GetTtsPlatform()->ClearError(); GetTtsPlatform()->StopSpeaking(); @@ -388,7 +390,6 @@ tts_platform->FinalizeVoiceOrdering(*out_voices); -#if BUILDFLAG(IS_CHROMEOS_ASH) // Append lacros voices after ash voices. if (remote_engine_delegate_) { std::vector<VoiceData> crosapi_voices; @@ -397,7 +398,6 @@ std::make_move_iterator(crosapi_voices.begin()), std::make_move_iterator(crosapi_voices.end())); } -#endif if (!allow_remote_voices_) { auto it = @@ -585,8 +585,16 @@ DCHECK(!voice.engine_id.empty()); SetCurrentUtterance(std::move(utterance)); current_utterance_->SetEngineId(voice.engine_id); - if (engine_delegate_) + if (voice.from_remote_tts_engine) { + DCHECK(remote_engine_delegate_); + TtsUtteranceImpl* utterance_impl = + AsUtteranceImpl(current_utterance_.get()); + utterance_impl->set_spoken_by_remote_engine(true); + remote_engine_delegate_->Speak(current_utterance_.get(), voice); + } else if (engine_delegate_) { engine_delegate_->Speak(current_utterance_.get(), voice); + } + bool sends_end_event = voice.events.find(TTS_EVENT_END) != voice.events.end(); if (!sends_end_event) { @@ -1021,11 +1029,7 @@ void TtsControllerImpl::SetRemoteTtsEngineDelegate( RemoteTtsEngineDelegate* delegate) { -#if BUILDFLAG(IS_CHROMEOS_ASH) remote_engine_delegate_ = delegate; -#else - NOTREACHED(); -#endif } } // namespace content
diff --git a/content/browser/speech/tts_controller_impl.h b/content/browser/speech/tts_controller_impl.h index 7f79a41..ee36781 100644 --- a/content/browser/speech/tts_controller_impl.h +++ b/content/browser/speech/tts_controller_impl.h
@@ -195,9 +195,10 @@ TtsControllerDelegate* GetTtsControllerDelegate(); void SetTtsControllerDelegateForTesting(TtsControllerDelegate* delegate); TtsControllerDelegate* delegate_ = nullptr; - RemoteTtsEngineDelegate* remote_engine_delegate_ = nullptr; #endif + RemoteTtsEngineDelegate* remote_engine_delegate_ = nullptr; + raw_ptr<TtsEngineDelegate, DanglingUntriaged> engine_delegate_ = nullptr; bool stop_speaking_when_hidden_ = false;
diff --git a/content/browser/speech/tts_controller_unittest.cc b/content/browser/speech/tts_controller_unittest.cc index 2f59ab28..06057705 100644 --- a/content/browser/speech/tts_controller_unittest.cc +++ b/content/browser/speech/tts_controller_unittest.cc
@@ -148,6 +148,10 @@ // Count API calls (TtsEngineDelegate:) void Stop(TtsUtterance* utterance) override { ++stop_called_; } + void Stop(BrowserContext* browser_context, + const std::string& engine_id) override { + ++stop_called_; + } void Pause(TtsUtterance* utterance) override { ++pause_called_; } void Resume(TtsUtterance* utterance) override { ++resume_called_; }
diff --git a/content/browser/speech/tts_utterance_impl.h b/content/browser/speech/tts_utterance_impl.h index d1c1a06d..4fd59943 100644 --- a/content/browser/speech/tts_utterance_impl.h +++ b/content/browser/speech/tts_utterance_impl.h
@@ -38,6 +38,11 @@ return was_created_with_web_contents_; } + void set_spoken_by_remote_engine(bool value) { + spoken_by_remote_engine_ = value; + } + bool spoken_by_remote_engine() const { return spoken_by_remote_engine_; } + // TtsUtterance overrides. void OnTtsEvent(TtsEventType event_type, int char_index, @@ -107,6 +112,9 @@ // utterance, or empty if native TTS is being used. std::string engine_id_; + // True if this utterance is spoken by a remote TTS engine. + bool spoken_by_remote_engine_ = false; + // The unique ID of this utterance, used to associate callback functions // with utterances. int id_;
diff --git a/content/browser/tracing/background_tracing_active_scenario.cc b/content/browser/tracing/background_tracing_active_scenario.cc index 66d65dc..6fb958a 100644 --- a/content/browser/tracing/background_tracing_active_scenario.cc +++ b/content/browser/tracing/background_tracing_active_scenario.cc
@@ -254,6 +254,8 @@ if (scenario_state_ == State::kAborted) { DCHECK_NE(config_->tracing_mode(), BackgroundTracingConfigImpl::SYSTEM); tracing_session_.reset(); + tracing_timer_.reset(); + std::move(on_aborted_callback_).Run(); } }
diff --git a/content/browser/web_contents/web_contents_android.cc b/content/browser/web_contents/web_contents_android.cc index cfcbbf09..72f835f 100644 --- a/content/browser/web_contents/web_contents_android.cc +++ b/content/browser/web_contents/web_contents_android.cc
@@ -690,7 +690,7 @@ &WebContentsAndroid::AXTreeSnapshotCallback, weak_factory_.GetWeakPtr(), std::move(j_view_structure_root), std::move(j_view_structure_builder), std::move(j_callback)), - ui::AXMode(ui::kAXModeComplete.mode() | ui::AXMode::kHTMLMetadata), + ui::AXMode(ui::kAXModeComplete.flags() | ui::AXMode::kHTMLMetadata), /* exclude_offscreen= */ false, /* max_nodes= */ 5000, /* timeout= */ base::Seconds(2));
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index c1736cb..6d5e376 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -174,7 +174,6 @@ #include "third_party/blink/public/mojom/window_features/window_features.mojom.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/accessibility/ax_tree_combiner.h" -#include "ui/base/ime/mojom/virtual_keyboard_types.mojom.h" #include "ui/base/pointer/pointer_device.h" #include "ui/base/window_open_disposition.h" #include "ui/color/color_provider_manager.h" @@ -1700,7 +1699,7 @@ // them into a single tree and call |callback| with that result, then // delete |combiner|. auto params = mojom::SnapshotAccessibilityTreeParams::New(); - params->ax_mode = ax_mode.mode(); + params->ax_mode = ax_mode.flags(); params->exclude_offscreen = exclude_offscreen; params->max_nodes = max_nodes; params->timeout = timeout; @@ -2232,26 +2231,6 @@ &WebContentsObserver::DidChangeVerticalScrollDirection, scroll_direction); } -int WebContentsImpl::GetVirtualKeyboardResizeHeight() { - // Only consider a web contents to be insetted by the virtual keyboard if it - // is in the currently active tab. - if (GetVisibility() != Visibility::VISIBLE) - return 0; - - // The only mode where the virtual keyboard causes the web contents to be - // resized is kResizesContent. - if (GetPrimaryPage().virtual_keyboard_mode() != - ui::mojom::VirtualKeyboardMode::kResizesContent) { - return 0; - } - - // The virtual keyboard never resizes content when fullscreened. - if (IsFullscreen()) - return 0; - - return GetDelegate() ? GetDelegate()->GetVirtualKeyboardHeight(this) : 0; -} - void WebContentsImpl::OnAudioStateChanged() { // This notification can come from any embedded contents or from this // WebContents' stream monitor. Aggregate these signals to get the actual @@ -2860,9 +2839,6 @@ // GuestViews in the same StoragePartition need to find each other's frames. prefs.renderer_wide_named_frame_lookup = IsGuest(); - if (command_line.HasSwitch(switches::kHideScrollbars)) - prefs.hide_scrollbars = true; - GetContentClient()->browser()->OverrideWebkitPrefs(this, &prefs); return prefs; } @@ -4521,7 +4497,7 @@ DCHECK_EQ(start_recording, callback.has_value()); if (start_recording) { BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( - ui::kAXModeBasic.mode()); + ui::kAXModeBasic.flags()); auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager(); CHECK(ax_mgr); base::ProcessId pid = base::Process::Current().Pid();
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 93244e9..1c1cf15 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -310,6 +310,7 @@ // Returns the primary FrameTree for this WebContents (as opposed to the // ones held by MPArch features like Prerender or Fenced Frame). + // See docs/frame_trees.md for more details. FrameTree& GetPrimaryFrameTree() { return primary_frame_tree_; } // Whether the initial empty page of this view has been accessed by another @@ -914,7 +915,6 @@ const gfx::Size& new_size) override; void OnVerticalScrollDirectionChanged( viz::VerticalScrollDirection scroll_direction) override; - int GetVirtualKeyboardResizeHeight() override; double GetPendingPageZoomLevel() override;
diff --git a/content/common/content_param_traits.cc b/content/common/content_param_traits.cc index cd1be9f5..c032e37 100644 --- a/content/common/content_param_traits.cc +++ b/content/common/content_param_traits.cc
@@ -137,7 +137,7 @@ } void ParamTraits<ui::AXMode>::Write(base::Pickle* m, const param_type& p) { - WriteParam(m, p.mode()); + WriteParam(m, p.flags()); } bool ParamTraits<ui::AXMode>::Read(const base::Pickle* m,
diff --git a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java index 48d27754e..d850c04 100644 --- a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java
@@ -15,6 +15,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; +import org.chromium.content.browser.webcontents.WebContentsImpl; import org.chromium.gfx.mojom.Rect; import org.chromium.media.mojom.AndroidOverlay; import org.chromium.media.mojom.AndroidOverlayClient; @@ -59,6 +60,12 @@ private final AndroidOverlayConfig mConfig; private final boolean mAsPanel; + // The handler will be notified when the surface will be destroyed soon. We'll + // notify the client to cleanup tasks on the surface, because the surface may be + // destroyed before SurfaceHolder.Callback2.surfaceDestroyed returns. + private final Runnable mTearDownDialogOverlaysHandler = this::onOverlayDestroyed; + private WebContentsImpl mWebContents; + /** * @param client Mojo client interface. * @param config initial overlay configuration. @@ -247,6 +254,18 @@ mClient.onPowerEfficientState(isPowerEfficient); } + /** + * Callback from the native to provide the WebContents. It should be called inside completeInit. + */ + @CalledByNative + private void onWebContents(WebContentsImpl webContents) { + assert mWebContents == null; + assert webContents != null; + + mWebContents = webContents; + mWebContents.addTearDownDialogOverlaysHandler(mTearDownDialogOverlaysHandler); + } + /** Initialize |mDialogCore| when the window is available. */ private void initializeDialogCore(WindowAndroid window) { ThreadUtils.assertOnUiThread(); @@ -291,6 +310,11 @@ // Native should have cleaned up the container view before we reach this. assert mContainerViewViewTreeObserver == null; + + if (mWebContents != null) { + mWebContents.removeTearDownDialogOverlaysHandler(mTearDownDialogOverlaysHandler); + mWebContents = null; + } } private void notifyDestroyed() {
diff --git a/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java b/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java index f6a14b8..9bf8b967 100644 --- a/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java
@@ -228,15 +228,6 @@ mNativeRenderFrameHostAndroid, RenderFrameHostImpl.this); } - @Override - public void insertVisualStateCallback(Callback<Boolean> callback) { - if (mNativeRenderFrameHostAndroid == 0) { - callback.onResult(false); - } - RenderFrameHostImplJni.get().insertVisualStateCallback( - mNativeRenderFrameHostAndroid, callback); - } - @NativeMethods interface Natives { GURL getLastCommittedURL(long nativeRenderFrameHostAndroid, RenderFrameHostImpl caller); @@ -267,7 +258,5 @@ RenderFrameHostImpl caller, String relyingPartyId, Origin effectiveOrigin, boolean isPaymentCredentialCreation); int getLifecycleState(long nativeRenderFrameHostAndroid, RenderFrameHostImpl caller); - void insertVisualStateCallback( - long nativeRenderFrameHostAndroid, Callback<Boolean> callback); } }
diff --git a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java index 15d27cd..337b37c 100644 --- a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java
@@ -22,6 +22,7 @@ import androidx.annotation.VisibleForTesting; import org.chromium.base.Log; +import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import org.chromium.base.UserData; import org.chromium.base.UserDataHost; @@ -67,6 +68,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -207,6 +209,8 @@ // Remember the stack for clearing native the native stack for debugging use after destroy. private Throwable mNativeDestroyThrowable; + private ObserverList<Runnable> mTearDownDialogOverlaysHandlers; + private static class WebContentsInternalsImpl implements WebContentsInternals { public UserDataHost userDataHost; public ViewAndroidDelegate viewAndroidDelegate; @@ -1074,6 +1078,32 @@ WebContentsImplJni.get().notifyBrowserControlsHeightChanged(mNativeWebContentsAndroid); } + @Override + public void tearDownDialogOverlays() { + if (mTearDownDialogOverlaysHandlers == null) return; + Iterator<Runnable> it = mTearDownDialogOverlaysHandlers.iterator(); + while (it.hasNext()) { + Runnable handler = it.next(); + handler.run(); + } + } + + public void addTearDownDialogOverlaysHandler(Runnable handler) { + if (mTearDownDialogOverlaysHandlers == null) { + mTearDownDialogOverlaysHandlers = new ObserverList<>(); + } + + assert !mTearDownDialogOverlaysHandlers.hasObserver(handler); + mTearDownDialogOverlaysHandlers.addObserver(handler); + } + + public void removeTearDownDialogOverlaysHandler(Runnable handler) { + assert mTearDownDialogOverlaysHandlers != null; + assert mTearDownDialogOverlaysHandlers.hasObserver(handler); + + mTearDownDialogOverlaysHandlers.removeObserver(handler); + } + private void checkNotDestroyed() { if (mNativeWebContentsAndroid != 0) return; throw new IllegalStateException(
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java b/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java index 466618b..d8510c4 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java
@@ -174,21 +174,4 @@ */ @LifecycleState int getLifecycleState(); - - /** - * Inserts a VisualStateCallback that's resolved once a visual update has been processed. - * - * The VisualStateCallback will be inserted in Blink and will be invoked when the contents of - * the DOM tree at the moment that the callback was inserted (or later) are submitted to the - * compositor in a CompositorFrame. In other words, the following events need to happen before - * the callback is invoked: - * 1. The DOM tree is committed becoming the pending tree - see ThreadProxy::BeginMainFrame - * 2. The pending tree is activated becoming the active tree - * 3. The compositor calls Draw and submits a new CompositorFrame to the Viz process. - * The callback is synchronously invoked if this is called while being destroyed. - * - * @param callback the callback to be inserted. The callback takes a single Boolean parameter - * which will be true if the visual state update was successful or false if it was aborted. - */ - void insertVisualStateCallback(Callback<Boolean> callback); }
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/WebContents.java b/content/public/android/java/src/org/chromium/content_public/browser/WebContents.java index 6e64784..fa8f159 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/WebContents.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/WebContents.java
@@ -555,4 +555,11 @@ * this. Min-height is the minimum visible height the controls can have. */ void notifyBrowserControlsHeightChanged(); + + /** + * Called before the dialog overlay dismissing e.g. Activity.onUserLeaveHint. It's a signal to + * cleanup the tasks depending on the overlay surface, because the surface destroy may happen + * before SurfaceHolder.Callback2.surfaceDestroyed returns. + */ + void tearDownDialogOverlays(); }
diff --git a/content/public/browser/navigation_controller.h b/content/public/browser/navigation_controller.h index d670516..3f56a51 100644 --- a/content/public/browser/navigation_controller.h +++ b/content/public/browser/navigation_controller.h
@@ -70,7 +70,7 @@ // WebContents, so there can be multiple NavigationControllers associated with // a WebContents. However only the primary one, and the // NavigationEntries/events originating from it, is exposed to //content -// embedders. +// embedders. See docs/frame_trees.md for more details. class NavigationController { public: using DeletionPredicate =
diff --git a/content/public/browser/navigation_handle.h b/content/public/browser/navigation_handle.h index b2fefdf..5ba39b81 100644 --- a/content/public/browser/navigation_handle.h +++ b/content/public/browser/navigation_handle.h
@@ -115,6 +115,7 @@ // additional frame trees for prerendering pages in addition to the primary // frame tree (holding the page currently shown to the user). The return // value remains constant over the navigation lifetime. + // See docs/frame_trees.md for more details. virtual bool IsInPrimaryMainFrame() const = 0; // Whether the navigation is taking place in a main frame which does not have
diff --git a/content/public/browser/page.h b/content/public/browser/page.h index 652333d..b503d78 100644 --- a/content/public/browser/page.h +++ b/content/public/browser/page.h
@@ -47,6 +47,7 @@ // additional FrameTrees which will have their own associated Page. Please take // into consideration when assuming that Page is appropriate for storing // something that's common for all frames you see on a tab. +// See docs/frame_trees.md for more details. // NOTE: Depending on the process model, the cross-origin iframes are likely to // be hosted in a different renderer process than the main document, so a given
diff --git a/content/public/browser/render_frame_host.h b/content/public/browser/render_frame_host.h index 06ba022..e88f5a3 100644 --- a/content/public/browser/render_frame_host.h +++ b/content/public/browser/render_frame_host.h
@@ -318,6 +318,7 @@ // Note that this may be different from getting the WebContents' primary main // frame. For example, if `this` is in a bfcached or prerendered page, this // will return the cached/prerendered page's main RenderFrameHost. + // See docs/frame_trees.md for more details. virtual RenderFrameHost* GetOutermostMainFrame() = 0; // Fenced frames (meta-bug https://crbug.com/1111084):
diff --git a/content/public/browser/tts_controller.h b/content/public/browser/tts_controller.h index 33463f0..6592b41f 100644 --- a/content/public/browser/tts_controller.h +++ b/content/public/browser/tts_controller.h
@@ -44,10 +44,8 @@ bool native; std::string native_voice_identifier; -#if BUILDFLAG(IS_CHROMEOS_ASH) - // If true, the voice is from a remote tts engine. - bool from_crosapi = false; -#endif + // If true, the voice is provided by a remote TTS engine. + bool from_remote_tts_engine = false; }; // Interface that delegates TTS requests to engines in content embedders. @@ -68,6 +66,10 @@ // associated with this utterance. virtual void Stop(TtsUtterance* utterance) = 0; + // Stop the given speech engine loaded in |browser_context|. + virtual void Stop(BrowserContext* browser_context, + const std::string& engine_id) = 0; + // Pause in the middle of speaking this utterance. virtual void Pause(TtsUtterance* utterance) = 0; @@ -91,6 +93,13 @@ // Returns a list of voices from remote tts engine for |browser_context|. virtual void GetVoices(BrowserContext* browser_context, std::vector<VoiceData>* out_voices) = 0; + + // Requests the given remote TTS engine to speak |utterance| with |voice|. + virtual void Speak(TtsUtterance* utterance, const VoiceData& voice) = 0; + + // Requests the remote TTS engine associated with |utterance| to stop + // speaking the |utterance|. + virtual void Stop(TtsUtterance* utterance) = 0; }; // Class that wants to be notified when the set of
diff --git a/content/public/browser/tts_platform.h b/content/public/browser/tts_platform.h index c36d38b..fbd146d4 100644 --- a/content/public/browser/tts_platform.h +++ b/content/public/browser/tts_platform.h
@@ -34,6 +34,25 @@ // utterance will be added to the utterance queue of the external // TtsController and processed in sequence. virtual void Enqueue(std::unique_ptr<TtsUtterance> utterance) = 0; + + // Handles TTS event received from the speech engine. Events are forwarded to + // the callback function, and in addition, completion and error events + // trigger finishing the current utterance. + // |utterance_id|: id of the utterance TtsEvent is associated with. + // |char_index|: The index of the current character in the utterance. For word + // events, the event fires at the end of one word and before the beginning of + // the next.The charIndex represents a point in the text at the beginning of + // the next word to be spoken. + // |length|: The length of the next part of the utterance. For example, in a + // word event, this is the length of the word which will be spoken next. + // If the |char_index| or |length| are not available, the speech engine should + // pass -1. + virtual void OnTtsEvent(content::BrowserContext* browser_context, + int utterance_id, + TtsEventType event_type, + int char_index, + int length, + const std::string& error_message) = 0; }; // Abstract class that defines the native platform TTS interface,
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index cc61bc1..03fe62f 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -120,11 +120,10 @@ // https://www.chromium.org/developers/design-documents/multi-process-architecture // . // -// Each WebContents has exactly one NavigationController; each -// NavigationController belongs to one WebContents. The NavigationController can -// be obtained from GetController(), and is used to load URLs into the -// WebContents, navigate it backwards/forwards, etc. See navigation_controller.h -// for more details. +// Each WebContents has a `NavigationController`, which can be obtained from +// `GetController()`, and is used to load URLs into the WebContents, navigate +// it backwards/forwards, etc. +// See navigation_controller.h for more details. class WebContents : public PageNavigator, public base::SupportsUserData { public: @@ -368,6 +367,7 @@ // Returns the primary main frame for the currently active page. Always // non-null except during WebContents destruction. This WebContents may // have additional main frames for prerendered pages, bfcached pages, etc. + // See docs/frame_trees.md for more details. virtual RenderFrameHost* GetPrimaryMainFrame() = 0; // Returns the current page in the primary frame tree of this WebContents. @@ -401,6 +401,7 @@ // reference to RenderFrameHost or a Page (e.g. each IPC from the renderer // process should be associated with a particular RenderFrameHost), it should // be used instead of getting the primary page from the WebContents. + // See docs/frame_trees.md for more details. virtual Page& GetPrimaryPage() = 0; // Returns the focused frame for the primary page or an inner page thereof.
diff --git a/content/public/browser/web_contents_delegate.cc b/content/public/browser/web_contents_delegate.cc index 7122abf..4f4ce7c4 100644 --- a/content/public/browser/web_contents_delegate.cc +++ b/content/public/browser/web_contents_delegate.cc
@@ -333,10 +333,6 @@ return false; } -int WebContentsDelegate::GetVirtualKeyboardHeight(WebContents* web_contents) { - return 0; -} - bool WebContentsDelegate::OnlyExpandTopControlsAtPageTop() { return false; }
diff --git a/content/public/browser/web_contents_delegate.h b/content/public/browser/web_contents_delegate.h index e2ce097..03b810c5 100644 --- a/content/public/browser/web_contents_delegate.h +++ b/content/public/browser/web_contents_delegate.h
@@ -651,7 +651,6 @@ virtual int GetBottomControlsMinHeight(); virtual bool ShouldAnimateBrowserControlsHeightChanges(); virtual bool DoBrowserControlsShrinkRendererSize(WebContents* web_contents); - virtual int GetVirtualKeyboardHeight(WebContents* web_contents); // Returns true if the top controls should only expand at the top of the page, // so they'll only be visible if the page is scrolled to the top. virtual bool OnlyExpandTopControlsAtPageTop();
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 38bbb62..2d16cfa4a 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -498,10 +498,6 @@ // Causes the GPU process to display a dialog on launch. const char kGpuStartupDialog[] = "gpu-startup-dialog"; -// Prevents creating scrollbars for web content. Useful for taking consistent -// screenshots. -const char kHideScrollbars[] = "hide-scrollbars"; - // Run the GPU process as a thread in the browser process. const char kInProcessGPU[] = "in-process-gpu";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index f1395bf..2c202f8 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -154,7 +154,6 @@ CONTENT_EXPORT extern const char kGpuProcess[]; CONTENT_EXPORT extern const char kGpuSandboxStartEarly[]; CONTENT_EXPORT extern const char kGpuStartupDialog[]; -extern const char kHideScrollbars[]; CONTENT_EXPORT extern const char kInProcessGPU[]; CONTENT_EXPORT extern const char kIPCConnectionTimeout[]; CONTENT_EXPORT extern const char kIsolatedAppOrigins[];
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockRenderFrameHost.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockRenderFrameHost.java index e6efdfc..bf8eacf 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockRenderFrameHost.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockRenderFrameHost.java
@@ -98,7 +98,4 @@ public int getLifecycleState() { return LifecycleState.ACTIVE; } - - @Override - public void insertVisualStateCallback(Callback<Boolean> callback) {} }
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockWebContents.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockWebContents.java index 32271b2a..f8b6dc6 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockWebContents.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockWebContents.java
@@ -319,4 +319,7 @@ @Override public void notifyBrowserControlsHeightChanged() {} + + @Override + public void tearDownDialogOverlays() {} }
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/Coordinates.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/Coordinates.java index 62660f8..88f68f4 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/Coordinates.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/util/Coordinates.java
@@ -54,8 +54,4 @@ public int getContentHeightPixInt() { return mRenderCoordinates.getContentHeightPixInt(); } - - public float getContentOffsetYPix() { - return mRenderCoordinates.getContentOffsetYPix(); - } }
diff --git a/content/public/test/mock_navigation_handle.h b/content/public/test/mock_navigation_handle.h index e2aaa4e..5add574 100644 --- a/content/public/test/mock_navigation_handle.h +++ b/content/public/test/mock_navigation_handle.h
@@ -50,7 +50,7 @@ return starting_site_instance_; } SiteInstance* GetSourceSiteInstance() override { - return nullptr; // Good enough for unit tests... + return source_site_instance_; } bool IsInMainFrame() const override { return render_frame_host_ ? !render_frame_host_->GetParent() : true; @@ -227,6 +227,9 @@ void set_starting_site_instance(SiteInstance* site_instance) { starting_site_instance_ = site_instance; } + void set_source_site_instance(SiteInstance* site_instance) { + source_site_instance_ = site_instance; + } void set_page_transition(ui::PageTransition page_transition) { page_transition_ = page_transition; } @@ -302,6 +305,7 @@ GURL url_; GURL previous_primary_main_frame_url_; raw_ptr<SiteInstance> starting_site_instance_ = nullptr; + raw_ptr<SiteInstance> source_site_instance_ = nullptr; raw_ptr<WebContents> web_contents_ = nullptr; GURL base_url_for_data_url_; blink::mojom::Referrer referrer_;
diff --git a/content/renderer/accessibility/render_accessibility_impl.cc b/content/renderer/accessibility/render_accessibility_impl.cc index 00f2af4..0de8125 100644 --- a/content/renderer/accessibility/render_accessibility_impl.cc +++ b/content/renderer/accessibility/render_accessibility_impl.cc
@@ -566,6 +566,7 @@ return true; case ax::mojom::Event::kAriaAttributeChanged: + case ax::mojom::Event::kChildrenChanged: case ax::mojom::Event::kDocumentTitleChanged: case ax::mojom::Event::kExpandedChanged: case ax::mojom::Event::kHide: @@ -587,7 +588,6 @@ // This list is duplicated in WebFrameTestProxy::PostAccessibilityEvent(). case ax::mojom::Event::kAlert: case ax::mojom::Event::kAutocorrectionOccured: - case ax::mojom::Event::kChildrenChanged: case ax::mojom::Event::kControlsChanged: case ax::mojom::Event::kEndOfTest: case ax::mojom::Event::kFocusAfterMenuClose: @@ -761,7 +761,7 @@ if (obj.IsNull()) return; - MarkWebAXObjectDirty(obj, /* subtree */ false); + HandleAXEvent(ui::AXEvent(obj.AxID(), ax::mojom::Event::kChildrenChanged)); } void RenderAccessibilityImpl::ShowPluginContextMenu() {
diff --git a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc index 65e50085..f2c03b75 100644 --- a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc +++ b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
@@ -310,7 +310,7 @@ // Ensure that a valid RenderAccessibilityImpl object is created and // associated to the RenderFrame, so that calls from tests to methods of // RenderAccessibilityImpl will work. - frame()->SetAccessibilityModeForTest(ui::kAXModeWebContentsOnly.mode()); + frame()->SetAccessibilityModeForTest(ui::kAXModeWebContentsOnly.flags()); } void TearDown() override { @@ -324,7 +324,7 @@ } void SetMode(ui::AXMode mode) { - frame()->GetRenderAccessibilityManager()->SetMode(mode.mode()); + frame()->GetRenderAccessibilityManager()->SetMode(mode); } ui::AXTreeUpdate GetLastAccUpdate() { @@ -453,7 +453,8 @@ // Send a childrenChanged on "A". ClearHandledUpdates(); - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(node_a, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(node_a.AxID(), ax::mojom::Event::kChildrenChanged)); // Hide node "B" ("C" stays visible). ExecuteJavaScriptForTests( @@ -465,7 +466,7 @@ // Since ignored nodes are included in the ax tree with State::kIgnored set, // "C" is NOT reparented, only the changed nodes are re-serialized. - // "A" updates because it handled dirty object + // "A" updates because it handled Event::kChildrenChanged // "B" updates because its State::kIgnored has changed EXPECT_EQ(0, update.node_id_to_clear); EXPECT_EQ(node_a.AxID(), update.nodes[0].id); @@ -501,7 +502,8 @@ WebAXObject node_c = node_b.ChildAt(0); // Send a childrenChanged on "A" and show node "B", - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(node_a, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(node_a.AxID(), ax::mojom::Event::kChildrenChanged)); ExecuteJavaScriptForTests( "document.getElementById('B').style.visibility = 'visible';"); @@ -512,7 +514,7 @@ // Since ignored nodes are included in the ax tree with State::kIgnored set, // "C" is NOT reparented, only the changed nodes are re-serialized. - // "A" updates because it handled the dirty + // "A" updates because it handled Event::kChildrenChanged // "B" updates because its State::kIgnored has changed ASSERT_EQ(2U, update.nodes.size()); EXPECT_EQ(0, update.node_id_to_clear); @@ -1218,7 +1220,8 @@ // No URL-keyed metrics should be fired after we send one event. WebDocument document = GetMainFrame()->GetDocument(); WebAXObject root_obj = WebAXObject::FromWebDocument(document); - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(root_obj, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(root_obj.AxID(), ax::mojom::Event::kChildrenChanged)); SendPendingAccessibilityEvents(); EXPECT_EQ(0, ukm_recorder()->calls()); histogram_tester.ExpectTotalCount( @@ -1227,7 +1230,8 @@ // No URL-keyed metrics should be fired even after an event that takes // 300 ms, but we should now have something to send. // This must be >= kMinSerializationTimeToSendInMS - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(root_obj, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(root_obj.AxID(), ax::mojom::Event::kChildrenChanged)); SendPendingAccessibilityEvents(); SetTimeDelayForNextSerialize(base::Milliseconds(300)); EXPECT_EQ(0, ukm_recorder()->calls()); @@ -1237,7 +1241,8 @@ // After 1000 seconds have passed, the next time we send an event we should // send URL-keyed metrics. task_environment_.FastForwardBy(base::Seconds(1000)); - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(root_obj, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(root_obj.AxID(), ax::mojom::Event::kChildrenChanged)); SendPendingAccessibilityEvents(); EXPECT_EQ(1, ukm_recorder()->calls()); histogram_tester.ExpectTotalCount( @@ -1246,7 +1251,8 @@ // Send another event that takes a long (simulated) time to serialize. // This must be >= kMinSerializationTimeToSend SetTimeDelayForNextSerialize(base::Milliseconds(200)); - GetRenderAccessibilityImpl()->MarkWebAXObjectDirty(root_obj, false); + GetRenderAccessibilityImpl()->HandleAXEvent( + ui::AXEvent(root_obj.AxID(), ax::mojom::Event::kChildrenChanged)); SendPendingAccessibilityEvents(); histogram_tester.ExpectTotalCount( "Accessibility.Performance.SendPendingAccessibilityEvents", 4);
diff --git a/content/renderer/accessibility/render_accessibility_manager.cc b/content/renderer/accessibility/render_accessibility_manager.cc index 4db08b83..e9485f36 100644 --- a/content/renderer/accessibility/render_accessibility_manager.cc +++ b/content/renderer/accessibility/render_accessibility_manager.cc
@@ -31,7 +31,7 @@ receiver_.set_disconnect_handler(base::BindOnce( [](RenderAccessibilityManager* impl) { impl->receiver_.reset(); - impl->SetMode(0); + impl->SetMode(ui::AXMode::kNone); }, base::Unretained(this))); } @@ -47,9 +47,9 @@ return render_accessibility_->GetAccessibilityMode(); } -void RenderAccessibilityManager::SetMode(uint32_t ax_mode) { +void RenderAccessibilityManager::SetMode(const ui::AXMode& new_mode) { ui::AXMode old_mode = GetAccessibilityMode(); - ui::AXMode new_mode(ax_mode); + if (old_mode == new_mode) return;
diff --git a/content/renderer/accessibility/render_accessibility_manager.h b/content/renderer/accessibility/render_accessibility_manager.h index 358962f..465d4b51 100644 --- a/content/renderer/accessibility/render_accessibility_manager.h +++ b/content/renderer/accessibility/render_accessibility_manager.h
@@ -64,7 +64,7 @@ ui::AXMode GetAccessibilityMode() const; // mojom::RenderAccessibility implementation. - void SetMode(uint32_t ax_mode) override; + void SetMode(const ui::AXMode& ax_mode) override; void FatalError() override; void HitTest( const gfx::Point& point,
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index aa66067..7bb5ad2 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -6022,7 +6022,7 @@ } void RenderFrameImpl::SetAccessibilityModeForTest(ui::AXMode new_mode) { - render_accessibility_manager_->SetMode(new_mode.mode()); + render_accessibility_manager_->SetMode(new_mode); } scoped_refptr<network::SharedURLLoaderFactory>
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index f8ae75f..86d691e7 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -2622,15 +2622,15 @@ ASSERT_TRUE(GetRenderAccessibilityManager()); ASSERT_FALSE(GetRenderAccessibilityManager()->GetRenderAccessibilityImpl()); - GetRenderAccessibilityManager()->SetMode(ui::kAXModeWebContentsOnly.mode()); + GetRenderAccessibilityManager()->SetMode(ui::kAXModeWebContentsOnly); ASSERT_TRUE(GetAccessibilityMode() == ui::kAXModeWebContentsOnly); ASSERT_TRUE(GetRenderAccessibilityManager()->GetRenderAccessibilityImpl()); - GetRenderAccessibilityManager()->SetMode(0); + GetRenderAccessibilityManager()->SetMode(ui::AXMode::kNone); ASSERT_TRUE(GetAccessibilityMode().is_mode_off()); ASSERT_FALSE(GetRenderAccessibilityManager()->GetRenderAccessibilityImpl()); - GetRenderAccessibilityManager()->SetMode(ui::kAXModeComplete.mode()); + GetRenderAccessibilityManager()->SetMode(ui::kAXModeComplete); ASSERT_TRUE(GetAccessibilityMode() == ui::kAXModeComplete); ASSERT_TRUE(GetRenderAccessibilityManager()->GetRenderAccessibilityImpl()); } @@ -2642,7 +2642,7 @@ GetRenderAccessibilityManager()->BindReceiver( remote.BindNewEndpointAndPassReceiver()); - GetRenderAccessibilityManager()->SetMode(ui::kAXModeWebContentsOnly.mode()); + GetRenderAccessibilityManager()->SetMode(ui::kAXModeWebContentsOnly); ASSERT_TRUE(GetAccessibilityMode() == ui::kAXModeWebContentsOnly); ASSERT_TRUE(GetRenderAccessibilityManager()->GetRenderAccessibilityImpl());
diff --git a/content/test/attribution_simulator_impl.cc b/content/test/attribution_simulator_impl.cc index 634e5736..6fd7417 100644 --- a/content/test/attribution_simulator_impl.cc +++ b/content/test/attribution_simulator_impl.cc
@@ -225,7 +225,9 @@ /*http_response_code=*/200)); } - void SendReport(AttributionDebugReport report) override { + void SendReport(AttributionDebugReport report, + DebugReportSentCallback done) override { + std::move(done).Run(std::move(report), /*status=*/200); // TODO(crbug.com/1371970): Consider supporting debug reports in the // simulator. }
diff --git a/content/web_test/renderer/web_frame_test_proxy.cc b/content/web_test/renderer/web_frame_test_proxy.cc index 30000db..376a78b 100644 --- a/content/web_test/renderer/web_frame_test_proxy.cc +++ b/content/web_test/renderer/web_frame_test_proxy.cc
@@ -559,6 +559,9 @@ case ax::mojom::Event::kCheckedStateChanged: event_name = "CheckedStateChanged"; break; + case ax::mojom::Event::kChildrenChanged: + event_name = "ChildrenChanged"; + break; case ax::mojom::Event::kClicked: event_name = "Clicked"; break; @@ -628,7 +631,6 @@ // RenderAccessibilityImpl::IsImmediateProcessingRequiredForEvent(). case ax::mojom::Event::kAlert: case ax::mojom::Event::kAutocorrectionOccured: - case ax::mojom::Event::kChildrenChanged: case ax::mojom::Event::kControlsChanged: case ax::mojom::Event::kEndOfTest: case ax::mojom::Event::kFocusAfterMenuClose:
diff --git a/docs/frame_trees.md b/docs/frame_trees.md index 999474a..f4301a7 100644 --- a/docs/frame_trees.md +++ b/docs/frame_trees.md
@@ -99,6 +99,19 @@ hosting document owns the inner FrameTree (possibly through an intermediate object, as is the case for content::FencedFrame). +## "MPArch" + +"MPArch," short for Multiple Page Architecture, refers to the name of the +project that introduced the capability of having multiple FrameTrees in a +single WebContents. + +You may also see comments which describe features relying on multiple FrameTrees +in terms of MPArch (e.g. "ignore navigations from MPArch pages"). These are in +reference to "non-primary" frame trees as described above. + +See the original [design doc](https://docs.google.com/document/d/1NginQ8k0w3znuwTiJ5qjYmBKgZDekvEPC22q0I4swxQ/edit?usp=sharing) +for further info. + ## Footnotes <a name="footnote_1"></a>1: GuestViews (embedding of a WebContents inside another WebContents) are
diff --git a/docs/updater/design_doc.md b/docs/updater/design_doc.md index ffb6e53..46f0bbb 100644 --- a/docs/updater/design_doc.md +++ b/docs/updater/design_doc.md
@@ -754,7 +754,7 @@ ### Periodic Task Scheduling On Mac, the scheduler is implemented via LaunchAgents (for user-level installs) and LaunchDaemons (for system-level installs). The scheduled task is defined by -the `org.chromium.ChromiumUpdater.wake.1.2.3.4.plist`, which contains a Label +the `org.chromium.ChromiumUpdater.wake.plist`, which contains a Label corresponding to the name of the plist, program arguments, which contains the path to the executable and the arguments it'll run with, and a StartInterval, which denotes interval for when launchctl should invoke the program. An example: @@ -767,13 +767,13 @@ <key>AbandonProcessGroup</key> <true/> <key>Label</key> - <string>org.chromium.ChromiumUpdater.wake.1.2.3.4</string> + <string>org.chromium.ChromiumUpdater.wake</string> <key>LimitLoadToSessionType</key> <string>Aqua</string> <key>ProgramArguments</key> <array> <string>/Users/user/Library/Chromium/ChromiumUpdater/1.2.3.4/ChromiumUpdater.app/Contents/MacOS/ChromiumUpdater</string> - <string>--wake</string> + <string>--wake-all</string> <string>--vmodule=*/chrome/updater/*=2,*/components/update_client/*=2</string> <string>--enable-logging</string> </array> @@ -783,6 +783,13 @@ </plist> ``` +macOS 13 notifies the user each time a new task is created. Since it is not +useful to notify the user each time the updater sets up a new version of +itself, the scheduled task is not side-by-side on macOS 13. The task is +replaced during each activation of each new instance, and calls --wake-all for +the active version of the updater. --wakeall will then --wake every version of +the updater that is present in the base install directory. + ### Legacy State TODO(crbug.com/1035895): Document usage of Keystone tickets on macOS.
diff --git a/docs/updater/functional_spec.md b/docs/updater/functional_spec.md index 3eecf8d7..4a60523 100644 --- a/docs/updater/functional_spec.md +++ b/docs/updater/functional_spec.md
@@ -148,7 +148,7 @@ updater is inactive, it may qualify and activate, or uninstall itself. If this version of the updater is active, it may check for updates for applications, unregister uninstalled applications, and more. -* --wakeall +* --wake-all * Runs --wake for every updater version installed in this scope. * --crash-me * Record a backtrace in the log, crash the program, save a crash dump,
diff --git a/extensions/browser/api/automation_internal/automation_internal_api.cc b/extensions/browser/api/automation_internal/automation_internal_api.cc index 6f8e614..f91e306af 100644 --- a/extensions/browser/api/automation_internal/automation_internal_api.cc +++ b/extensions/browser/api/automation_internal/automation_internal_api.cc
@@ -446,7 +446,7 @@ return; ui::AXMode new_mode = web_contents()->GetAccessibilityMode(); - uint8_t flags = ui::kAXModeWebContentsOnly.mode(); + uint8_t flags = ui::kAXModeWebContentsOnly.flags(); new_mode.set_mode(flags, false); web_contents()->SetAccessibilityMode(std::move(new_mode)); }
diff --git a/extensions/browser/extension_user_script_loader.cc b/extensions/browser/extension_user_script_loader.cc index 38ac74b..991e735 100644 --- a/extensions/browser/extension_user_script_loader.cc +++ b/extensions/browser/extension_user_script_loader.cc
@@ -21,6 +21,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/memory/read_only_shared_memory_region.h" +#include "base/metrics/histogram_macros.h" #include "base/one_shot_event.h" #include "base/run_loop.h" #include "base/strings/string_util.h" @@ -155,6 +156,19 @@ FROM_HERE, base::BindOnce(&VerifyContent, std::move(info))); } +void RecordContentScriptLength(const std::string& script_content) { + // Max bucket at 10 GB, which is way above the reasonable maximum size of a + // script. + static constexpr int kMaxUmaLength = 1024 * 1024 * 10; + static constexpr int kMinUmaLength = 1; + static constexpr int kBucketCount = 50; + + size_t content_script_length_kb = script_content.length() / 1024; + UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ContentScripts.ContentScriptLength", + content_script_length_kb, kMinUmaLength, + kMaxUmaLength, kBucketCount); +} + // Loads user scripts from the extension who owns these scripts. void LoadScriptContent(const mojom::HostID& host_id, UserScript::File* script_file, @@ -194,8 +208,12 @@ // Remove BOM from the content. if (base::StartsWith(*content, base::kUtf8ByteOrderMark, base::CompareCase::SENSITIVE)) { - script_file->set_content(content->substr(strlen(base::kUtf8ByteOrderMark))); + std::string trimmed_content = + content->substr(strlen(base::kUtf8ByteOrderMark)); + RecordContentScriptLength(trimmed_content); + script_file->set_content(trimmed_content); } else { + RecordContentScriptLength(*content); script_file->set_content(*content); } }
diff --git a/fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml b/fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml index a97928a..b8f37b0 100644 --- a/fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml +++ b/fuchsia_web/runners/cast/cast_runner_integration_test.shard.test-cml
@@ -47,7 +47,6 @@ "deprecated-allowed-packages": [ "cast_runner", "flatland-scene-manager-test-ui-stack", - "test_manager", "web_engine", ], },
diff --git a/fuchsia_web/webengine/web_engine_integration_tests.shard.test-cml b/fuchsia_web/webengine/web_engine_integration_tests.shard.test-cml index f741869..fc83e8f 100644 --- a/fuchsia_web/webengine/web_engine_integration_tests.shard.test-cml +++ b/fuchsia_web/webengine/web_engine_integration_tests.shard.test-cml
@@ -51,7 +51,6 @@ "deprecated-allowed-packages": [ "cursor", "flatland-scene-manager-test-ui-stack", - "test_manager", "web_engine", ], },
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index 7ac1fc8..036abc5f9 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -8558,10 +8558,18 @@ service_id = texture_ref->service_id(); } + bool valid_target = false; + if (texture_ref) { + valid_target = texture_manager()->ValidForTextureTarget( + texture_ref->texture(), level, 0, 0, 1); + } else { + valid_target = texture_manager()->ValidForTarget(textarget, level, 0, 0, 1); + } + if ((level > 0 && !feature_info_->IsWebGL2OrES3Context() && !(fbo_render_mipmap_explicitly_enabled_ && feature_info_->feature_flags().oes_fbo_render_mipmap)) || - !texture_manager()->ValidForTarget(textarget, level, 0, 0, 1)) { + !valid_target) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, name, "level out of range"); @@ -8633,8 +8641,8 @@ "texture is neither TEXTURE_3D nor TEXTURE_2D_ARRAY"); return; } - if (!texture_manager()->ValidForTarget(texture_target, level, - 0, 0, layer)) { + if (!texture_manager()->ValidForTextureTarget(texture_ref->texture(), level, + 0, 0, layer)) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "invalid level or layer"); return; @@ -14686,11 +14694,6 @@ LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "imageSize < 0"); return error::kNoError; } - if (!texture_manager()->ValidForTarget(target, level, width, height, depth) || - border != 0) { - LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "dimensions out of range"); - return error::kNoError; - } TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( &state_, target); if (!texture_ref) { @@ -14699,6 +14702,12 @@ return error::kNoError; } Texture* texture = texture_ref->texture(); + if (!texture_manager()->ValidForTextureTarget(texture, level, width, height, + depth) || + border != 0) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "dimensions out of range"); + return error::kNoError; + } if (texture->IsImmutable()) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, "texture is immutable"); return error::kNoError; @@ -15068,10 +15077,6 @@ LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "imageSize < 0"); return error::kNoError; } - if (!texture_manager()->ValidForTarget(target, level, width, height, depth)) { - LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "dimensions out of range"); - return error::kNoError; - } TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( &state_, target); if (!texture_ref) { @@ -15079,7 +15084,14 @@ GL_INVALID_OPERATION, func_name, "no texture bound at target"); return error::kNoError; } + Texture* texture = texture_ref->texture(); + if (!texture_manager()->ValidForTextureTarget(texture, level, width, height, + depth)) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "dimensions out of range"); + return error::kNoError; + } + GLenum type = 0; GLenum internal_format = 0; if (!texture->GetLevelType(target, level, &type, &internal_format)) { @@ -15204,7 +15216,8 @@ GL_INVALID_OPERATION, func_name, "texture is immutable"); return; } - if (!texture_manager()->ValidForTarget(target, level, width, height, 1) || + if (!texture_manager()->ValidForTextureTarget(texture, level, width, height, + 1) || border != 0) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, func_name, "dimensions out of range"); @@ -17778,8 +17791,8 @@ } // Check that this type of texture is allowed. - if (!texture_manager()->ValidForTarget(source_target, source_level, - source_width, source_height, 1)) { + if (!texture_manager()->ValidForTextureTarget( + source_texture, source_level, source_width, source_height, 1)) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, kFunctionName, "Bad dimensions"); return; } @@ -17946,8 +17959,8 @@ } // Check that this type of texture is allowed. - if (!texture_manager()->ValidForTarget(source_target, source_level, - source_width, source_height, 1)) { + if (!texture_manager()->ValidForTextureTarget( + source_texture, source_level, source_width, source_height, 1)) { LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "source texture bad dimensions"); return; @@ -18187,11 +18200,20 @@ return; } } + TextureRef* texture_ref = + texture_manager()->GetTextureInfoForTarget(&state_, target); + if (!texture_ref) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, function_name, + "unknown texture for target"); + return; + } + Texture* texture = texture_ref->texture(); // The glTexStorage entry points require width, height, and depth to be // at least 1, but the other texture entry points (those which use - // ValidForTarget) do not. So we have to add an extra check here. + // ValidForTextureTarget) do not. So we have to add an extra check here. bool is_invalid_texstorage_size = width < 1 || height < 1 || depth < 1; - if (!texture_manager()->ValidForTarget(target, 0, width, height, depth) || + if (!texture_manager()->ValidForTextureTarget(texture, 0, width, height, + depth) || is_invalid_texstorage_size) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "dimensions out of range"); @@ -18204,14 +18226,6 @@ LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, function_name, "too many levels"); return; } - TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( - &state_, target); - if (!texture_ref) { - LOCAL_SET_GL_ERROR( - GL_INVALID_OPERATION, function_name, "unknown texture for target"); - return; - } - Texture* texture = texture_ref->texture(); if (texture->IsAttachedToFramebuffer()) { framebuffer_state_.clear_state_dirty = true; }
diff --git a/gpu/command_buffer/service/texture_manager.cc b/gpu/command_buffer/service/texture_manager.cc index 48325b8..ba0ebe2 100644 --- a/gpu/command_buffer/service/texture_manager.cc +++ b/gpu/command_buffer/service/texture_manager.cc
@@ -1642,7 +1642,7 @@ return; if (face_infos_.empty() || - static_cast<size_t>(base_level_) >= face_infos_[0].level_infos.size()) { + static_cast<size_t>(base_level_) >= MaxValidMipLevel()) { texture_complete_ = false; cube_complete_ = false; return; @@ -2025,8 +2025,7 @@ // the time. if (face_infos_.size() == 6 && !cube_complete()) return false; - DCHECK(level >= 0 && - level < static_cast<GLint>(face_infos_[0].level_infos.size())); + DCHECK(level >= 0 && level < static_cast<GLint>(MaxValidMipLevel())); if (level > base_level_ && !texture_complete()) { return false; } @@ -2061,7 +2060,7 @@ void Texture::ApplyFormatWorkarounds(const FeatureInfo* feature_info) { if (feature_info->gl_version_info().NeedsLuminanceAlphaEmulation()) { - if (static_cast<size_t>(base_level_) >= face_infos_[0].level_infos.size()) + if (static_cast<size_t>(base_level_) >= MaxValidMipLevel()) return; const Texture::LevelInfo& info = face_infos_[0].level_infos[base_level_]; SetCompatibilitySwizzle(GetCompatibilitySwizzleInternal(info.format)); @@ -2296,8 +2295,11 @@ return default_texture; } -bool TextureManager::ValidForTarget( - GLenum target, GLint level, GLsizei width, GLsizei height, GLsizei depth) { +bool TextureManager::ValidForTarget(GLenum target, + GLint level, + GLsizei width, + GLsizei height, + GLsizei depth) { if (level < 0 || level >= MaxLevelsForTarget(target)) return false; GLsizei max_size = MaxSizeForTarget(target) >> level; @@ -2317,6 +2319,18 @@ (target != GL_TEXTURE_2D || (depth == 1)); } +bool TextureManager::ValidForTextureTarget(const Texture* texture, + GLint level, + GLsizei width, + GLsizei height, + GLsizei depth) { + if (texture->target() == 0) + return false; + if (level < 0 || static_cast<size_t>(level) >= texture->MaxValidMipLevel()) + return false; + return ValidForTarget(texture->target(), level, width, height, depth); +} + void TextureManager::SetTarget(TextureRef* ref, GLenum target) { DCHECK(ref); ref->texture()->SetTarget(target, MaxLevelsForTarget(target)); @@ -2800,14 +2814,6 @@ args.internal_format, args.level)) { return false; } - if (!ValidForTarget(args.target, args.level, - args.width, args.height, args.depth) || - args.border != 0) { - ERRORSTATE_SET_GL_ERROR( - error_state, GL_INVALID_VALUE, function_name, - "dimensions out of range"); - return false; - } if ((GLES2Util::GetChannelsForFormat(args.format) & (GLES2Util::kDepth | GLES2Util::kStencil)) != 0 && args.pixels && !feature_info_->IsWebGL2OrES3Context()) { @@ -2830,7 +2836,13 @@ "texture is immutable"); return false; } - + if (!ValidForTextureTarget(local_texture_ref->texture(), args.level, + args.width, args.height, args.depth) || + args.border != 0) { + ERRORSTATE_SET_GL_ERROR(error_state, GL_INVALID_VALUE, function_name, + "dimensions out of range"); + return false; + } Buffer* buffer = state->bound_pixel_unpack_buffer.get(); if (buffer) { if (buffer->GetMappedRange()) {
diff --git a/gpu/command_buffer/service/texture_manager.h b/gpu/command_buffer/service/texture_manager.h index 341adcd..bf92c1b 100644 --- a/gpu/command_buffer/service/texture_manager.h +++ b/gpu/command_buffer/service/texture_manager.h
@@ -470,6 +470,11 @@ sampler_state_.min_filter != GL_LINEAR; } + size_t MaxValidMipLevel() const { + DCHECK(!face_infos_.empty()); + return face_infos_[0].level_infos.size(); + } + private: friend class MailboxManagerTest; friend class TextureManager; @@ -932,6 +937,11 @@ bool ValidForTarget( GLenum target, GLint level, GLsizei width, GLsizei height, GLsizei depth); + bool ValidForTextureTarget(const Texture* texture, + GLint level, + GLsizei width, + GLsizei height, + GLsizei depth); // True if this texture meets all the GLES2 criteria for rendering. // See section 3.8.2 of the GLES2 spec.
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index 797cde3..052c9f8 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -1120,14 +1120,12 @@ wire_server_->InjectInstance(dawn_instance_->Get(), 1, 0); - // If there is no isolation key provider (or unsafe webgpu is not enabled), we - // don't want to wait for an isolation key to come when processing device - // requests. Therefore, we can set the isolation key to an empty string to - // avoid blocking and disable caching in Dawn. Note that the isolation key - // provider is not available in some testing scenarios and the in-process - // command buffer case. - // TODO(dawn:549) Enable by default when tested and DocumentToken is used. - if (isolation_key_provider_ == nullptr || !enable_unsafe_webgpu_) { + // If there is no isolation key provider we don't want to wait for an + // isolation key to come when processing device requests. Therefore, we can + // set the isolation key to an empty string to avoid blocking and disable + // caching in Dawn. Note that the isolation key provider is not available in + // some testing scenarios and the in-process command buffer case. + if (isolation_key_provider_ == nullptr) { isolation_key_ = ""; } } @@ -1346,10 +1344,9 @@ if (!enable_unsafe_webgpu_) { force_enabled_toggles.push_back("disallow_spirv"); } - // Enable the blob cache only if we have an isolation key. - // TODO(dawn:549) Change the flag so that default is enabled. - if (enable_unsafe_webgpu_ && !isolation_key_->empty()) { - force_enabled_toggles.push_back("enable_blob_cache"); + // Disable the blob cache if we don't have an isolation key. + if (isolation_key_->empty()) { + force_enabled_toggles.push_back("disable_blob_cache"); } for (const std::string& toggles : force_enabled_toggles_) { @@ -1366,8 +1363,8 @@ desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&dawn_toggles); // Dawn caching isolation key information needs to be passed per device. If an - // isolation key is empty, we do not pass this extra descriptor to tell Dawn - // not to use the blob store caching. + // isolation key is empty, we do not pass this extra descriptor, and disable + // the blob cache via toggles above. WGPUDawnCacheDeviceDescriptor dawn_cache = {}; if (!isolation_key_->empty()) { dawn_cache.isolationKey = isolation_key_->c_str();
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory.cc b/gpu/ipc/service/gpu_memory_buffer_factory.cc index ac1ce80..235a17b 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory.cc +++ b/gpu/ipc/service/gpu_memory_buffer_factory.cc
@@ -29,7 +29,8 @@ // static std::unique_ptr<GpuMemoryBufferFactory> GpuMemoryBufferFactory::CreateNativeType( - viz::VulkanContextProvider* vulkan_context_provider) { + viz::VulkanContextProvider* vulkan_context_provider, + scoped_refptr<base::SingleThreadTaskRunner> io_runner) { #if BUILDFLAG(IS_MAC) return std::make_unique<GpuMemoryBufferFactoryIOSurface>(); #elif BUILDFLAG(IS_ANDROID) @@ -38,7 +39,7 @@ return std::make_unique<GpuMemoryBufferFactoryNativePixmap>( vulkan_context_provider); #elif BUILDFLAG(IS_WIN) - return std::make_unique<GpuMemoryBufferFactoryDXGI>(); + return std::make_unique<GpuMemoryBufferFactoryDXGI>(std::move(io_runner)); #else return nullptr; #endif
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory.h b/gpu/ipc/service/gpu_memory_buffer_factory.h index f762c97c..6a30604 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory.h +++ b/gpu/ipc/service/gpu_memory_buffer_factory.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/memory/unsafe_shared_memory_region.h" +#include "base/task/single_thread_task_runner.h" #include "gpu/ipc/common/surface_handle.h" #include "gpu/ipc/service/gpu_ipc_service_export.h" #include "ui/gfx/geometry/size.h" @@ -32,7 +33,8 @@ // Creates a new factory instance for native GPU memory buffers. Returns null // if native buffers are not supported. static std::unique_ptr<GpuMemoryBufferFactory> CreateNativeType( - viz::VulkanContextProvider* vulkan_context_provider); + viz::VulkanContextProvider* vulkan_context_provider, + scoped_refptr<base::SingleThreadTaskRunner> io_runner = nullptr); // Creates a new GPU memory buffer instance. A valid handle is returned on // success. This method is thread-safe but it should not be called on the IO
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc index db442b2..d3dee403 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc +++ b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
@@ -7,17 +7,22 @@ #include <vector> #include "base/memory/unsafe_shared_memory_region.h" +#include "base/synchronization/waitable_event.h" #include "base/trace_event/trace_event.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/ipc/common/dxgi_helpers.h" #include "ui/gfx/buffer_format_util.h" +#include "ui/gfx/buffer_types.h" +#include "ui/gfx/buffer_usage_util.h" #include "ui/gl/gl_angle_util_win.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_image_dxgi.h" namespace gpu { -GpuMemoryBufferFactoryDXGI::GpuMemoryBufferFactoryDXGI() { +GpuMemoryBufferFactoryDXGI::GpuMemoryBufferFactoryDXGI( + scoped_refptr<base::SingleThreadTaskRunner> io_runner) + : io_runner_(std::move(io_runner)) { DETACH_FROM_THREAD(thread_checker_); } GpuMemoryBufferFactoryDXGI::~GpuMemoryBufferFactoryDXGI() = default; @@ -26,7 +31,9 @@ // sharing keyed mutex state between DXGI GMBs and D3D shared image backings. Microsoft::WRL::ComPtr<ID3D11Device> GpuMemoryBufferFactoryDXGI::GetOrCreateD3D11Device() { + DCHECK(!io_runner_ || io_runner_->BelongsToCurrentThread()); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + if (!d3d11_device_ || FAILED(d3d11_device_->GetDeviceRemovedReason())) { // Reset device if it was removed. d3d11_device_ = nullptr; @@ -84,6 +91,43 @@ return d3d11_device_; } +gfx::GpuMemoryBufferHandle +GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBufferOnIO( + gfx::GpuMemoryBufferId id, + const gfx::Size& size, + const gfx::Size& framebuffer_size, + gfx::BufferFormat format, + gfx::BufferUsage usage, + int client_id, + SurfaceHandle surface_handle) { + DCHECK(io_runner_); + + gfx::GpuMemoryBufferHandle result; + base::WaitableEvent event; + + io_runner_->PostTask( + FROM_HERE, + base::BindOnce( + [](gfx::GpuMemoryBufferHandle* out_gmb_handle, + base::WaitableEvent* waitable_event, + GpuMemoryBufferFactoryDXGI* factory, gfx::GpuMemoryBufferId id, + const gfx::Size& size, const gfx::Size& framebuffer_size, + gfx::BufferFormat format, gfx::BufferUsage usage, int client_id, + SurfaceHandle surface_handle) { + *out_gmb_handle = factory->CreateGpuMemoryBuffer( + id, size, framebuffer_size, format, usage, client_id, + surface_handle); + + waitable_event->Signal(); + }, + &result, &event, this, id, size, framebuffer_size, format, usage, + client_id, surface_handle)); + + event.Wait(); + + return result; +} + gfx::GpuMemoryBufferHandle GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId id, const gfx::Size& size, @@ -92,6 +136,12 @@ gfx::BufferUsage usage, int client_id, SurfaceHandle surface_handle) { + if (io_runner_ && !io_runner_->BelongsToCurrentThread()) { + // Thread-hop is required! + return CreateGpuMemoryBufferOnIO(id, size, framebuffer_size, format, usage, + client_id, surface_handle); + } + TRACE_EVENT0("gpu", "GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer"); DCHECK_EQ(framebuffer_size, size); @@ -107,8 +157,12 @@ case gfx::BufferFormat::RGBX_8888: dxgi_format = DXGI_FORMAT_R8G8B8A8_UNORM; break; + case gfx::BufferFormat::YUV_420_BIPLANAR: + dxgi_format = DXGI_FORMAT_NV12; + break; default: - NOTREACHED(); + NOTREACHED() << "invalid buffer format, format=" + << gfx::BufferFormatToString(format); return handle; } @@ -119,7 +173,9 @@ // We are binding as a shader resource and render target regardless of usage, // so make sure that the usage is one that we support. DCHECK(usage == gfx::BufferUsage::GPU_READ || - usage == gfx::BufferUsage::SCANOUT); + usage == gfx::BufferUsage::SCANOUT || + usage == gfx::BufferUsage::SCANOUT_CPU_READ_WRITE) + << "Incorrect usage, usage=" << gfx::BufferUsageToString(usage); D3D11_TEXTURE2D_DESC desc = { static_cast<UINT>(size.width()),
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h index 8c28e9f..a4ed8e5 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h +++ b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h
@@ -9,14 +9,13 @@ #include <dxgi.h> #include <wrl/client.h> -#include "base/memory/ref_counted.h" -#include "base/synchronization/lock.h" +#include "base/memory/scoped_refptr.h" +#include "base/task/single_thread_task_runner.h" #include "base/threading/thread_checker.h" #include "gpu/command_buffer/service/image_factory.h" #include "gpu/ipc/service/gpu_ipc_service_export.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "ui/gfx/geometry/size.h" -#include "ui/gl/gl_image_dxgi.h" namespace gl { class GLImage; @@ -28,7 +27,14 @@ : public GpuMemoryBufferFactory, public ImageFactory { public: - GpuMemoryBufferFactoryDXGI(); + // Creates new instance of GpuMemoryBufferFactoryDXGI. `io_runner` is needed + // in order to create GpuMemoryBuffers on the correct thread. GpuServiceImpl + // calls into this class from IO runner (when processing IPC requests), so + // we need to ensure that other callers are able to thread-hop to that runner + // when creating GMBs (so far, the other caller for whom it matters is + // `FrameSinkVideoCapturerImpl` when running in GMB mode on Windows). + explicit GpuMemoryBufferFactoryDXGI( + scoped_refptr<base::SingleThreadTaskRunner> io_runner = nullptr); ~GpuMemoryBufferFactoryDXGI() override; GpuMemoryBufferFactoryDXGI(const GpuMemoryBufferFactoryDXGI&) = delete; @@ -66,9 +72,23 @@ private: Microsoft::WRL::ComPtr<ID3D11Device> GetOrCreateD3D11Device(); - Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_; + gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferOnIO( + gfx::GpuMemoryBufferId id, + const gfx::Size& size, + const gfx::Size& framebuffer_size, + gfx::BufferFormat format, + gfx::BufferUsage usage, + int client_id, + SurfaceHandle surface_handle); + + Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_ + GUARDED_BY_CONTEXT(thread_checker_); + Microsoft::WRL::ComPtr<ID3D11Texture2D> staging_texture_; + // May be null for testing: + scoped_refptr<base::SingleThreadTaskRunner> io_runner_; + THREAD_CHECKER(thread_checker_); };
diff --git a/headless/app/headless_shell_command_line.cc b/headless/app/headless_shell_command_line.cc index d15de03..a7d0b24 100644 --- a/headless/app/headless_shell_command_line.cc +++ b/headless/app/headless_shell_command_line.cc
@@ -215,6 +215,13 @@ return false; } + if (command_line.HasSwitch(switches::kHideScrollbars)) { + builder.SetOverrideWebPreferencesCallback( + base::BindRepeating([](blink::web_pref::WebPreferences* preferences) { + preferences->hide_scrollbars = true; + })); + } + if (command_line.HasSwitch(switches::kUserAgent)) { std::string user_agent = command_line.GetSwitchValueASCII(switches::kUserAgent);
diff --git a/headless/app/headless_shell_switches.cc b/headless/app/headless_shell_switches.cc index e2ddf46..f0d31a6 100644 --- a/headless/app/headless_shell_switches.cc +++ b/headless/app/headless_shell_switches.cc
@@ -41,6 +41,9 @@ // Instructs headless_shell to print document.body.innerHTML to stdout. const char kDumpDom[] = "dump-dom"; +// Hide scrollbars from screenshots. +const char kHideScrollbars[] = "hide-scrollbars"; + // Specifies which encryption storage backend to use. Possible values are // kwallet, kwallet5, gnome, gnome-keyring, gnome-libsecret, basic. Any other // value will lead to Chrome detecting the best backend automatically.
diff --git a/headless/app/headless_shell_switches.h b/headless/app/headless_shell_switches.h index 0d76074d..3f2456b3 100644 --- a/headless/app/headless_shell_switches.h +++ b/headless/app/headless_shell_switches.h
@@ -20,6 +20,7 @@ HEADLESS_EXPORT extern const char kDumpDom[]; HEADLESS_EXPORT extern const char kEnableBeginFrameControl[]; HEADLESS_EXPORT extern const char kEnableCrashReporter[]; +HEADLESS_EXPORT extern const char kHideScrollbars[]; HEADLESS_EXPORT extern const char kPasswordStore[]; HEADLESS_EXPORT extern const char kPrintToPDF[]; HEADLESS_EXPORT extern const char kPrintToPDFNoHeader[];
diff --git "a/infra/config/generated/builders/ci/Android arm64 Builder \050dbg\051/properties.json" "b/infra/config/generated/builders/ci/Android arm64 Builder \050dbg\051/properties.json" index 5228793..fc2ecb79 100644 --- "a/infra/config/generated/builders/ci/Android arm64 Builder \050dbg\051/properties.json" +++ "b/infra/config/generated/builders/ci/Android arm64 Builder \050dbg\051/properties.json"
@@ -150,42 +150,6 @@ { "builder_id": { "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android", - "enable_wpr_tests" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", "builder": "Nougat Phone Tester", "project": "chromium" }, @@ -315,11 +279,6 @@ }, { "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - { - "bucket": "ci", "builder": "Nougat Phone Tester", "project": "chromium" }, @@ -360,10 +319,6 @@ "group": "tryserver.chromium.android" }, { - "builder": "android_n5x_swarming_dbg", - "group": "tryserver.chromium.android" - }, - { "builder": "android_unswarmed_pixel_aosp", "group": "tryserver.chromium.android" },
diff --git a/infra/config/generated/builders/ci/Marshmallow 64 bit Tester/properties.json b/infra/config/generated/builders/ci/Marshmallow 64 bit Tester/properties.json deleted file mode 100644 index e8a8e060..0000000 --- a/infra/config/generated/builders/ci/Marshmallow 64 bit Tester/properties.json +++ /dev/null
@@ -1,102 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "COMPILE_AND_TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android", - "enable_wpr_tests" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - } - ], - "mirroring_builder_group_and_names": [ - { - "builder": "android_arm64_dbg_recipe", - "group": "tryserver.chromium.android" - }, - { - "builder": "android_n5x_swarming_dbg", - "group": "tryserver.chromium.android" - } - ] - } - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "chromium.android", - "recipe": "chromium" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/ci/Linux MSan Focal/properties.json b/infra/config/generated/builders/ci/mac-12-wpt-fyi-rel/properties.json similarity index 77% rename from infra/config/generated/builders/ci/Linux MSan Focal/properties.json rename to infra/config/generated/builders/ci/mac-12-wpt-fyi-rel/properties.json index 5fc9bed..979ecbe 100644 --- a/infra/config/generated/builders/ci/Linux MSan Focal/properties.json +++ b/infra/config/generated/builders/ci/mac-12-wpt-fyi-rel/properties.json
@@ -6,7 +6,7 @@ { "builder_id": { "bucket": "ci", - "builder": "Linux MSan Focal", + "builder": "mac-12-wpt-fyi-rel", "project": "chromium" }, "builder_spec": { @@ -17,7 +17,9 @@ "mb" ], "build_config": "Release", - "config": "chromium_msan" + "config": "chromium", + "target_bits": 64, + "target_platform": "mac" }, "legacy_gclient_config": { "config": "chromium" @@ -29,21 +31,15 @@ "builder_ids": [ { "bucket": "ci", - "builder": "Linux MSan Focal", + "builder": "mac-12-wpt-fyi-rel", "project": "chromium" } - ], - "mirroring_builder_group_and_names": [ - { - "builder": "linux_chromium_msan_focal", - "group": "tryserver.chromium.linux" - } ] } }, "$build/reclient": { "instance": "rbe-chromium-trusted", - "jobs": 500, + "jobs": 250, "metrics_project": "chromium-reclient-metrics" }, "$recipe_engine/resultdb/test_presentation": {
diff --git a/infra/config/generated/builders/try/android_arm64_dbg_recipe/properties.json b/infra/config/generated/builders/try/android_arm64_dbg_recipe/properties.json index e526690..4db1781 100644 --- a/infra/config/generated/builders/try/android_arm64_dbg_recipe/properties.json +++ b/infra/config/generated/builders/try/android_arm64_dbg_recipe/properties.json
@@ -150,42 +150,6 @@ { "builder_id": { "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android", - "enable_wpr_tests" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", "builder": "Nougat Phone Tester", "project": "chromium" }, @@ -315,11 +279,6 @@ }, { "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - { - "bucket": "ci", "builder": "Nougat Phone Tester", "project": "chromium" },
diff --git a/infra/config/generated/builders/try/android_n5x_swarming_dbg/properties.json b/infra/config/generated/builders/try/android_n5x_swarming_dbg/properties.json deleted file mode 100644 index 85e274cd..0000000 --- a/infra/config/generated/builders/try/android_n5x_swarming_dbg/properties.json +++ /dev/null
@@ -1,104 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "COMPILE_AND_TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android" - ], - "config": "chromium" - } - } - }, - { - "builder_id": { - "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - }, - "builder_spec": { - "build_gs_bucket": "chromium-android-archive", - "builder_group": "chromium.android", - "execution_mode": "TEST", - "legacy_android_config": { - "config": "main_builder_mb" - }, - "legacy_chromium_config": { - "apply_configs": [ - "download_vr_test_apks" - ], - "build_config": "Debug", - "config": "android", - "target_bits": 64, - "target_platform": "android" - }, - "legacy_gclient_config": { - "apply_configs": [ - "android", - "enable_wpr_tests" - ], - "config": "chromium" - }, - "parent": { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Android arm64 Builder (dbg)", - "project": "chromium" - } - ], - "builder_ids_in_scope_for_testing": [ - { - "bucket": "ci", - "builder": "Marshmallow 64 bit Tester", - "project": "chromium" - } - ] - } - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "jobs": 300, - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.android", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/linux_chromium_msan_focal/properties.json b/infra/config/generated/builders/try/linux_chromium_msan_focal/properties.json deleted file mode 100644 index 79e84aff..0000000 --- a/infra/config/generated/builders/try/linux_chromium_msan_focal/properties.json +++ /dev/null
@@ -1,52 +0,0 @@ -{ - "$build/chromium_tests_builder_config": { - "builder_config": { - "builder_db": { - "entries": [ - { - "builder_id": { - "bucket": "ci", - "builder": "Linux MSan Focal", - "project": "chromium" - }, - "builder_spec": { - "builder_group": "chromium.fyi", - "execution_mode": "COMPILE_AND_TEST", - "legacy_chromium_config": { - "apply_configs": [ - "mb" - ], - "build_config": "Release", - "config": "chromium_msan" - }, - "legacy_gclient_config": { - "config": "chromium" - } - } - } - ] - }, - "builder_ids": [ - { - "bucket": "ci", - "builder": "Linux MSan Focal", - "project": "chromium" - } - ] - } - }, - "$build/reclient": { - "instance": "rbe-chromium-untrusted", - "jobs": 300, - "metrics_project": "chromium-reclient-metrics" - }, - "$recipe_engine/resultdb/test_presentation": { - "column_keys": [], - "grouping_keys": [ - "status", - "v.test_suite" - ] - }, - "builder_group": "tryserver.chromium.linux", - "recipe": "chromium_trybot" -} \ No newline at end of file
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 11737688..6d2e34db 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -173,6 +173,10 @@ owner_whitelist_group: "project-chromium-robot-committers" } builders { + name: "chrome/try/linux-chromeos-compile-chrome" + includable_only: true + } + builders { name: "chrome/try/linux-nearby-chrome-fyi" includable_only: true owner_whitelist_group: "googlers" @@ -969,10 +973,6 @@ } } builders { - name: "chromium/try/android_n5x_swarming_dbg" - includable_only: true - } - builders { name: "chromium/try/android_optional_gpu_tests_rel" location_filters { gerrit_host_regexp: ".*" @@ -2970,10 +2970,6 @@ } } builders { - name: "chromium/try/linux_chromium_msan_focal" - includable_only: true - } - builders { name: "chromium/try/linux_chromium_msan_rel_ng" includable_only: true }
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 36f5a28..7a02dda 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -13839,7 +13839,7 @@ dimensions: "cores:8" dimensions: "cpu:x86-64" dimensions: "free_space:standard" - dimensions: "os:Ubuntu-18.04" + dimensions: "os:Ubuntu-20.04" dimensions: "pool:luci.chromium.ci" dimensions: "ssd:1" exe { @@ -13924,102 +13924,13 @@ } } builders { - name: "Linux MSan Focal" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "free_space:standard" - dimensions: "os:Ubuntu-20.04" - dimensions: "pool:luci.chromium.ci" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/ci/Linux MSan Focal/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "chromium.fyi",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium"' - '}' - priority: 35 - execution_timeout_secs: 57600 - build_numbers: YES - service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 100 - } - experiments { - key: "luci.buildbucket.omit_python2" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "ci_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_ci_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_ci_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { name: "Linux MSan Tests" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" dimensions: "cores:8" dimensions: "cpu:x86-64" dimensions: "free_space:standard" - dimensions: "os:Ubuntu-18.04" + dimensions: "os:Ubuntu-20.04" dimensions: "pool:luci.chromium.ci" dimensions: "ssd:0" exe { @@ -17967,94 +17878,6 @@ } } builders { - name: "Marshmallow 64 bit Tester" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "free_space:standard" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.ci" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/ci/Marshmallow 64 bit Tester/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "chromium.android",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium"' - '}' - execution_timeout_secs: 10800 - build_numbers: YES - service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 100 - } - experiments { - key: "luci.buildbucket.omit_python2" - value: 0 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "ci_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_ci_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_ci_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { name: "Network Service Linux" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" @@ -41361,6 +41184,93 @@ } } builders { + name: "mac-12-wpt-fyi-rel" + swarming_host: "chromium-swarm.appspot.com" + dimensions: "builder:mac-12-wpt-fyi-rel" + dimensions: "cores:4" + dimensions: "cpu:x86-64" + dimensions: "os:Mac-12" + dimensions: "pool:luci.chromium.ci" + exe { + cipd_package: "infra/chromium/bootstrapper/${platform}" + cipd_version: "latest" + cmd: "bootstrapper" + } + properties: + '{' + ' "$bootstrap/exe": {' + ' "exe": {' + ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' + ' "cipd_version": "refs/heads/main",' + ' "cmd": [' + ' "luciexe"' + ' ]' + ' }' + ' },' + ' "$bootstrap/properties": {' + ' "properties_file": "infra/config/generated/builders/ci/mac-12-wpt-fyi-rel/properties.json",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "chromium.fyi",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium"' + '}' + priority: 35 + execution_timeout_secs: 36000 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium_swarming.expose_merge_script_failures" + value: 100 + } + experiments { + key: "luci.buildbucket.omit_python2" + value: 100 + } + experiments { + key: "luci.recipes.use_python3" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_ci_test_results" + test_results { + predicate { + test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "mac-angle-chromium-amd" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" @@ -62188,116 +62098,6 @@ } } builders { - name: "android_n5x_swarming_dbg" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/android_n5x_swarming_dbg/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.android",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 14400 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 100 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.buildbucket.omit_python2" - value: 0 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { name: "android_optional_gpu_tests_rel" swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:android_optional_gpu_tests_rel" @@ -83648,122 +83448,12 @@ } } builders { - name: "linux_chromium_msan_focal" - swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" - dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-20.04" - dimensions: "pool:luci.chromium.try" - dimensions: "ssd:0" - exe { - cipd_package: "infra/chromium/bootstrapper/${platform}" - cipd_version: "latest" - cmd: "bootstrapper" - } - properties: - '{' - ' "$bootstrap/exe": {' - ' "exe": {' - ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' - ' "cipd_version": "refs/heads/main",' - ' "cmd": [' - ' "luciexe"' - ' ]' - ' }' - ' },' - ' "$bootstrap/properties": {' - ' "properties_file": "infra/config/generated/builders/try/linux_chromium_msan_focal/properties.json",' - ' "top_level_project": {' - ' "ref": "refs/heads/main",' - ' "repo": {' - ' "host": "chromium.googlesource.com",' - ' "project": "chromium/src"' - ' }' - ' }' - ' },' - ' "builder_group": "tryserver.chromium.linux",' - ' "led_builder_is_bootstrapped": true,' - ' "recipe": "chromium_trybot"' - '}' - execution_timeout_secs: 57600 - expiration_secs: 7200 - grace_period { - seconds: 120 - } - caches { - name: "win_toolchain" - path: "win_toolchain" - } - build_numbers: YES - service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" - task_template_canary_percentage { - value: 5 - } - experiments { - key: "chromium_swarming.expose_merge_script_failures" - value: 100 - } - experiments { - key: "enable_weetbix_queries" - value: 100 - } - experiments { - key: "luci.buildbucket.omit_python2" - value: 100 - } - experiments { - key: "luci.recipes.use_python3" - value: 100 - } - experiments { - key: "weetbix.enable_weetbix_exonerations" - value: 100 - } - experiments { - key: "weetbix.retry_weak_exonerations" - value: 100 - } - resultdb { - enable: true - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "try_test_results" - test_results {} - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "gpu_try_test_results" - test_results { - predicate { - test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" - } - } - } - bq_exports { - project: "chrome-luci-data" - dataset: "chromium" - table: "blink_web_tests_try_test_results" - test_results { - predicate { - test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" - } - } - } - history_options { - use_invocation_timestamp: true - } - } - } - builders { name: "linux_chromium_msan_rel_ng" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" + dimensions: "os:Ubuntu-20.04" dimensions: "pool:luci.chromium.try" dimensions: "ssd:0" exe {
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index a9d0d63..dab5f7a 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -1153,11 +1153,6 @@ short_name: "x86" } builders { - name: "buildbucket/luci.chromium.ci/Marshmallow 64 bit Tester" - category: "chromium.android|tester|phone" - short_name: "M" - } - builders { name: "buildbucket/luci.chromium.ci/Nougat Phone Tester" category: "chromium.android|tester|phone" short_name: "N" @@ -4381,11 +4376,6 @@ short_name: "size" } builders { - name: "buildbucket/luci.chromium.ci/Marshmallow 64 bit Tester" - category: "tester|phone" - short_name: "M" - } - builders { name: "buildbucket/luci.chromium.ci/Nougat Phone Tester" category: "tester|phone" short_name: "N" @@ -8368,6 +8358,10 @@ category: "mac" } builders { + name: "buildbucket/luci.chromium.ci/mac-12-wpt-fyi-rel" + category: "mac" + } + builders { name: "buildbucket/luci.chromium.ci/mac-fieldtrial-tester" category: "mac" } @@ -8751,11 +8745,6 @@ short_name: "crs" } builders { - name: "buildbucket/luci.chromium.ci/Linux MSan Focal" - category: "msan" - short_name: "lin" - } - builders { name: "buildbucket/luci.chromium.ci/linux-upload-perfetto" category: "perfetto" short_name: "lnx" @@ -16378,9 +16367,6 @@ name: "buildbucket/luci.chromium.try/android_cronet" } builders { - name: "buildbucket/luci.chromium.try/android_n5x_swarming_dbg" - } - builders { name: "buildbucket/luci.chromium.try/android_optional_gpu_tests_rel" } builders { @@ -16960,9 +16946,6 @@ name: "buildbucket/luci.chromium.try/linux_chromium_dbg_ng" } builders { - name: "buildbucket/luci.chromium.try/linux_chromium_msan_focal" - } - builders { name: "buildbucket/luci.chromium.try/linux_chromium_msan_rel_ng" } builders { @@ -17514,9 +17497,6 @@ name: "buildbucket/luci.chromium.try/android_cronet" } builders { - name: "buildbucket/luci.chromium.try/android_n5x_swarming_dbg" - } - builders { name: "buildbucket/luci.chromium.try/android_optional_gpu_tests_rel" } builders { @@ -17991,9 +17971,6 @@ name: "buildbucket/luci.chromium.try/linux_chromium_dbg_ng" } builders { - name: "buildbucket/luci.chromium.try/linux_chromium_msan_focal" - } - builders { name: "buildbucket/luci.chromium.try/linux_chromium_msan_rel_ng" } builders {
diff --git a/infra/config/generated/luci/luci-scheduler.cfg b/infra/config/generated/luci/luci-scheduler.cfg index 4ce6262..7017bb7 100644 --- a/infra/config/generated/luci/luci-scheduler.cfg +++ b/infra/config/generated/luci/luci-scheduler.cfg
@@ -1739,15 +1739,6 @@ } } job { - id: "Linux MSan Focal" - realm: "ci" - buildbucket { - server: "cr-buildbucket.appspot.com" - bucket: "ci" - builder: "Linux MSan Focal" - } -} -job { id: "Linux MSan Tests" realm: "ci" buildbucket { @@ -2227,15 +2218,6 @@ } } job { - id: "Marshmallow 64 bit Tester" - realm: "ci" - buildbucket { - server: "cr-buildbucket.appspot.com" - bucket: "ci" - builder: "Marshmallow 64 bit Tester" - } -} -job { id: "Network Service Linux" realm: "ci" buildbucket { @@ -5090,6 +5072,16 @@ } } job { + id: "mac-12-wpt-fyi-rel" + realm: "ci" + schedule: "triggered" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "ci" + builder: "mac-12-wpt-fyi-rel" + } +} +job { id: "mac-angle-chromium-amd" realm: "ci" buildbucket { @@ -5968,7 +5960,6 @@ triggers: "Linux ChromiumOS MSan Focal" triggers: "Linux FYI GPU TSAN Release" triggers: "Linux MSan Builder" - triggers: "Linux MSan Focal" triggers: "Linux TSan Builder" triggers: "Linux Viz" triggers: "MSAN Release (chained origins)"
diff --git a/infra/config/generated/luci/realms.cfg b/infra/config/generated/luci/realms.cfg index bb268efd..207584a3 100644 --- a/infra/config/generated/luci/realms.cfg +++ b/infra/config/generated/luci/realms.cfg
@@ -135,7 +135,6 @@ values: "Mac11 Tests" values: "Mac12 Tests" values: "Mac12 Tests (dbg)" - values: "Marshmallow 64 bit Tester" values: "Nougat Phone Tester" values: "Oreo Phone Tester" values: "WebKit Win10"
diff --git a/infra/config/subprojects/chromium/ci/chromium.android.star b/infra/config/subprojects/chromium/ci/chromium.android.star index 83222c4f..70cf8cbd8 100644 --- a/infra/config/subprojects/chromium/ci/chromium.android.star +++ b/infra/config/subprojects/chromium/ci/chromium.android.star
@@ -494,41 +494,6 @@ ) ci.thin_tester( - name = "Marshmallow 64 bit Tester", - branch_selector = branches.STANDARD_MILESTONE, - builder_spec = builder_config.builder_spec( - execution_mode = builder_config.execution_mode.TEST, - gclient_config = builder_config.gclient_config( - config = "chromium", - apply_configs = [ - "android", - "enable_wpr_tests", - ], - ), - chromium_config = builder_config.chromium_config( - config = "android", - apply_configs = [ - "download_vr_test_apks", - ], - build_config = builder_config.build_config.DEBUG, - target_bits = 64, - target_platform = builder_config.target_platform.ANDROID, - ), - android_config = builder_config.android_config( - config = "main_builder_mb", - ), - build_gs_bucket = "chromium-android-archive", - ), - console_view_entry = consoles.console_view_entry( - category = "tester|phone", - short_name = "M", - ), - cq_mirrors_console_view = "mirrors", - triggered_by = ["ci/Android arm64 Builder (dbg)"], - sheriff_rotations = args.ignore_default(None), -) - -ci.thin_tester( name = "Nougat Phone Tester", branch_selector = branches.STANDARD_MILESTONE, builder_spec = builder_config.builder_spec(
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index 38a976ea..f71d262 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -1503,6 +1503,30 @@ reclient_jobs = None, ) +fyi_mac_builder( + name = "mac-12-wpt-fyi-rel", + builderless = False, + console_view_entry = consoles.console_view_entry( + category = "mac", + ), + builder_spec = builder_config.builder_spec( + chromium_config = builder_config.chromium_config( + config = "chromium", + apply_configs = ["mb"], + build_config = builder_config.build_config.RELEASE, + target_bits = 64, + target_platform = builder_config.target_platform.MAC, + ), + gclient_config = builder_config.gclient_config( + config = "chromium", + ), + ), + # TODO(crbug.com/1385202): Enable scheduler when machine has been allocated. + schedule = "triggered", + triggered_by = [], + os = os.MAC_12, +) + ci.builder( name = "chromeos-amd64-generic-rel (reclient)", console_view_entry = consoles.console_view_entry( @@ -1927,32 +1951,6 @@ ci.builder( # An FYI version of the following builders that runs on Focal: - # https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Builder - # https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests - # TODO(crbug.com/1260217): Remove this builder when the main MSAN builder - # has migrated to focal. - name = "Linux MSan Focal", - builder_spec = builder_config.builder_spec( - gclient_config = builder_config.gclient_config( - config = "chromium", - ), - chromium_config = builder_config.chromium_config( - config = "chromium_msan", - apply_configs = ["mb"], - build_config = builder_config.build_config.RELEASE, - ), - ), - console_view_entry = consoles.console_view_entry( - category = "msan", - short_name = "lin", - ), - reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CI, - os = os.LINUX_FOCAL, - execution_timeout = 16 * time.hour, -) - -ci.builder( - # An FYI version of the following builders that runs on Focal: # https://ci.chromium.org/p/chromium/builders/ci/Linux%20ChromiumOS%20MSan%20Builder # https://ci.chromium.org/p/chromium/builders/ci/Linux%20ChromiumOS%20MSan%20Tests # TODO(crbug.com/1260217): Remove this builder when the main MSAN builder
diff --git a/infra/config/subprojects/chromium/ci/chromium.memory.star b/infra/config/subprojects/chromium/ci/chromium.memory.star index 950bfdba..5b7ad835 100644 --- a/infra/config/subprojects/chromium/ci/chromium.memory.star +++ b/infra/config/subprojects/chromium/ci/chromium.memory.star
@@ -321,6 +321,7 @@ short_name = "bld", ), ssd = True, + os = os.LINUX_FOCAL, ) linux_memory_builder( @@ -348,6 +349,7 @@ ), reclient_jobs = reclient.jobs.LOW_JOBS_FOR_CI, triggered_by = ["Linux MSan Builder"], + os = os.LINUX_FOCAL, ) linux_memory_builder(
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index b25783f..69174d6 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -151,15 +151,19 @@ def chrome_internal_verifier( *, builder, + include_owner_whitelist = True, **kwargs): + owner_whitelist = [] + if include_owner_whitelist: + owner_whitelist = [ + "googlers", + "project-chromium-robot-committers", + ] branches.cq_tryjob_verifier( builder = "{}:try/{}".format(settings.chrome_project, builder), cq_group = "cq", includable_only = True, - owner_whitelist = [ - "googlers", - "project-chromium-robot-committers", - ], + owner_whitelist = owner_whitelist, **kwargs ) @@ -277,6 +281,13 @@ ) chrome_internal_verifier( + builder = "linux-chromeos-compile-chrome", + # We skip the owner_whitelist here since the recipe it runs enforces the + # restrictions outlined in http://shortn/_ulOm5v8gA2. + include_owner_whitelist = False, +) + +chrome_internal_verifier( builder = "linux-nearby-chrome-fyi", )
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star index cb71c99a2..8197d6d 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star
@@ -706,15 +706,6 @@ ) try_.builder( - name = "android_n5x_swarming_dbg", - mirrors = [ - "ci/Android arm64 Builder (dbg)", - "ci/Marshmallow 64 bit Tester", - ], - goma_backend = None, -) - -try_.builder( name = "android_unswarmed_pixel_aosp", mirrors = [ "ci/Android arm64 Builder (dbg)",
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star index 16d0759..f0762a5 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star
@@ -522,17 +522,6 @@ ) try_.builder( - name = "linux_chromium_msan_focal", - mirrors = [ - "ci/Linux MSan Focal", - ], - execution_timeout = 16 * time.hour, - goma_backend = None, - os = os.LINUX_FOCAL, - reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CQ, -) - -try_.builder( name = "linux_chromium_msan_rel_ng", mirrors = [ "ci/Linux MSan Builder", @@ -540,6 +529,7 @@ ], execution_timeout = 6 * time.hour, goma_backend = None, + os = os.LINUX_FOCAL, reclient_jobs = reclient.jobs.HIGH_JOBS_FOR_CQ, )
diff --git a/media/gpu/sandbox/BUILD.gn b/media/gpu/sandbox/BUILD.gn index c7a9bd11..cfcb7fa 100644 --- a/media/gpu/sandbox/BUILD.gn +++ b/media/gpu/sandbox/BUILD.gn
@@ -30,4 +30,9 @@ if (use_v4l2_codec) { deps += [ "//media/gpu/v4l2" ] } + if (current_cpu != "s390x" && current_cpu != "ppc64" && is_linux && + !is_castos) { + # For DRI_DRIVER_DIR. + configs += [ "//build/config/linux/dri" ] + } }
diff --git a/media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.cc b/media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.cc index b8fd522b..c8bf0192 100644 --- a/media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.cc +++ b/media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.cc
@@ -9,6 +9,7 @@ #include "base/strings/stringprintf.h" #include "media/gpu/buildflags.h" +#include "sandbox/policy/linux/bpf_hardware_video_decoding_policy_linux.h" #if BUILDFLAG(USE_VAAPI) #include "media/gpu/vaapi/vaapi_wrapper.h" @@ -16,21 +17,111 @@ using sandbox::syscall_broker::BrokerFilePermission; +// TODO(b/195769334): the hardware video decoding sandbox is really only useful +// when building with VA-API or V4L2 (otherwise, we're not really doing hardware +// video decoding). Consider restricting the kHardwareVideoDecoding sandbox type +// to exist only in those configurations so that the presandbox hook is only +// compiled in those scenarios. As it is now, kHardwareVideoDecoding exists for +// all ash-chrome builds because +// chrome/browser/ash/arc/video/gpu_arc_video_service_host.cc depends on it and +// that file is built for ash-chrome regardless of VA-API/V4L2. That means that +// bots like linux-chromeos-rel end up compiling this presandbox hook (thus the +// NOTREACHED()s in some places here). + namespace media { +namespace { -bool HardwareVideoDecodingPreSandboxHook( - sandbox::policy::SandboxLinux::Options options) { - sandbox::syscall_broker::BrokerCommandSet command_set; - std::vector<BrokerFilePermission> permissions; +void AllowAccessToRenderNodes(std::vector<BrokerFilePermission>& permissions, + bool include_sys_dev_char, + bool read_write) { + for (int i = 128; i <= 137; ++i) { + const std::string path = base::StringPrintf("/dev/dri/renderD%d", i); + struct stat st; + if (stat(path.c_str(), &st) == 0) { + permissions.push_back(read_write ? BrokerFilePermission::ReadWrite(path) + : BrokerFilePermission::ReadOnly(path)); + if (include_sys_dev_char) { + uint32_t major = (static_cast<uint32_t>(st.st_rdev) >> 8) & 0xff; + uint32_t minor = static_cast<uint32_t>(st.st_rdev) & 0xff; + std::string char_device_path = + base::StringPrintf("/sys/dev/char/%u:%u/", major, minor); + permissions.push_back( + BrokerFilePermission::ReadOnlyRecursive(char_device_path)); + } + } + } +} + +bool HardwareVideoDecodingPreSandboxHookForVaapiOnIntel( + sandbox::syscall_broker::BrokerCommandSet& command_set, + std::vector<BrokerFilePermission>& permissions) { +#if BUILDFLAG(IS_CHROMEOS_ASH) + // This should only be needed in order for GbmDeviceWrapper in + // platform_video_frame_utils.cc to be able to initialize minigbm after + // entering the sandbox. Since minigbm is only needed for buffer allocation on + // ash-chrome, we restrict this to that platform. + // + // TODO(b/210759684): we should open the render nodes for both libva and + // minigbm before entering the sandbox so that we can remove this permission. + command_set.set(sandbox::syscall_broker::COMMAND_OPEN); + AllowAccessToRenderNodes(permissions, /*include_sys_dev_char=*/false, + /*read_write=*/false); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if BUILDFLAG(USE_VAAPI) + VaapiWrapper::PreSandboxInitialization(); + return true; +#else + NOTREACHED(); + return false; +#endif // BUILDFLAG(USE_VAAPI) +} + +bool HardwareVideoDecodingPreSandboxHookForVaapiOnAMD( + sandbox::syscall_broker::BrokerCommandSet& command_set, + std::vector<BrokerFilePermission>& permissions) { + command_set.set(sandbox::syscall_broker::COMMAND_OPEN); + command_set.set(sandbox::syscall_broker::COMMAND_STAT); + command_set.set(sandbox::syscall_broker::COMMAND_READLINK); + + AllowAccessToRenderNodes(permissions, /*include_sys_dev_char=*/true, + /*read_write=*/true); + permissions.push_back(BrokerFilePermission::ReadOnly("/dev/dri")); + + const char* radeonsi_lib = "/usr/lib64/dri/radeonsi_dri.so"; +#if defined(DRI_DRIVER_DIR) + radeonsi_lib = DRI_DRIVER_DIR "/radeonsi_dri.so"; +#endif + if (nullptr == dlopen(radeonsi_lib, RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE)) { + LOG(ERROR) << "dlopen(radeonsi_dri.so) failed with error: " << dlerror(); + return false; + } + +#if BUILDFLAG(USE_VAAPI) + VaapiWrapper::PreSandboxInitialization(); + return true; +#else + NOTREACHED(); + return false; +#endif // BUILDFLAG(USE_VAAPI) +} + +bool HardwareVideoDecodingPreSandboxHookForV4L2( + sandbox::syscall_broker::BrokerCommandSet& command_set, + std::vector<BrokerFilePermission>& permissions) { #if BUILDFLAG(USE_V4L2_CODEC) command_set.set(sandbox::syscall_broker::COMMAND_OPEN); + // TODO(b/210759684): we should open the render node for minigbm before + // entering the sandbox so that we can remove this permission. + AllowAccessToRenderNodes(permissions, /*include_sys_dev_char=*/false, + /*read_write=*/false); + // Device nodes for V4L2 video decode accelerator drivers. - // We do not use a FileEnumerator because the device files may not exist - // yet when the sandbox is created. But since we are restricting access - // to the video-dec* and media-dec* prefixes we know that we cannot - // authorize a non-decoder device by accident. + // We do not use a FileEnumerator because the device files may not exist yet + // when the sandbox is created. But since we are restricting access to the + // video-dec* and media-dec* prefixes we know that we cannot authorize a + // non-decoder device by accident. static constexpr size_t MAX_V4L2_DECODERS = 5; static const base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/dev/"); @@ -53,80 +144,74 @@ // platforms that need it. static const char kDevImageProc0Path[] = "/dev/image-proc0"; permissions.push_back(BrokerFilePermission::ReadWrite(kDevImageProc0Path)); -#elif BUILDFLAG(USE_VAAPI) - command_set.set(sandbox::syscall_broker::COMMAND_OPEN); - if (options.use_amd_specific_policies) { - command_set.set(sandbox::syscall_broker::COMMAND_ACCESS); - command_set.set(sandbox::syscall_broker::COMMAND_STAT); - command_set.set(sandbox::syscall_broker::COMMAND_READLINK); - - permissions.push_back(BrokerFilePermission::ReadOnly("/dev/dri")); - - static const char* kDevices[] = {"/sys/dev/char", "/sys/devices"}; - for (const char* item : kDevices) { - std::string path(item); - permissions.push_back( - BrokerFilePermission::StatOnlyWithIntermediateDirs(path)); - permissions.push_back( - BrokerFilePermission::ReadOnlyRecursive(path + "/")); - } - } -#endif - - // TODO(b/195769334): consider using the type of client to decide if we should - // allow access to the render node: - // - // - If the client is ARC++/ARCVM, the render node is only needed for two - // cases, the legacy VaapiVideoDecodeAccelerator and AMD. - // - // - If the client is a Chrome renderer process, the render node is needed on - // ChromeOS to allocate output buffers. - for (int i = 128; i <= 137; ++i) { - const std::string path = base::StringPrintf("/dev/dri/renderD%d", i); - struct stat st; - if (stat(path.c_str(), &st) == 0) { - permissions.push_back(options.use_amd_specific_policies - ? BrokerFilePermission::ReadWrite(path) - : BrokerFilePermission::ReadOnly(path)); - } - } - - sandbox::policy::SandboxLinux::GetInstance()->StartBrokerProcess( - command_set, permissions, sandbox::policy::SandboxLinux::PreSandboxHook(), - options); - - // TODO(b/195769334): the hardware video decoding sandbox is really only - // useful when building with VA-API or V4L2 (otherwise, we're not really doing - // hardware video decoding). Consider restricting the kHardwareVideoDecoding - // sandbox type to exist only in those configurations so that the presandbox - // hook is only reached in those scenarios. As it is now, - // kHardwareVideoDecoding exists for all ash-chrome builds because - // chrome/browser/ash/arc/video/gpu_arc_video_service_host.cc depends on it - // and that file is built for ash-chrome regardless of VA-API/V4L2. That means - // that bots like linux-chromeos-rel end up reaching this presandbox hook. -#if BUILDFLAG(USE_VAAPI) - VaapiWrapper::PreSandboxInitialization(); - - if (options.use_amd_specific_policies) { - const char* radeonsi_lib = "/usr/lib64/dri/radeonsi_dri.so"; -#if defined(DRI_DRIVER_DIR) - radeonsi_lib = DRI_DRIVER_DIR "/radeonsi_dri.so"; -#endif - if (nullptr == - dlopen(radeonsi_lib, RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE)) { - LOG(ERROR) << "dlopen(radeonsi_dri.so) failed with error: " << dlerror(); - return false; - } - } -#elif BUILDFLAG(USE_V4L2_CODEC) && BUILDFLAG(USE_LIBV4L2) + // Some platforms (RK3399) need libv4l2 to interact with the kernel V4L2 + // driver, so we need to load that library prior to entering the sandbox. +#if BUILDFLAG(USE_LIBV4L2) #if defined(__aarch64__) dlopen("/usr/lib64/libv4l2.so", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); #else dlopen("/usr/lib/libv4l2.so", RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE); #endif // defined(__aarch64__) -#endif +#endif // BUILDFLAG(USE_LIBV4L2) + return true; +#else + NOTREACHED(); + return false; +#endif // BUILDFLAG(USE_V4L2_CODEC) +} +} // namespace + +// TODO(b/195769334): consider using the type of client to decide if we should +// allow opening the render node after entering the sandbox: +// +// - If the client is ARC++/ARCVM, the render node only needs to be opened after +// entering the sandbox for two cases: the legacy VaapiVideoDecodeAccelerator +// and AMD. +// +// - If the client is a Chrome renderer process, the render node needs to be +// opened after entering the sandbox on ChromeOS to allocate output buffers +// (at least). +bool HardwareVideoDecodingPreSandboxHook( + sandbox::policy::SandboxLinux::Options options) { + using HardwareVideoDecodingProcessPolicy = + sandbox::policy::HardwareVideoDecodingProcessPolicy; + using PolicyType = + sandbox::policy::HardwareVideoDecodingProcessPolicy::PolicyType; + + const PolicyType policy_type = + HardwareVideoDecodingProcessPolicy::ComputePolicyType( + options.use_amd_specific_policies); + + sandbox::syscall_broker::BrokerCommandSet command_set; + std::vector<BrokerFilePermission> permissions; + + bool result_for_platform_policy; + switch (policy_type) { + case PolicyType::kVaapiOnIntel: + result_for_platform_policy = + HardwareVideoDecodingPreSandboxHookForVaapiOnIntel(command_set, + permissions); + break; + case PolicyType::kVaapiOnAMD: + result_for_platform_policy = + HardwareVideoDecodingPreSandboxHookForVaapiOnAMD(command_set, + permissions); + break; + case PolicyType::kV4L2: + result_for_platform_policy = + HardwareVideoDecodingPreSandboxHookForV4L2(command_set, permissions); + break; + } + if (!result_for_platform_policy) + return false; + + // TODO(b/210759684): should this still be called if |command_set| or + // |permissions| is empty? + sandbox::policy::SandboxLinux::GetInstance()->StartBrokerProcess( + command_set, permissions, sandbox::policy::SandboxLinux::PreSandboxHook(), + options); return true; }
diff --git a/media/gpu/v4l2/test/av1_decoder.cc b/media/gpu/v4l2/test/av1_decoder.cc index 63aced0c..b9d9cff 100644 --- a/media/gpu/v4l2/test/av1_decoder.cc +++ b/media/gpu/v4l2/test/av1_decoder.cc
@@ -878,32 +878,32 @@ } std::set<int> Av1Decoder::RefreshReferenceSlots( - const uint8_t refresh_frame_flags, + const libgav1::ObuFrameHeader& frame_hdr, const libgav1::RefCountedBufferPtr current_frame, const scoped_refptr<MmapedBuffer> buffer, - const uint32_t last_queued_buffer_index, - const uint8_t order_hint) { - state_->UpdateReferenceFrames(current_frame, - base::strict_cast<int>(refresh_frame_flags)); + const uint32_t last_queued_buffer_index) { + state_->UpdateReferenceFrames( + current_frame, base::strict_cast<int>(frame_hdr.refresh_frame_flags)); static_assert( - kAv1NumRefFrames == sizeof(refresh_frame_flags) * CHAR_BIT, + kAv1NumRefFrames == sizeof(frame_hdr.refresh_frame_flags) * CHAR_BIT, "|refresh_frame_flags| size must be equal to |kAv1NumRefFrames|"); - const std::bitset<kAv1NumRefFrames> refresh_frame_slots(refresh_frame_flags); + const std::bitset<kAv1NumRefFrames> refresh_frame_slots( + frame_hdr.refresh_frame_flags); std::set<int> reusable_buffer_ids; - constexpr uint8_t kRefreshFrameFlagsNone = 0; - if (refresh_frame_flags == kRefreshFrameFlagsNone) { - // Indicates to reuse currently decoded CAPTURE buffer. - reusable_buffer_ids.insert(buffer->buffer_id()); - - return reusable_buffer_ids; - } - constexpr uint8_t kRefreshFrameFlagsAll = 0xFF; - if (refresh_frame_flags == kRefreshFrameFlagsAll) { + // If |show_existing_frame| = 1 and the frame to show is a key frame, the + // reference frame loading process as specified in section 7.21 of the AV1 + // spec is invoked. + const bool is_show_existing_key_frame = + (frame_hdr.show_existing_frame && + (state_->reference_frame[frame_hdr.frame_to_show]->frame_type() == + libgav1::kFrameKey)); + if (frame_hdr.refresh_frame_flags == kRefreshFrameFlagsAll || + is_show_existing_key_frame) { // After decoding a key frame, all CAPTURE buffers can be reused except the // CAPTURE buffer corresponding to the key frame. for (size_t i = 0; i < kNumberOfBuffersInCaptureQueue; i++) @@ -919,8 +919,18 @@ // reference frame slots in the reference frames list. ref_frames_.fill(buffer); - // TODO(b/249104479): Update |ref_order_hint_| as needed for all reference - // frame slots after finding relevant test vector + if (is_show_existing_key_frame) { + for (size_t i = 0; i < libgav1::kNumReferenceFrameTypes; i++) + ref_order_hint_[i] = ref_order_hint_[frame_hdr.frame_to_show]; + } + + return reusable_buffer_ids; + } + + constexpr uint8_t kRefreshFrameFlagsNone = 0; + if (frame_hdr.refresh_frame_flags == kRefreshFrameFlagsNone) { + // Indicates to reuse currently decoded CAPTURE buffer. + reusable_buffer_ids.insert(buffer->buffer_id()); return reusable_buffer_ids; } @@ -952,12 +962,24 @@ } } ref_frames_[i] = buffer; - ref_order_hint_[i] = order_hint; + ref_order_hint_[i] = frame_hdr.order_hint; } return reusable_buffer_ids; } +void Av1Decoder::QueueReusableBuffersInCaptureQueue( + const std::set<int> reusable_buffer_ids, + const bool is_inter_frame) { + for (const auto reusable_buffer_id : reusable_buffer_ids) { + if (!v4l2_ioctl_->QBuf(CAPTURE_queue_, reusable_buffer_id)) + LOG(ERROR) << "VIDIOC_QBUF failed for CAPTURE queue."; + + if (is_inter_frame) + CAPTURE_queue_->set_last_queued_buffer_index(reusable_buffer_id); + } +} + VideoDecoder::Result Av1Decoder::DecodeNextFrame(std::vector<char>& y_plane, std::vector<char>& u_plane, std::vector<char>& v_plane, @@ -1008,6 +1030,22 @@ repeated_frame_buffer->mmaped_planes()[1].start_addr), CAPTURE_queue_->coded_size()); + // Repeated frames normally don't need to update reference frames. But in + // this special case when the repeated frame is pointing to a key frame, all + // the reference frames have to be updated to the key frame pointed by the + // repeated frame. + if (state_->reference_frame[current_frame_header.frame_to_show] + ->frame_type() == libgav1::kFrameKey) { + const std::set<int> reusable_buffer_ids = + RefreshReferenceSlots(current_frame_header, current_frame, + ref_frames_[current_frame_header.frame_to_show], + CAPTURE_queue_->last_queued_buffer_index()); + + QueueReusableBuffersInCaptureQueue( + reusable_buffer_ids, + !libgav1::IsIntraFrame(current_frame_header.frame_type)); + } + return VideoDecoder::kOk; } @@ -1079,19 +1117,13 @@ static_cast<char*>(buffer->mmaped_planes()[1].start_addr), CAPTURE_queue_->coded_size()); - const std::set<int> reusable_buffer_ids = - RefreshReferenceSlots(current_frame_header.refresh_frame_flags, - current_frame, CAPTURE_queue_->GetBuffer(index), - CAPTURE_queue_->last_queued_buffer_index(), - current_frame_header.order_hint); + const std::set<int> reusable_buffer_ids = RefreshReferenceSlots( + current_frame_header, current_frame, CAPTURE_queue_->GetBuffer(index), + CAPTURE_queue_->last_queued_buffer_index()); - for (const auto reusable_buffer_id : reusable_buffer_ids) { - if (!v4l2_ioctl_->QBuf(CAPTURE_queue_, reusable_buffer_id)) - LOG(ERROR) << "VIDIOC_QBUF failed for CAPTURE queue."; - - if (!libgav1::IsIntraFrame(current_frame_header.frame_type)) - CAPTURE_queue_->set_last_queued_buffer_index(reusable_buffer_id); - } + QueueReusableBuffersInCaptureQueue( + reusable_buffer_ids, + !libgav1::IsIntraFrame(current_frame_header.frame_type)); if (!v4l2_ioctl_->DQBuf(OUTPUT_queue_, &index)) LOG(FATAL) << "VIDIOC_DQBUF failed for OUTPUT queue.";
diff --git a/media/gpu/v4l2/test/av1_decoder.h b/media/gpu/v4l2/test/av1_decoder.h index 61e570d..79ac8e8 100644 --- a/media/gpu/v4l2/test/av1_decoder.h +++ b/media/gpu/v4l2/test/av1_decoder.h
@@ -94,11 +94,17 @@ // Returns |reusable_buffer_slots| to indicate which CAPTURE buffers can be // reused for VIDIOC_QBUF ioctl call. std::set<int> RefreshReferenceSlots( - const uint8_t refresh_frame_flags, + const libgav1::ObuFrameHeader& frame_hdr, const libgav1::RefCountedBufferPtr current_frame, const scoped_refptr<MmapedBuffer> buffer, - const uint32_t last_queued_buffer_index, - const uint8_t order_hint); + const uint32_t last_queued_buffer_index); + + // Queues reusable buffers in CAPTURE queue, indicated by + // |reusable_buffer_ids|. Saves buffer ids for inter frames to prevent + // unnecessary QBUF attempts. + void QueueReusableBuffersInCaptureQueue( + const std::set<int> reusable_buffer_ids, + const bool is_inter_frame); // Reference frames currently in use. std::array<scoped_refptr<MmapedBuffer>, kAv1NumRefFrames> ref_frames_;
diff --git a/media/mojo/mojom/speech_recognition_service.mojom b/media/mojo/mojom/speech_recognition_service.mojom index 5f8bb51..5c183c5 100644 --- a/media/mojo/mojom/speech_recognition_service.mojom +++ b/media/mojo/mojom/speech_recognition_service.mojom
@@ -42,10 +42,11 @@ BindAudioSourceSpeechRecognitionContext( pending_receiver<AudioSourceSpeechRecognitionContext> context); - // Sets the file path to the Speech On-Device API (SODA) binary and - // the config file for the language pack. - SetSodaPath(mojo_base.mojom.FilePath binary_path, - mojo_base.mojom.FilePath config_path); + // Sets the file path to the Speech On-Device API (SODA) binary, the config + // file paths for the language packs, and the primary language name. + SetSodaPaths(mojo_base.mojom.FilePath binary_path, + map<string, mojo_base.mojom.FilePath> config_paths, + string primary_language_name); }; // The interface used to start and stop fetching audio from the microphone
diff --git a/mojo/public/cpp/bindings/interface_endpoint_client.h b/mojo/public/cpp/bindings/interface_endpoint_client.h index 773a6188..8b92c3b 100644 --- a/mojo/public/cpp/bindings/interface_endpoint_client.h +++ b/mojo/public/cpp/bindings/interface_endpoint_client.h
@@ -72,27 +72,27 @@ // Sets the error handler to receive notifications when an error is // encountered. void set_connection_error_handler(base::OnceClosure error_handler) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); error_handler_ = std::move(error_handler); error_with_reason_handler_.Reset(); } void set_connection_error_with_reason_handler( ConnectionErrorWithReasonCallback error_handler) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); error_with_reason_handler_ = std::move(error_handler); error_handler_.Reset(); } // Returns true if an error was encountered. bool encountered_error() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); return encountered_error_; } // Returns true if this endpoint has any pending callbacks. bool has_pending_responders() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); base::AutoLock lock(async_responders_lock_); return !async_responders_.empty() || !sync_responses_.empty(); } @@ -354,7 +354,9 @@ base::Location next_call_location_; #endif - SEQUENCE_CHECKER(sequence_checker_); + // We use SequenceCheckerImpl directly, to assert some sequence checks even in + // release builds. See https://crbug.com/1325096. + base::SequenceCheckerImpl sequence_checker_; base::WeakPtrFactory<InterfaceEndpointClient> weak_ptr_factory_{this}; };
diff --git a/mojo/public/cpp/bindings/lib/interface_endpoint_client.cc b/mojo/public/cpp/bindings/lib/interface_endpoint_client.cc index a330769..c9f840b 100644 --- a/mojo/public/cpp/bindings/lib/interface_endpoint_client.cc +++ b/mojo/public/cpp/bindings/lib/interface_endpoint_client.cc
@@ -459,7 +459,7 @@ method_info_callback_(method_info_callback), method_name_callback_(method_name_callback) { DCHECK(handle_.is_valid()); - DETACH_FROM_SEQUENCE(sequence_checker_); + sequence_checker_.DetachFromSequence(); // TODO(yzshen): the way to use validator (or message filter in general) // directly is a little awkward. @@ -483,7 +483,7 @@ } InterfaceEndpointClient::~InterfaceEndpointClient() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); if (controller_) handle_.group_controller()->DetachEndpointClient(handle_); } @@ -502,7 +502,7 @@ } ScopedInterfaceEndpointHandle InterfaceEndpointClient::PassHandle() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); DCHECK(!has_pending_responders()); if (!handle_.is_valid()) @@ -524,7 +524,7 @@ } void InterfaceEndpointClient::RaiseError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); if (!handle_.pending_association()) handle_.group_controller()->RaiseError(); @@ -532,7 +532,7 @@ void InterfaceEndpointClient::CloseWithReason(uint32_t custom_reason, base::StringPiece description) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); auto handle = PassHandle(); handle.ResetWithReason(custom_reason, description); @@ -568,7 +568,7 @@ bool InterfaceEndpointClient::SendMessage(Message* message, bool is_control_message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); DCHECK(!message->has_flag(Message::kFlagExpectsResponse)); DCHECK(!handle_.pending_association()); @@ -604,7 +604,7 @@ bool is_control_message, SyncSendMode sync_send_mode, std::unique_ptr<MessageReceiver> responder) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); DCHECK(message->has_flag(Message::kFlagExpectsResponse)); DCHECK(!handle_.pending_association()); @@ -685,7 +685,7 @@ } bool InterfaceEndpointClient::HandleIncomingMessage(Message* message) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); // Accept() may invalidate `this` and `message` so we need to copy the // members we need for logging in case of an error. @@ -708,7 +708,7 @@ info->set_mojo_interface_tag(interface_name_); }); - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK(sequence_checker_.CalledOnValidSequence()); if (encountered_error_) return; @@ -831,7 +831,7 @@ } void InterfaceEndpointClient::ResetFromAnotherSequenceUnsafe() { - DETACH_FROM_SEQUENCE(sequence_checker_); + sequence_checker_.DetachFromSequence(); if (controller_) { controller_ = nullptr;
diff --git a/mojo/public/tools/bindings/generators/OWNERS b/mojo/public/tools/bindings/generators/OWNERS new file mode 100644 index 0000000..fb33ab8 --- /dev/null +++ b/mojo/public/tools/bindings/generators/OWNERS
@@ -0,0 +1,2 @@ +# TypeScript bindings generator +per-file mojom_ts_generator.py=rbpotter@chromium.org
diff --git a/mojo/public/tools/bindings/generators/mojom_ts_generator.py b/mojo/public/tools/bindings/generators/mojom_ts_generator.py index 5162d5b..8ee12d63 100644 --- a/mojo/public/tools/bindings/generators/mojom_ts_generator.py +++ b/mojo/public/tools/bindings/generators/mojom_ts_generator.py
@@ -5,7 +5,6 @@ import mojom.generate.generator as generator import mojom.generate.module as mojom -import mojom.generate.pack as pack import os import sys import urllib.request @@ -39,7 +38,7 @@ mojom.NULLABLE_STRING: "null" } -_kind_to_closure_type = { +_kind_to_ts_type = { mojom.BOOL: "boolean", mojom.INT8: "number", mojom.UINT8: "number", @@ -48,8 +47,8 @@ mojom.INT32: "number", mojom.UINT32: "number", mojom.FLOAT: "number", - mojom.INT64: "number", - mojom.UINT64: "number", + mojom.INT64: "bigint", + mojom.UINT64: "bigint", mojom.DOUBLE: "number", mojom.STRING: "string", mojom.NULLABLE_STRING: "string", @@ -163,7 +162,7 @@ return '/{}/'.format(path.strip('/')) -class JavaScriptStylizer(generator.Stylizer): +class TypeScriptStylizer(generator.Stylizer): def StylizeConstant(self, mojom_name): return generator.ToUpperSnakeCase(mojom_name) @@ -226,21 +225,17 @@ return "ts_templates" def GetFilters(self): - js_filters = { + ts_filters = { "constant_value": self._GetConstantValue, - "constant_value_in_js_module": self._GetConstantValueInJsModule, - "default_value": self._JavaScriptDefaultValue, - "default_value_in_js_module": self._DefaultValueInJsModule, - "field_type_in_js_module": self._GetFieldTypeInJsModule, + "default_ts_value": self._GetDefaultValue, "imports_for_kind": self._GetImportsForKind, "is_bool_kind": mojom.IsBoolKind, - "spec_type_in_js_module": self._GetSpecTypeInJsModule, - "type_in_js_module": self._GetTypeInJsModule, - "type_in_js_module_with_nullability": - self._GetTypeInJsModuleWithNullability, - "sanitize_identifier": self._JavaScriptSanitizeIdentifier, + "spec_type": self._GetSpecType, + "ts_type": self._TypescriptType, + "ts_type_maybe_nullable": self._TypescriptTypeMaybeNullable, + "sanitize_identifier": self._TypeScriptSanitizeIdentifier, } - return js_filters + return ts_filters @UseJinja("module_definition.tmpl") def _GenerateWebUiModule(self): @@ -250,7 +245,7 @@ if self.variant: raise Exception("Variants not supported in JavaScript bindings.") - self.module.Stylize(JavaScriptStylizer()) + self.module.Stylize(TypeScriptStylizer()) # TODO(crbug.com/795977): Change the media router extension to not mess with # the mojo namespace, so that namespaces such as "mojo.common.mojom" are not @@ -259,7 +254,7 @@ assert(_GetWebUiModulePath(self.module) is not None) self.WriteWithComment(self._GenerateWebUiModule(), - "mojom-webui/%s-webui.ts" % self.module.path) + "%s-webui.ts" % self.module.path) def _GetBindingsLibraryPath(self): return "//resources/mojo/mojo/public/js/bindings.js" @@ -293,28 +288,28 @@ or mojom.IsDoubleKind(kind) or mojom.IsStringKind(kind) or mojom.IsEnumKind(kind)) - def _GetTypeNameForNewBindings(self, - kind, - with_nullability=False, - for_module=False): - def recurse_with_nullability(kind): - return self._GetTypeNameForNewBindings(kind, - with_nullability=True, - for_module=for_module) + def _TypescriptType(self, kind, maybe_nullable=False): + def recurse_nullable(kind): + return self._TypescriptType(kind, maybe_nullable=True) def get_type_name(kind): - if kind == mojom.INT64 or kind == mojom.UINT64: - return "bigint" - if kind in mojom.PRIMITIVES: - return _kind_to_closure_type[kind] + if self._IsPrimitiveKind(kind): + return _kind_to_ts_type[kind] + if mojom.IsArrayKind(kind): - return "Array<%s>" % recurse_with_nullability(kind.kind) - if mojom.IsMapKind(kind) and self._IsStringableKind(kind.key_kind): - return "Object<%s, %s>" % (recurse_with_nullability( - kind.key_kind), recurse_with_nullability(kind.value_kind)) + if (mojom.IsNullableKind(kind.kind)): + return "Array<%s>" % recurse_nullable(kind.kind) + else: + return "%s[]" % get_type_name(kind.kind) + + if (mojom.IsMapKind(kind) and self._IsStringableKind(kind.key_kind) + and not mojom.IsNullableKind(kind.key_kind)): + return "{[key: %s]: %s}" % (get_type_name( + kind.key_kind), recurse_nullable(kind.value_kind)) + if mojom.IsMapKind(kind): - return "Map<%s, %s>" % (recurse_with_nullability( - kind.key_kind), recurse_with_nullability(kind.value_kind)) + return "Map<%s, %s>" % (recurse_nullable( + kind.key_kind), recurse_nullable(kind.value_kind)) if (mojom.IsAssociatedKind(kind) or mojom.IsInterfaceRequestKind(kind) or mojom.IsPendingRemoteKind(kind) @@ -326,21 +321,19 @@ named_kind = kind name = [] - qualified = (not for_module) or (self.module is not named_kind.module) + qualified = self.module is not named_kind.module if qualified and named_kind.module: name.append(named_kind.module.namespace) if named_kind.parent_kind: name.append(named_kind.parent_kind.name) if mojom.IsEnumKind(kind) and named_kind.parent_kind: - name = ".".join(name) + name = "_".join(name) name += "_" + named_kind.name else: name.append("" + named_kind.name) - name = ".".join(name) - - if for_module: - name = name.replace(".", "_") + name = "_".join(name) + name = name.replace('.', '_') if (mojom.IsStructKind(kind) or mojom.IsUnionKind(kind) or mojom.IsEnumKind(kind)): @@ -353,37 +346,21 @@ # TODO(calamity): Support associated interfaces properly. if (mojom.IsAssociatedInterfaceKind(kind) or mojom.IsPendingAssociatedRemoteKind(kind)): - return "Object" + return "object" # TODO(calamity): Support associated interface requests properly. if (mojom.IsAssociatedInterfaceRequestKind(kind) or mojom.IsPendingAssociatedReceiverKind(kind)): - return "Object" - raise Exception("No valid closure type: %s" % kind) + return "object" - if with_nullability: - return ('?' if mojom.IsNullableKind(kind) else '!') + get_type_name(kind) + raise Exception("Type is not supported yet.") + + if (maybe_nullable and mojom.IsNullableKind(kind)): + return "(" + get_type_name(kind) + " | null)" return get_type_name(kind) - def _GetTypeInJsModule(self, kind): - return self._GetTypeNameForNewBindings(kind, - with_nullability=False, - for_module=True) - - def _GetTypeInJsModuleWithNullability(self, kind): - return self._GetTypeNameForNewBindings(kind, - with_nullability=True, - for_module=True) - - def _GetFieldTypeForNewBindings(self, kind, for_module=False): - if mojom.IsNullableKind(kind): - return "({}|undefined)".format( - self._GetTypeNameForNewBindings(kind, for_module=for_module)) - else: - return "!" + self._GetTypeNameForNewBindings(kind, for_module=for_module) - - def _GetFieldTypeInJsModule(self, kind): - return self._GetFieldTypeForNewBindings(kind, for_module=True) + def _TypescriptTypeMaybeNullable(self, kind): + return self._TypescriptType(kind, maybe_nullable=True) def _GetNameInJsModule(self, kind): qualifier = "" @@ -414,16 +391,7 @@ ] assert False, kind.name - def _JavaScriptType(self, kind): - name = [] - if kind.module and kind.module.path != self.module.path: - name.append(kind.module.unique_name) - if kind.parent_kind: - name.append(kind.parent_kind.name) - name.append(kind.name) - return ".".join(name) - - def _GetSpecType(self, kind, for_module=False): + def _GetSpecType(self, kind): def get_spec(kind): if self._IsPrimitiveKind(kind): return _kind_to_lite_js_type[kind] @@ -445,18 +413,15 @@ named_kind = kind name = [] - qualified = (not for_module) or (self.module is not named_kind.module) + qualified = self.module is not named_kind.module if qualified and named_kind.module: name.append(named_kind.module.namespace) if named_kind.parent_kind: parent_name = named_kind.parent_kind.name - if mojom.IsStructKind(named_kind.parent_kind) and not for_module: - parent_name += "Spec" name.append(parent_name) name.append(named_kind.name) - name = ".".join(name) - if for_module: - name = name.replace(".", "_") + name = "_".join(name) + name = name.replace(".", "_") if (mojom.IsStructKind(kind) or mojom.IsUnionKind(kind) or mojom.IsEnumKind(kind)): @@ -479,43 +444,7 @@ return get_spec(kind) - def _GetSpecTypeInJsModule(self, kind): - return self._GetSpecType(kind, for_module=True) - - def _JavaScriptDefaultValue(self, field): - if field.default: - if mojom.IsStructKind(field.kind): - assert field.default == "default" - return "new %s()" % self._JavaScriptType(field.kind) - return self._ExpressionToText(field.default) - if field.kind in mojom.PRIMITIVES: - return _kind_to_javascript_default_value[field.kind] - if mojom.IsStructKind(field.kind): - return "null" - if mojom.IsUnionKind(field.kind): - return "null" - if mojom.IsArrayKind(field.kind): - return "null" - if mojom.IsMapKind(field.kind): - return "null" - if mojom.IsInterfaceKind(field.kind): - return "new %sPtr()" % self._JavaScriptType(field.kind) - if mojom.IsPendingRemoteKind(field.kind): - return "new %sPtr()" % self._JavaScriptType(field.kind.kind) - if (mojom.IsInterfaceRequestKind(field.kind) - or mojom.IsPendingReceiverKind(field.kind)): - return "new bindings.InterfaceRequest()" - if (mojom.IsAssociatedInterfaceKind(field.kind) - or mojom.IsPendingAssociatedRemoteKind(field.kind)): - return "new associatedBindings.AssociatedInterfacePtrInfo()" - if (mojom.IsAssociatedInterfaceRequestKind(field.kind) - or mojom.IsPendingAssociatedReceiverKind(field.kind)): - return "new associatedBindings.AssociatedInterfaceRequest()" - if mojom.IsEnumKind(field.kind): - return "0" - raise Exception("No valid default: %s" % field) - - def _GetDefaultValue(self, field, for_module=False): + def _GetDefaultValue(self, field): if field.default: if mojom.IsStructKind(field.kind): assert field.default == "default" @@ -525,7 +454,7 @@ field.default, (mojom.EnumValue, mojom.NamedValue, mojom.BuiltinValue))): return "BigInt('{}')".format(int(field.default, 0)) - return self._ExpressionToTextLite(field.default, for_module=for_module) + return self._ExpressionToText(field.default) if field.kind == mojom.INT64 or field.kind == mojom.UINT64: return "BigInt(0)" if field.kind in mojom.PRIMITIVES: @@ -534,16 +463,13 @@ return "0" return "null" - def _DefaultValueInJsModule(self, field): - return self._GetDefaultValue(field, for_module=True) - - def _JavaScriptSanitizeIdentifier(self, identifier): + def _TypeScriptSanitizeIdentifier(self, identifier): if identifier in _js_reserved_keywords: return identifier + '_' return identifier - def _ExpressionToText(self, token): + def _ExpressionOrConstantToText(self, token): if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): # Both variable and enum constants are constructed like: # NamespaceUid.Struct[.Enum].CONSTANT_NAME @@ -568,48 +494,40 @@ return token - def _ExpressionToTextLite(self, token, for_module=False): + def _ExpressionToText(self, token): if isinstance(token, (mojom.EnumValue, mojom.NamedValue)): # Generate the following for: # - Enums: NamespaceUid.Enum.CONSTANT_NAME # - Struct: NamespaceUid.Struct_CONSTANT_NAME namespace_components = [] - qualified = (not for_module) or (token.module is not self.module) + qualified = token.module is not self.module if token.module and qualified: namespace_components.append(token.module.namespace) if token.parent_kind: namespace_components.append(token.parent_kind.name) name_prefix = '.'.join(namespace_components) - if for_module: - name_prefix = name_prefix.replace('.', '_') + name_prefix = name_prefix.replace('.', '_') name = [] if isinstance(token, mojom.EnumValue): name.append(token.enum.name) name.append(token.name) - separator = "." - if mojom.IsStructKind(token.parent_kind) or for_module: - separator = "_" - if len(name_prefix) > 0: - return name_prefix + separator + ".".join(name) + return f"{name_prefix}_{'.'.join(name)}" return ".".join(name) - return self._ExpressionToText(token) + return self._ExpressionOrConstantToText(token) - def _GetConstantValue(self, constant, for_module=False): + def _GetConstantValue(self, constant): assert isinstance(constant, mojom.Constant) - text = self._ExpressionToTextLite(constant.value, for_module=for_module) + text = self._ExpressionOrConstantToText(constant.value) if constant.kind == mojom.INT64 or constant.kind == mojom.UINT64: return "BigInt('{}')".format(int(text, 0)) return text - def _GetConstantValueInJsModule(self, constant): - return self._GetConstantValue(constant, for_module=True) - def _GetJsModuleImports(self): this_module_path = _GetWebUiModulePath(self.module) this_module_is_shared = bool(
diff --git a/mojo/public/tools/bindings/generators/ts_templates/OWNERS b/mojo/public/tools/bindings/generators/ts_templates/OWNERS new file mode 100644 index 0000000..a1d25f2 --- /dev/null +++ b/mojo/public/tools/bindings/generators/ts_templates/OWNERS
@@ -0,0 +1 @@ +rbpotter@chromium.org
diff --git a/mojo/public/tools/bindings/generators/ts_templates/enum_definition.tmpl b/mojo/public/tools/bindings/generators/ts_templates/enum_definition.tmpl index 27c4817..8a4cd2c 100644 --- a/mojo/public/tools/bindings/generators/ts_templates/enum_definition.tmpl +++ b/mojo/public/tools/bindings/generators/ts_templates/enum_definition.tmpl
@@ -1,23 +1,16 @@ {%- macro enum_def(enum) -%} -/** - * @const { {$: !mojo.internal.MojomType} } - */ -export const {{enum|type_in_js_module}}Spec = { $: mojo.internal.Enum() }; +export const {{enum|ts_type}}Spec: { $: mojo.internal.MojomType } = { $: mojo.internal.Enum() }; -/** - * @enum {number} - */ -export const {{enum|type_in_js_module}} = { - {# Set up the enum here, but fill out the values later. #} -{%- for field in enum.fields %} - {{field.name}}: {{field.numeric_value}}, -{%- endfor %} -{%- if enum.min_value is not none %} - MIN_VALUE: {{enum.min_value}}, -{%- endif %} -{%- if enum.max_value is not none %} - MAX_VALUE: {{enum.max_value}}, -{%- endif %} -}; +export enum {{enum.name}} { +{%- for field in enum.fields %} + {{field.name}} = {{field.numeric_value}}, +{%- endfor %} +{%- if enum.min_value is not none %} + MIN_VALUE = {{enum.min_value}}, +{%- endif %} +{%- if enum.max_value is not none %} + MAX_VALUE = {{enum.max_value}}, +{%- endif %} +} {%- endmacro %}
diff --git a/mojo/public/tools/bindings/generators/ts_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/ts_templates/interface_definition.tmpl index 6ed5b6e0..82b1a5b4 100644 --- a/mojo/public/tools/bindings/generators/ts_templates/interface_definition.tmpl +++ b/mojo/public/tools/bindings/generators/ts_templates/interface_definition.tmpl
@@ -1,73 +1,53 @@ -{% macro generateMethodAnnotation(method) %} - /** -{%- for param in method.parameters %} - * @param { {{param.kind|type_in_js_module_with_nullability}} } {{param.name|sanitize_identifier}} -{%- endfor -%} +{%- macro generate_return_type(method) %} {%- if method.response_parameters != None %} -{%- if method.response_parameters|length == 0 %} - * @return {!Promise} -{%- else %} - * @return {!Promise<{ +{%- if method.response_parameters|length == 0 %}Promise<void> +{%- else %}Promise<{ {%- for response_parameter in method.response_parameters %} - {{response_parameter.name}}: {{response_parameter.kind|type_in_js_module_with_nullability}}, -{%- endfor %} - * }>} + {{response_parameter.name}}: {{response_parameter.kind|ts_type_maybe_nullable}}, +{%- endfor %} }> {%- endif %} +{%- else %}void {%- endif %} - */ -{% endmacro %} +{%- endmacro %} -/** - * @implements {mojo.internal.interfaceSupport.PendingReceiver} - */ -export class {{interface.name}}PendingReceiver { - /** - * @param {!MojoHandle|!mojo.internal.interfaceSupport.Endpoint} handle - */ - constructor(handle) { - /** @public {!mojo.internal.interfaceSupport.Endpoint} */ +export class {{interface.name}}PendingReceiver implements + mojo.internal.interfaceSupport.PendingReceiver { + + handle: mojo.internal.interfaceSupport.Endpoint; + constructor(handle: MojoHandle|mojo.internal.interfaceSupport.Endpoint) { this.handle = mojo.internal.interfaceSupport.getEndpointForReceiver(handle); } - /** @param {string=} scope */ - bindInBrowser(scope = 'context') { + bindInBrowser(scope: string = 'context') { mojo.internal.interfaceSupport.bind( - this.handle, '{{mojom_namespace}}.{{interface.name}}', scope); + this.handle, + '{{mojom_namespace}}.{{interface.name}}', + scope); } } -/** @interface */ -export class {{interface.name}}Interface { +export interface {{interface.name}}Interface { {%- for method in interface.methods %} - {{generateMethodAnnotation(method)}} {{method.name}}( {%- for param in method.parameters -%} -{{param.name|sanitize_identifier}}{% if not loop.last %}, {% endif %} -{%- endfor -%} -) {} +{{param.name|sanitize_identifier}}: {{param.kind|ts_type_maybe_nullable}}{% if not loop.last %}, {% endif %} +{%- endfor -%}): {{generate_return_type(method)}}; {%- endfor %} } -/** - * @implements { {{interface.name}}Interface } - */ -export class {{interface.name}}Remote { - /** @param {MojoHandle|mojo.internal.interfaceSupport.Endpoint=} handle */ - constructor(handle = undefined) { - /** - * @private {!mojo.internal.interfaceSupport.InterfaceRemoteBase<!{{interface.name}}PendingReceiver>} - */ +export class {{interface.name}}Remote implements {{interface.name}}Interface { + private proxy: mojo.internal.interfaceSupport.InterfaceRemoteBase<{{interface.name}}PendingReceiver>; + $: mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper<{{interface.name}}PendingReceiver>; + onConnectionError: mojo.internal.interfaceSupport.ConnectionErrorEventRouter; + + constructor( + handle?: MojoHandle|mojo.internal.interfaceSupport.Endpoint) { this.proxy = new mojo.internal.interfaceSupport.InterfaceRemoteBase( - {{interface.name}}PendingReceiver, - handle); + {{interface.name}}PendingReceiver, handle); - /** - * @public {!mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper<!{{interface.name}}PendingReceiver>} - */ this.$ = new mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper(this.proxy); - /** @public {!mojo.internal.interfaceSupport.ConnectionErrorEventRouter} */ this.onConnectionError = this.proxy.getConnectionErrorEventRouter(); } @@ -75,11 +55,10 @@ {%- set interface_message_id = interface.mojom_name ~ "_" ~ method.mojom_name %} - {{generateMethodAnnotation(method)}} {{method.name}}( {%- for param in method.parameters %} - {{param.name}}{%- if not loop.last %},{% endif %} -{%- endfor -%}) { + {{param.name}}: {{param.kind|ts_type_maybe_nullable}}{%- if not loop.last %},{% endif %} +{%- endfor -%}): {{generate_return_type(method)}} { {%- if method.response_parameters != None %} return this.proxy.sendMessage( {%- else %} @@ -99,7 +78,7 @@ ]); } {%- endfor %} -} +}; /** * An object which receives request messages for the {{interface.name}} @@ -107,17 +86,16 @@ * interface. */ export class {{interface.name}}Receiver { - /** - * @param {!{{interface.name}}Interface } impl - */ - constructor(impl) { - /** @private {!mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal<!{{interface.name}}Remote>} */ + private helper_internal_: mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal<{{interface.name}}Remote>; + + $: mojo.internal.interfaceSupport.InterfaceReceiverHelper<{{interface.name}}Remote>; + + onConnectionError: mojo.internal.interfaceSupport.ConnectionErrorEventRouter; + + constructor(impl: {{interface.name}}Interface) { this.helper_internal_ = new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal( {{interface.name}}Remote); - /** - * @public {!mojo.internal.interfaceSupport.InterfaceReceiverHelper<!{{interface.name}}Remote>} - */ this.$ = new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_); {% for method in interface.methods %} @@ -133,16 +111,12 @@ {%- endif %} impl.{{method.name}}.bind(impl)); {%- endfor %} - /** @public {!mojo.internal.interfaceSupport.ConnectionErrorEventRouter} */ this.onConnectionError = this.helper_internal_.getConnectionErrorEventRouter(); } } export class {{interface.name}} { - /** - * @return {!string} - */ - static get $interfaceName() { + static get $interfaceName(): string { return "{{mojom_namespace}}.{{interface.name}}"; } @@ -150,10 +124,8 @@ * Returns a remote for this interface which sends messages to the browser. * The browser must have an interface request binder registered for this * interface and accessible to the calling document's frame. - * - * @return {!{{interface.name}}Remote} */ - static getRemote() { + static getRemote(): {{interface.name}}Remote { let remote = new {{interface.name}}Remote; remote.$.bindNewPipeAndPassReceiver().bindInBrowser(); return remote; @@ -161,9 +133,9 @@ } {#--- Enums #} -{% from "lite/enum_definition_for_module.tmpl" import enum_def with context %} +{%- from "enum_definition.tmpl" import enum_def with context %} {%- for enum in interface.enums %} -{{enum_def(enum)}} +{{ enum_def(enum) }} {%- endfor %} /** @@ -173,22 +145,26 @@ * receiver can have any number of listeners added to it. */ export class {{interface.name}}CallbackRouter { + private helper_internal_: mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal<{{interface.name}}Remote>; + $: mojo.internal.interfaceSupport.InterfaceReceiverHelper<{{interface.name}}Remote>; + router_: mojo.internal.interfaceSupport.CallbackRouter; +{% for method in interface.methods %} +{%- set interface_message_id = + interface.mojom_name ~ "_" ~ method.mojom_name %} + {{method.name}}: mojo.internal.interfaceSupport.InterfaceCallbackReceiver; +{%- endfor %} + onConnectionError: mojo.internal.interfaceSupport.ConnectionErrorEventRouter; + constructor() { this.helper_internal_ = new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal( {{interface.name}}Remote); - /** - * @public {!mojo.internal.interfaceSupport.InterfaceReceiverHelper<!{{interface.name}}Remote>} - */ this.$ = new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_); this.router_ = new mojo.internal.interfaceSupport.CallbackRouter; {% for method in interface.methods %} {%- set interface_message_id = interface.mojom_name ~ "_" ~ method.mojom_name %} - /** - * @public {!mojo.internal.interfaceSupport.InterfaceCallbackReceiver} - */ this.{{method.name}} = new mojo.internal.interfaceSupport.InterfaceCallbackReceiver( this.router_); @@ -204,15 +180,14 @@ this.{{method.name}}.createReceiverHandler(false /* expectsResponse */)); {%- endif %} {%- endfor %} - /** @public {!mojo.internal.interfaceSupport.ConnectionErrorEventRouter} */ this.onConnectionError = this.helper_internal_.getConnectionErrorEventRouter(); } /** - * @param {number} id An ID returned by a prior call to addListener. - * @return {boolean} True iff the identified listener was found and removed. + * @param id An ID returned by a prior call to addListener. + * @return True iff the identified listener was found and removed. */ - removeListener(id) { + removeListener(id: number): boolean { return this.router_.removeListener(id); } }
diff --git a/mojo/public/tools/bindings/generators/ts_templates/module_definition.tmpl b/mojo/public/tools/bindings/generators/ts_templates/module_definition.tmpl index d067a94..a42588c 100644 --- a/mojo/public/tools/bindings/generators/ts_templates/module_definition.tmpl +++ b/mojo/public/tools/bindings/generators/ts_templates/module_definition.tmpl
@@ -21,10 +21,7 @@ {#--- Constants #} {%- for constant in module.constants %} -/** - * @const { {{constant.kind|type_in_js_module_with_nullability}} } - */ -export const {{constant.name}} = {{constant|constant_value_in_js_module}}; +export const {{constant.name}}: {{constant.kind|ts_type_maybe_nullable}} = {{constant|constant_value}}; {% endfor -%}
diff --git a/mojo/public/tools/bindings/generators/ts_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/ts_templates/struct_definition.tmpl index f9d5241..c6508fc 100644 --- a/mojo/public/tools/bindings/generators/ts_templates/struct_definition.tmpl +++ b/mojo/public/tools/bindings/generators/ts_templates/struct_definition.tmpl
@@ -1,12 +1,9 @@ {% for constant in struct.constants %} -/** - * @const { {{constant.kind|type_in_js_module_with_nullability}} } - */ -export const {{struct.name}}_{{constant.name}} = - {{constant|constant_value_in_js_module}}; +export const {{struct.name}}_{{constant.name}}: {{constant.kind|ts_type_maybe_nullable}} = + {{constant|constant_value}}; {% endfor %} -{%- from "lite/enum_definition_for_module.tmpl" import enum_def with context %} +{%- from "enum_definition.tmpl" import enum_def with context %} {% for enum in struct.enums %} {{enum_def(enum)}} {% endfor %} @@ -20,8 +17,8 @@ '{{packed_field.field.name}}', {{packed_field.offset}}, {% if packed_field.field.kind|is_bool_kind %}{{packed_field.bit}} {%- else %}0{% endif %}, - {{packed_field.field.kind|spec_type_in_js_module}}, - {{packed_field.field|default_value_in_js_module}}, + {{packed_field.field.kind|spec_type}}, + {{packed_field.field|default_ts_value}}, {%- if packed_field.field.kind.is_nullable %} true /* nullable */, {%- else %} @@ -41,14 +38,9 @@ mojo.internal.createStructDeserializer({{struct.name}}Spec.$); {% endif %} -/** - * @record - */ -export class {{struct.name}} { - constructor() { +export interface {{struct.name}} { {%- for packed_field in struct.packed.packed_fields %} - /** @type { {{packed_field.field.kind|field_type_in_js_module}} } */ - this.{{packed_field.field.name}}; -{%- endfor %} - } + {% set f = packed_field.field -%} + {{f.name}}{% if f.kind.is_nullable %}?{% endif %}: {{f.kind|ts_type}}; +{%- endfor %} }
diff --git a/mojo/public/tools/bindings/generators/ts_templates/union_definition.tmpl b/mojo/public/tools/bindings/generators/ts_templates/union_definition.tmpl index 68be8b2..e257771c 100644 --- a/mojo/public/tools/bindings/generators/ts_templates/union_definition.tmpl +++ b/mojo/public/tools/bindings/generators/ts_templates/union_definition.tmpl
@@ -4,7 +4,7 @@ {%- for field in union.fields %} '{{field.name}}': { 'ordinal': {{field.ordinal}}, - 'type': {{field.kind|spec_type_in_js_module}}, + 'type': {{field.kind|spec_type}}, {%- if field.kind.is_nullable %} 'nullable': true, {%- endif %} @@ -12,11 +12,8 @@ {%- endfor %} }); -/** - * @typedef { { +export interface {{union.name}} { {%- for field in union.fields %} - * {{field.name}}: ({{field.kind|type_in_js_module_with_nullability}}|undefined), -{%- endfor %} - * } } - */ -export const {{union.name}} = {}; + {{field.name}}?: {{field.kind|ts_type_maybe_nullable}}, +{%- endfor %} +}
diff --git a/mojo/public/tools/bindings/mojom.gni b/mojo/public/tools/bindings/mojom.gni index 5781c8a..080bcee7 100644 --- a/mojo/public/tools/bindings/mojom.gni +++ b/mojo/public/tools/bindings/mojom.gni
@@ -45,7 +45,7 @@ enable_mojom_closure_compile = enable_js_type_check && optimize_webui # Enables generating Typescript bindings and compiling them to JS bindings. - enable_typescript_bindings = false + enable_typescript_bindings = true # Enables generating javascript fuzzing-related code and the bindings for the # MojoLPM fuzzer targets. Off by default. @@ -2005,7 +2005,7 @@ outputs = [] foreach(base_path, output_file_base_paths) { - outputs += [ "$root_gen_dir/mojom-webui/$base_path-webui.ts" ] + outputs += [ "$root_gen_dir/$base_path-webui.ts" ] } args = common_generator_args response_file_contents = source_filelist
diff --git a/mojo/public/tools/bindings/mojom_bindings_generator.py b/mojo/public/tools/bindings/mojom_bindings_generator.py index e0ecc221..5a5cace 100755 --- a/mojo/public/tools/bindings/mojom_bindings_generator.py +++ b/mojo/public/tools/bindings/mojom_bindings_generator.py
@@ -54,6 +54,7 @@ "javascript": "mojom_js_generator", "java": "mojom_java_generator", "mojolpm": "mojom_mojolpm_generator", + "typescript": "mojom_ts_generator", } _BUILTIN_CHECKS = {
diff --git a/net/cert/pki/DEPS b/net/cert/pki/DEPS new file mode 100644 index 0000000..e003c77e9 --- /dev/null +++ b/net/cert/pki/DEPS
@@ -0,0 +1,34 @@ +include_rules = [ + # Do not take new base/ dependencies in here. + # Please check with bbe@ if you run afoul of this + # TODO(crbug.com/1322914): Remove exceptions. + "-base", + "+base/base_paths.h", + "+base/callback_forward.h", + "+base/compiler_specific.h", + "+base/containers/contains.h", + "+base/containers/span.h", + "+base/files/file_util.h", + "+base/logging.h", + "+base/memory/raw_ptr.h", + "+base/memory/ref_counted.h", + "+base/memory/scoped_refptr.h", + "+base/metrics/histogram_functions.h", + "+base/numerics/clamped_math.h", + "+base/path_service.h", + "+base/ranges/algorithm.h", + "+base/stl_util.h", + "+base/strings/string_number_conversions.h", + "+base/strings/string_piece.h", + "+base/supports_user_data.h", + "+base/time/time.h", + "+base/win/wincrypt_shim.h", +] +specific_include_rules = { + "path_builder_unittest\.cc": [ + "+base/test/bind.h", + "+base/test/metrics/histogram_tester.h", + "+base/test/task_environment.h", + ], +} +
diff --git a/net/cert/pki/path_builder_unittest.cc b/net/cert/pki/path_builder_unittest.cc index 5366801..1a048bc 100644 --- a/net/cert/pki/path_builder_unittest.cc +++ b/net/cert/pki/path_builder_unittest.cc
@@ -5,6 +5,7 @@ #include "net/cert/pki/path_builder.h" #include <algorithm> + #include "base/base_paths.h" #include "base/callback_forward.h" #include "base/containers/span.h" @@ -12,7 +13,6 @@ #include "base/path_service.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" -#include "base/test/task_environment.h" #include "base/time/time.h" #include "build/build_config.h" #include "net/cert/pem.h"
diff --git a/net/first_party_sets/global_first_party_sets.cc b/net/first_party_sets/global_first_party_sets.cc index e6dc57cc..1ff9fc41 100644 --- a/net/first_party_sets/global_first_party_sets.cc +++ b/net/first_party_sets/global_first_party_sets.cc
@@ -99,9 +99,14 @@ entries_(std::move(entries)), aliases_(std::move(aliases)), manual_config_(std::move(manual_config)) { - // `aliases_` can only be nonempty if `entries_` is also nonempty. - if (!aliases_.empty()) - DCHECK(!entries_.empty()); + if (public_sets_version_.IsValid()) { + DCHECK(base::ranges::all_of(aliases_, [&](const auto& pair) { + return entries_.contains(pair.second); + })); + } else { + DCHECK(entries_.empty()); + DCHECK(aliases_.empty()); + } } GlobalFirstPartySets::GlobalFirstPartySets(GlobalFirstPartySets&&) = default;
diff --git a/net/first_party_sets/global_first_party_sets.h b/net/first_party_sets/global_first_party_sets.h index 9b867ef..58539d2 100644 --- a/net/first_party_sets/global_first_party_sets.h +++ b/net/first_party_sets/global_first_party_sets.h
@@ -199,6 +199,9 @@ } // The version associated with the component_updater-provided public sets. + // This may be invalid if the "First-Party Sets" component has not been + // installed yet, or has been corrupted. Entries and aliases from invalid + // components are ignored. base::Version public_sets_version_; // Represents the mapping of site -> entry, where keys are sites within sets,
diff --git a/net/test/embedded_test_server/http2_connection.cc b/net/test/embedded_test_server/http2_connection.cc index 45513245..90d42ce 100644 --- a/net/test/embedded_test_server/http2_connection.cc +++ b/net/test/embedded_test_server/http2_connection.cc
@@ -372,11 +372,11 @@ http2::adapter::Http2StreamId stream_id) { HttpRequest::HeaderMap header_map = header_map_[stream_id]; auto request = std::make_unique<HttpRequest>(); + // TODO(crbug.com/1375303): Handle proxy cases. request->relative_url = header_map[":path"]; request->base_url = GURL(header_map[":authority"]); request->method_string = header_map[":method"]; - request->method = HttpRequestParser::GetMethodType( - base::ToLowerASCII(request->method_string)); + request->method = HttpRequestParser::GetMethodType(request->method_string); request->headers = header_map; request->has_content = false;
diff --git a/net/test/embedded_test_server/http_request.cc b/net/test/embedded_test_server/http_request.cc index b9b96cd..4704ab10 100644 --- a/net/test/embedded_test_server/http_request.cc +++ b/net/test/embedded_test_server/http_request.cc
@@ -11,6 +11,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "net/base/host_port_pair.h" #include "net/http/http_chunked_decoder.h" #include "url/gurl.h" @@ -94,18 +95,35 @@ DCHECK_EQ(3u, header_line_tokens.size()); // Method. http_request_->method_string = header_line_tokens[0]; - http_request_->method = - GetMethodType(base::ToLowerASCII(header_line_tokens[0])); - // Address. - // Don't build an absolute URL as the parser does not know (should not - // know) anything about the server address. - GURL url(header_line_tokens[1]); - if (url.is_valid()) { - http_request_->relative_url = url.PathForRequest(); - } else if (header_line_tokens[1][0] == '/') { + http_request_->method = GetMethodType(http_request_->method_string); + // Target resource. See + // https://www.rfc-editor.org/rfc/rfc9112#name-request-line + // https://www.rfc-editor.org/rfc/rfc9110#name-determining-the-target-reso + if (http_request_->method == METHOD_CONNECT) { + // CONNECT uses a special authority-form. Just report the value as + // `relative_url`. + // https://www.rfc-editor.org/rfc/rfc9112#section-3.2.3 + CHECK(!HostPortPair::FromString(header_line_tokens[1]).IsEmpty()); http_request_->relative_url = header_line_tokens[1]; + } else if (http_request_->method == METHOD_OPTIONS && + header_line_tokens[1] == "*") { + // OPTIONS allows a special asterisk-form for the request target. + // https://www.rfc-editor.org/rfc/rfc9112#section-3.2.4 + http_request_->relative_url = "*"; } else { - http_request_->relative_url = "/" + header_line_tokens[1]; + // The request target should be origin-form, unless connecting through a + // proxy, in which case it is absolute-form. + // https://www.rfc-editor.org/rfc/rfc9112#name-origin-form + // https://www.rfc-editor.org/rfc/rfc9112#name-absolute-form + if (!header_line_tokens[1].empty() && + header_line_tokens[1].front() == '/') { + http_request_->relative_url = header_line_tokens[1]; + } else { + GURL url(header_line_tokens[1]); + CHECK(url.is_valid()); + // TODO(crbug.com/1375303): This should retain the entire URL. + http_request_->relative_url = url.PathForRequest(); + } } // Protocol. @@ -224,26 +242,26 @@ } // static -HttpMethod HttpRequestParser::GetMethodType(const std::string& token) { - if (token == "get") { +HttpMethod HttpRequestParser::GetMethodType(base::StringPiece token) { + if (token == "GET") { return METHOD_GET; - } else if (token == "head") { + } else if (token == "HEAD") { return METHOD_HEAD; - } else if (token == "post") { + } else if (token == "POST") { return METHOD_POST; - } else if (token == "put") { + } else if (token == "PUT") { return METHOD_PUT; - } else if (token == "delete") { + } else if (token == "DELETE") { return METHOD_DELETE; - } else if (token == "patch") { + } else if (token == "PATCH") { return METHOD_PATCH; - } else if (token == "connect") { + } else if (token == "CONNECT") { return METHOD_CONNECT; - } else if (token == "options") { + } else if (token == "OPTIONS") { return METHOD_OPTIONS; } LOG(WARNING) << "Method not implemented: " << token; - return METHOD_GET; + return METHOD_UNKNOWN; } } // namespace net::test_server
diff --git a/net/test/embedded_test_server/http_request.h b/net/test/embedded_test_server/http_request.h index d356fe5..de14212 100644 --- a/net/test/embedded_test_server/http_request.h +++ b/net/test/embedded_test_server/http_request.h
@@ -59,8 +59,14 @@ // Returns a GURL as a convenience to extract the path and query strings. GURL GetURL() const; - std::string relative_url; // Starts with '/'. Example: "/test?query=foo" + // The request target. For most methods, this will start with '/', e.g., + // "/test?query=foo". If `method` is `METHOD_OPTIONS`, it may also be "*". If + // `method` is `METHOD_CONNECT`, it will instead be a string like + // "example.com:443". + std::string relative_url; GURL base_url; + // The HTTP method. If unknown, this will be `METHOD_UNKNOWN` and the actual + // method will be in `method_string`. HttpMethod method = METHOD_UNKNOWN; std::string method_string; std::string all_headers; @@ -117,7 +123,9 @@ // another request. std::unique_ptr<HttpRequest> GetRequest(); - static HttpMethod GetMethodType(const std::string& token); + // Returns `METHOD_UNKNOWN` if `token` is not a recognized method. Methods are + // case-sensitive. + static HttpMethod GetMethodType(base::StringPiece token); private: // Parses headers and returns ACCEPTED if whole request was parsed. Otherwise
diff --git a/net/test/embedded_test_server/http_request_unittest.cc b/net/test/embedded_test_server/http_request_unittest.cc index d0d2b57..f685b1c 100644 --- a/net/test/embedded_test_server/http_request_unittest.cc +++ b/net/test/embedded_test_server/http_request_unittest.cc
@@ -144,6 +144,20 @@ EXPECT_FALSE(request->has_content); } +TEST(HttpRequestTest, ParseConnect) { + HttpRequestParser parser; + + parser.ProcessChunk("CONNECT example.com:443 HTTP/1.1\r\n\r\n"); + ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); + + std::unique_ptr<HttpRequest> request = parser.GetRequest(); + EXPECT_EQ("example.com:443", request->relative_url); + EXPECT_EQ("CONNECT", request->method_string); + EXPECT_EQ(METHOD_CONNECT, request->method); + EXPECT_EQ("", request->content); + EXPECT_FALSE(request->has_content); +} + TEST(HttpRequestTest, GetURL) { HttpRequest request; request.relative_url = "/foobar.html?q=foo";
diff --git a/net/test/embedded_test_server/request_handler_util.cc b/net/test/embedded_test_server/request_handler_util.cc index 570dae40..fa3434b4 100644 --- a/net/test/embedded_test_server/request_handler_util.cc +++ b/net/test/embedded_test_server/request_handler_util.cc
@@ -79,6 +79,10 @@ } bool ShouldHandle(const HttpRequest& request, const std::string& path_prefix) { + if (request.method == METHOD_CONNECT) { + return false; + } + GURL url = request.GetURL(); return url.path() == path_prefix || base::StartsWith(url.path(), path_prefix + "/", @@ -155,6 +159,10 @@ // TODO(svaldez): Figure out why thread is I/O restricted in the first place. base::ScopedAllowBlockingForTesting allow_blocking; + if (request.method == METHOD_CONNECT) { + return nullptr; + } + // A proxy request will have an absolute path. Simulate the proxy by stripping // the scheme, host, and port. GURL request_url = request.GetURL();
diff --git a/remoting/android/client_java_tmpl.gni b/remoting/android/client_java_tmpl.gni index 98bb7d7..3a3dd4c 100644 --- a/remoting/android/client_java_tmpl.gni +++ b/remoting/android/client_java_tmpl.gni
@@ -56,7 +56,6 @@ "TrackpadInputStrategy.java", "TwoPointsEventParameter.java", "WebViewActivity.java", - "accountswitcher/AccountManagerCompat.java", "accountswitcher/AccountSwitcher.java", "accountswitcher/AccountSwitcherBase.java", "accountswitcher/AccountSwitcherBasic.java",
diff --git a/remoting/android/java/src/org/chromium/chromoting/Chromoting.java b/remoting/android/java/src/org/chromium/chromoting/Chromoting.java index d7a23a0c..4cbcb56c 100644 --- a/remoting/android/java/src/org/chromium/chromoting/Chromoting.java +++ b/remoting/android/java/src/org/chromium/chromoting/Chromoting.java
@@ -11,7 +11,6 @@ import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.drawable.Drawable; -import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.view.ContextMenu; @@ -625,11 +624,9 @@ @Override public void onAccountSelected(String accountName) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - String logInAnnouncement = - getString(R.string.log_in_account_accessibility_description, accountName); - mAccountSwitcher.getView().announceForAccessibility(logInAnnouncement); - } + String logInAnnouncement = + getString(R.string.log_in_account_accessibility_description, accountName); + mAccountSwitcher.getView().announceForAccessibility(logInAnnouncement); mAccount = accountName; JniOAuthTokenGetter.setAccount(accountName); mNotificationPresenter.presentIfNecessary(accountName);
diff --git a/remoting/android/java/src/org/chromium/chromoting/Desktop.java b/remoting/android/java/src/org/chromium/chromoting/Desktop.java index 2ec4074..b45c25c14 100644 --- a/remoting/android/java/src/org/chromium/chromoting/Desktop.java +++ b/remoting/android/java/src/org/chromium/chromoting/Desktop.java
@@ -180,7 +180,6 @@ mInputMode = getInitialInputModeValue(); mResizeToClientEnabled = getStoredResizeToClientEnabled(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { attachSystemUiResizeListener(); // Suspend the ActionBar timer when the user interacts with the options menu. @@ -194,9 +193,6 @@ } } }); - } else { - mRemoteHostDesktop.setFitsSystemWindows(true); - } } @Override @@ -212,16 +208,11 @@ super.onResume(); mActivityLifecycleListener.onActivityResumed(this); mClient.enableVideoChannel(true); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - // We want to call the change handler with an initial value as - // onMultiWindowModeChanged won't be called if the state hasn't changed, such as - // when the user resizes in split-screen, and we want to ensure we have a default - // value set (even though it may change soon after). - onMultiWindowModeChanged(isInMultiWindowMode()); - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - setUpAutoHideToolbar(); - syncActionBarToSystemUiState(); - } + // We want to call the change handler with an initial value as + // onMultiWindowModeChanged won't be called if the state hasn't changed, such as + // when the user resizes in split-screen, and we want to ensure we have a default + // value set (even though it may change soon after). + onMultiWindowModeChanged(isInMultiWindowMode()); } @Override @@ -277,33 +268,31 @@ mActivityLifecycleListener.onActivityCreatedOptionsMenu(this, menu); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - // We don't need to show a hide ActionBar button if immersive fullscreen is - // supported. - menu.findItem(R.id.actionbar_hide).setVisible(false); + // We don't need to show a hide ActionBar button if immersive fullscreen is + // supported. + menu.findItem(R.id.actionbar_hide).setVisible(false); - // Although the MenuItems are being created here, they do not have any backing Views - // yet as those are created just after this method exits. We post an async task to - // the UI thread here so that we can attach our interaction listeners shortly after - // the views have been created. - final Menu menuFinal = menu; - new Handler().post(new Runnable() { - @Override - public void run() { - // Attach a listener to the toolbar itself then attach one to each menu item - // which has a backing view object. - attachToolbarInteractionListenerToView(mToolbar); - int items = menuFinal.size(); - for (int i = 0; i < items; i++) { - int itemId = menuFinal.getItem(i).getItemId(); - View menuItemView = findViewById(itemId); - if (menuItemView != null) { - attachToolbarInteractionListenerToView(menuItemView); - } + // Although the MenuItems are being created here, they do not have any backing Views + // yet as those are created just after this method exits. We post an async task to + // the UI thread here so that we can attach our interaction listeners shortly after + // the views have been created. + final Menu menuFinal = menu; + new Handler().post(new Runnable() { + @Override + public void run() { + // Attach a listener to the toolbar itself then attach one to each menu item + // which has a backing view object. + attachToolbarInteractionListenerToView(mToolbar); + int items = menuFinal.size(); + for (int i = 0; i < items; i++) { + int itemId = menuFinal.getItem(i).getItemId(); + View menuItemView = findViewById(itemId); + if (menuItemView != null) { + attachToolbarInteractionListenerToView(menuItemView); } } - }); - } + } + }); ChromotingUtil.tintMenuIcons(this, menu); @@ -507,23 +496,14 @@ @SuppressLint("InlinedApi") private static int getFullscreenFlags() { // LOW_PROFILE gives the status and navigation bars a "lights-out" appearance. - // FULLSCREEN hides the status bar on supported devices (4.1 and above). - int flags = View.SYSTEM_UI_FLAG_LOW_PROFILE; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - flags |= View.SYSTEM_UI_FLAG_FULLSCREEN; - } - return flags; + // FULLSCREEN hides the status bar. + return View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN; } @SuppressLint("InlinedApi") private static int getLayoutFlags() { - int flags = 0; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - flags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; - flags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; - flags |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; - } - return flags; + return View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; } /** @@ -599,13 +579,9 @@ // HIDE_NAVIGATION hides the navigation bar. However, if the user touches the screen, // the event is not seen by the application and instead the navigation bar is re-shown. // IMMERSIVE fixes this problem and allows the user to interact with the app while - // keeping the navigation controls hidden. This flag was introduced in 4.4, later than - // HIDE_NAVIGATION, and so a runtime check is needed before setting either of these - // flags. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - flags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; - flags |= View.SYSTEM_UI_FLAG_IMMERSIVE; - } + // keeping the navigation controls hidden. + flags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + flags |= View.SYSTEM_UI_FLAG_IMMERSIVE; flags |= getLayoutFlags(); getWindow().getDecorView().setSystemUiVisibility(flags);
diff --git a/remoting/android/java/src/org/chromium/chromoting/WebViewActivity.java b/remoting/android/java/src/org/chromium/chromoting/WebViewActivity.java index 2db79623..c05a803 100644 --- a/remoting/android/java/src/org/chromium/chromoting/WebViewActivity.java +++ b/remoting/android/java/src/org/chromium/chromoting/WebViewActivity.java
@@ -5,14 +5,12 @@ package org.chromium.chromoting; import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.view.MenuItem; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; -import androidx.annotation.RequiresApi; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; @@ -50,7 +48,6 @@ return true; } - @RequiresApi(Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return shouldOverrideUrlLoading(request.getUrl());
diff --git a/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountManagerCompat.java b/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountManagerCompat.java deleted file mode 100644 index 71616271..0000000 --- a/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountManagerCompat.java +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chromoting.accountswitcher; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; - -import java.util.ArrayList; - -/** API compatibility wrapper for AccountManager methods. */ -public class AccountManagerCompat { - /** - * @see android.accounts.AccountManager#newChooseAccountIntent() - */ - @SuppressWarnings("deprecation") - public static Intent newChooseAccountIntent(Account selectedAccount, - ArrayList<Account> allowableAccounts, String[] allowableAccountTypes, - String descriptionOverrideText, String addAccountAuthTokenType, - String[] addAccountRequiredFeatures, Bundle addAccountOptions) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - return AccountManager.newChooseAccountIntent(selectedAccount, allowableAccounts, - allowableAccountTypes, descriptionOverrideText, addAccountAuthTokenType, - addAccountRequiredFeatures, addAccountOptions); - } - return AccountManager.newChooseAccountIntent(selectedAccount, allowableAccounts, - allowableAccountTypes, false, descriptionOverrideText, addAccountAuthTokenType, - addAccountRequiredFeatures, addAccountOptions); - } -}
diff --git a/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountSwitcherBasic.java b/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountSwitcherBasic.java index bddba575..73422cf 100644 --- a/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountSwitcherBasic.java +++ b/remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountSwitcherBasic.java
@@ -140,8 +140,12 @@ if (mSelectedAccount != null) { selected = new Account(mSelectedAccount, ACCOUNT_TYPE); } - Intent intent = AccountManagerCompat.newChooseAccountIntent( - selected, null, new String[] {ACCOUNT_TYPE}, null, null, null, null); + + Intent intent = AccountManager.newChooseAccountIntent(selected, /*allowableAccounts=*/null, + new String[] {ACCOUNT_TYPE}, + /*descriptionOverrideText=*/null, /*addAccountAuthTokenType=*/null, + /*addAccountRequiredFeatures=*/null, /*addAccountOptions=*/null); + mActivity.startActivityForResult(intent, REQUEST_CODE_CHOOSE_ACCOUNT); } }
diff --git a/remoting/android/java/src/org/chromium/chromoting/help/HelpActivity.java b/remoting/android/java/src/org/chromium/chromoting/help/HelpActivity.java index f8a671ef3..ebba9140 100644 --- a/remoting/android/java/src/org/chromium/chromoting/help/HelpActivity.java +++ b/remoting/android/java/src/org/chromium/chromoting/help/HelpActivity.java
@@ -10,7 +10,6 @@ import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; @@ -20,7 +19,6 @@ import android.webkit.WebView; import android.webkit.WebViewClient; -import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; @@ -102,7 +100,6 @@ return true; } - @RequiresApi(Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return shouldOverrideUrlLoading(request.getUrl());
diff --git a/remoting/android/lint-baseline.xml b/remoting/android/lint-baseline.xml index f6a316d..d84c240e 100644 --- a/remoting/android/lint-baseline.xml +++ b/remoting/android/lint-baseline.xml
@@ -123,127 +123,6 @@ </issue> <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/accountswitcher/AccountManagerCompat.java" - line="25" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Chromoting.java" - line="628" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="183" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="215" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="221" - column="20"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="280" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="512" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="521" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/Desktop.java" - line="605" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" @RequiresApi(Build.VERSION_CODES.N)" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/help/HelpActivity.java" - line="105" - column="13"/> - </issue> - - <issue - id="ObsoleteSdkInt" - message="Unnecessary; SDK_INT is always >= 24" - errorLine1=" @RequiresApi(Build.VERSION_CODES.N)" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> - <location - file="../../remoting/android/java/src/org/chromium/chromoting/WebViewActivity.java" - line="53" - column="13"/> - </issue> - - <issue id="MonochromeLauncherIcon" message="The application adaptive icon is missing a monochrome tag" errorLine1="<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">"
diff --git a/remoting/host/me2me_desktop_environment.cc b/remoting/host/me2me_desktop_environment.cc index 19eb5be3..0b2dc17 100644 --- a/remoting/host/me2me_desktop_environment.cc +++ b/remoting/host/me2me_desktop_environment.cc
@@ -124,10 +124,12 @@ capabilities += protocol::kRemoteWebAuthnCapability; } -#if BUILDFLAG(IS_LINUX) && defined(REMOTING_USE_X11) +#if (BUILDFLAG(IS_LINUX) && defined(REMOTING_USE_X11)) || BUILDFLAG(IS_MAC) capabilities += " "; capabilities += protocol::kMultiStreamCapability; +#endif // (BUILDFLAG(IS_LINUX) && defined(REMOTING_USE_X11)) || ... +#if BUILDFLAG(IS_LINUX) && defined(REMOTING_USE_X11) // Client-controlled layout is only supported with Xorg+video-dummy. if (UsingVideoDummyDriver()) { capabilities += " ";
diff --git a/sandbox/win/src/interception.cc b/sandbox/win/src/interception.cc index ec9dfc0..a6fdb99 100644 --- a/sandbox/win/src/interception.cc +++ b/sandbox/win/src/interception.cc
@@ -18,7 +18,6 @@ #include "base/notreached.h" #include "base/scoped_native_library.h" #include "base/win/pe_image.h" -#include "base/win/windows_version.h" #include "sandbox/win/src/interception_internal.h" #include "sandbox/win/src/interceptors.h" #include "sandbox/win/src/internal_types.h" @@ -432,25 +431,7 @@ if (!ntdll_base) return SBOX_ERROR_NO_HANDLE; - std::unique_ptr<ServiceResolverThunk> thunk; -#if defined(_WIN64) - thunk = std::make_unique<ServiceResolverThunk>(child_->Process(), true); -#else - base::win::OSInfo* os_info = base::win::OSInfo::GetInstance(); - base::win::Version real_os_version = os_info->Kernel32Version(); - if (os_info->IsWowX86OnAMD64()) { - if (real_os_version >= base::win::Version::WIN10) - thunk.reset(new Wow64W10ResolverThunk(child_->Process(), true)); - else if (real_os_version >= base::win::Version::WIN8) - thunk.reset(new Wow64W8ResolverThunk(child_->Process(), true)); - else - thunk.reset(new Wow64ResolverThunk(child_->Process(), true)); - } else if (real_os_version >= base::win::Version::WIN8) { - thunk.reset(new Win8ResolverThunk(child_->Process(), true)); - } else { - thunk.reset(new ServiceResolverThunk(child_->Process(), true)); - } -#endif + ServiceResolverThunk thunk(child_->Process(), /*relaxed=*/true); for (auto interception : interceptions_) { const std::wstring ntdll(kNtdllName); @@ -460,7 +441,7 @@ if (INTERCEPTION_SERVICE_CALL != interception.type) return SBOX_ERROR_BAD_PARAMS; - NTSTATUS ret = thunk->Setup( + NTSTATUS ret = thunk.Setup( ntdll_base, nullptr, interception.function.c_str(), interception.interceptor.c_str(), interception.interceptor_address, &thunks->thunks[dll_data->num_thunks],
diff --git a/sandbox/win/src/service_resolver.h b/sandbox/win/src/service_resolver.h index d385810f..2cfdb409 100644 --- a/sandbox/win/src/service_resolver.h +++ b/sandbox/win/src/service_resolver.h
@@ -53,37 +53,41 @@ size_t GetThunkSize() const override; // Call this to set up ntdll_base_ which will allow for local patches. - virtual void AllowLocalPatches(); + void AllowLocalPatches(); // Verifies that the function specified by |target_name| in |target_module| is // a service and copies the data from that function into |thunk_storage|. If // |storage_bytes| is too small, then the method fails. - virtual NTSTATUS CopyThunk(const void* target_module, - const char* target_name, - BYTE* thunk_storage, - size_t storage_bytes, - size_t* storage_used); + NTSTATUS CopyThunk(const void* target_module, + const char* target_name, + BYTE* thunk_storage, + size_t storage_bytes, + size_t* storage_used); - protected: + // Checks if a target was patched correctly for a jump. This is only for use + // in testing in 32-bit builds. Will always return true on 64-bit builds. Set + // |thunk_storage| to the same pointer passed to Setup(). + bool VerifyJumpTargetForTesting(void* thunk_storage) const; + + private: // The unit test will use this member to allow local patch on a buffer. HMODULE ntdll_base_; // Handle of the child process. HANDLE process_; - private: // Returns true if the code pointer by target_ corresponds to the expected // type of function. Saves that code on the first part of the thunk pointed // by local_thunk (should be directly accessible from the parent). - virtual bool IsFunctionAService(void* local_thunk) const; + bool IsFunctionAService(void* local_thunk) const; // Performs the actual patch of target_. // local_thunk must be already fully initialized, and the first part must // contain the original code. The real type of this buffer is ServiceFullThunk // (yes, private). remote_thunk (real type ServiceFullThunk), must be // allocated on the child, and will contain the thunk data, after this call. - // Returns the apropriate status code. - virtual NTSTATUS PerformPatch(void* local_thunk, void* remote_thunk); + // Returns the appropriate status code. + NTSTATUS PerformPatch(void* local_thunk, void* remote_thunk); // Provides basically the same functionality as IsFunctionAService but it // continues even if it does not recognize the function code. remote_thunk @@ -95,74 +99,6 @@ ULONG relative_jump_; }; -// This is the concrete resolver used to perform service-call type functions -// inside ntdll.dll on WOW64 (32 bit ntdll on 64 bit Vista). -class Wow64ResolverThunk : public ServiceResolverThunk { - public: - // The service resolver needs a child process to write to. - Wow64ResolverThunk(HANDLE process, bool relaxed) - : ServiceResolverThunk(process, relaxed) {} - - Wow64ResolverThunk(const Wow64ResolverThunk&) = delete; - Wow64ResolverThunk& operator=(const Wow64ResolverThunk&) = delete; - - ~Wow64ResolverThunk() override {} - - private: - bool IsFunctionAService(void* local_thunk) const override; -}; - -// This is the concrete resolver used to perform service-call type functions -// inside ntdll.dll on WOW64 for Windows 8. -class Wow64W8ResolverThunk : public ServiceResolverThunk { - public: - // The service resolver needs a child process to write to. - Wow64W8ResolverThunk(HANDLE process, bool relaxed) - : ServiceResolverThunk(process, relaxed) {} - - Wow64W8ResolverThunk(const Wow64W8ResolverThunk&) = delete; - Wow64W8ResolverThunk& operator=(const Wow64W8ResolverThunk&) = delete; - - ~Wow64W8ResolverThunk() override {} - - private: - bool IsFunctionAService(void* local_thunk) const override; -}; - -// This is the concrete resolver used to perform service-call type functions -// inside ntdll.dll on Windows 8. -class Win8ResolverThunk : public ServiceResolverThunk { - public: - // The service resolver needs a child process to write to. - Win8ResolverThunk(HANDLE process, bool relaxed) - : ServiceResolverThunk(process, relaxed) {} - - Win8ResolverThunk(const Win8ResolverThunk&) = delete; - Win8ResolverThunk& operator=(const Win8ResolverThunk&) = delete; - - ~Win8ResolverThunk() override {} - - private: - bool IsFunctionAService(void* local_thunk) const override; -}; - -// This is the concrete resolver used to perform service-call type functions -// inside ntdll.dll on WOW64 for Windows 10. -class Wow64W10ResolverThunk : public ServiceResolverThunk { - public: - // The service resolver needs a child process to write to. - Wow64W10ResolverThunk(HANDLE process, bool relaxed) - : ServiceResolverThunk(process, relaxed) {} - - Wow64W10ResolverThunk(const Wow64W10ResolverThunk&) = delete; - Wow64W10ResolverThunk& operator=(const Wow64W10ResolverThunk&) = delete; - - ~Wow64W10ResolverThunk() override {} - - private: - bool IsFunctionAService(void* local_thunk) const override; -}; - } // namespace sandbox #endif // SANDBOX_WIN_SRC_SERVICE_RESOLVER_H_
diff --git a/sandbox/win/src/service_resolver_32.cc b/sandbox/win/src/service_resolver_32.cc index 9631dc1..f0eba39c 100644 --- a/sandbox/win/src/service_resolver_32.cc +++ b/sandbox/win/src/service_resolver_32.cc
@@ -17,43 +17,16 @@ const BYTE kMovEax = 0xB8; const BYTE kMovEdx = 0xBA; const USHORT kMovEdxEsp = 0xD48B; -const USHORT kCallPtrEdx = 0x12FF; const USHORT kCallEdx = 0xD2FF; const BYTE kCallEip = 0xE8; const BYTE kRet = 0xC2; const BYTE kRet2 = 0xC3; const USHORT kJmpEdx = 0xE2FF; -const USHORT kXorEcx = 0xC933; -const ULONG kLeaEdx = 0x0424548D; -const ULONG kCallFs1 = 0xC015FF64; -const USHORT kCallFs2 = 0; -const BYTE kCallFs3 = 0; -const BYTE kAddEsp1 = 0x83; -const USHORT kAddEsp2 = 0x4C4; const BYTE kJmp32 = 0xE9; const USHORT kSysenter = 0x340F; -// Service code for 32 bit systems. -// NOTE: on win2003 "call dword ptr [edx]" is "call edx". -struct ServiceEntry { - // This struct contains roughly the following code: - // 00 mov eax,25h - // 05 mov edx,offset SharedUserData!SystemCallStub (7ffe0300) - // 0a call dword ptr [edx] - // 0c ret 2Ch - // 0f nop - BYTE mov_eax; // = B8 - ULONG service_id; - BYTE mov_edx; // = BA - ULONG stub; - USHORT call_ptr_edx; // = FF 12 - BYTE ret; // = C2 - USHORT num_params; - BYTE nop; -}; - -// Service code for 32 bit Windows 8. -struct ServiceEntryW8 { +// Service code for 32 bit Windows. Introduced in Windows 8. +struct ServiceEntry32 { // This struct contains the following code: // 00 b825000000 mov eax,25h // 05 e803000000 call eip+3 @@ -74,60 +47,13 @@ USHORT nop; }; -// Service code for a 32 bit process running on a 64 bit os. -struct Wow64Entry { - // This struct may contain one of two versions of code: - // 1. For XP, Vista and 2K3: - // 00 b825000000 mov eax, 25h - // 05 33c9 xor ecx, ecx - // 07 8d542404 lea edx, [esp + 4] - // 0b 64ff15c0000000 call dword ptr fs:[0C0h] - // 12 c22c00 ret 2Ch - // - // 2. For Windows 7: - // 00 b825000000 mov eax, 25h - // 05 33c9 xor ecx, ecx - // 07 8d542404 lea edx, [esp + 4] - // 0b 64ff15c0000000 call dword ptr fs:[0C0h] - // 12 83c404 add esp, 4 - // 15 c22c00 ret 2Ch - // - // So we base the structure on the bigger one: - BYTE mov_eax; // = B8 - ULONG service_id; - USHORT xor_ecx; // = 33 C9 - ULONG lea_edx; // = 8D 54 24 04 - ULONG call_fs1; // = 64 FF 15 C0 - USHORT call_fs2; // = 00 00 - BYTE call_fs3; // = 00 - BYTE add_esp1; // = 83 or ret - USHORT add_esp2; // = C4 04 or num_params - BYTE ret; // = C2 - USHORT num_params; -}; - -// Service code for a 32 bit process running on 64 bit Windows 8. -struct Wow64EntryW8 { - // 00 b825000000 mov eax, 25h - // 05 64ff15c0000000 call dword ptr fs:[0C0h] - // 0b c22c00 ret 2Ch - // 0f 90 nop - BYTE mov_eax; // = B8 - ULONG service_id; - ULONG call_fs1; // = 64 FF 15 C0 - USHORT call_fs2; // = 00 00 - BYTE call_fs3; // = 00 - BYTE ret; // = C2 - USHORT num_params; - BYTE nop; -}; - -// Service code for a 32 bit process running on 64 bit Windows 10. -struct Wow64EntryW10 { +// Service code for a 32 bit process under Wow64. Introduced in Windows 10. +// Also used for the patching process. +struct ServiceEntryWow64 { // 00 b828000000 mov eax, 28h // 05 bab0d54877 mov edx, 7748D5B0h // 09 ffd2 call edx - // 0b c22800 ret 28h + // 0c c22800 ret 28h BYTE mov_eax; // = B8 ULONG service_id; BYTE mov_edx; // = BA @@ -135,27 +61,86 @@ USHORT call_edx; // = FF D2 BYTE ret; // = C2 USHORT num_params; + BYTE nop; }; // Make sure that relaxed patching works as expected. -const size_t kMinServiceSize = offsetof(ServiceEntry, ret); -static_assert(sizeof(ServiceEntryW8) >= kMinServiceSize, - "wrong service length"); -static_assert(sizeof(Wow64Entry) >= kMinServiceSize, "wrong service length"); -static_assert(sizeof(Wow64EntryW8) >= kMinServiceSize, "wrong service length"); +const size_t kMinServiceSize = offsetof(ServiceEntryWow64, ret); +// Maximum size of the entry, was the size of the Windows Vista WoW64 entry. +// Keep this fixed for compatibility reasons. +const size_t kMaxServiceSize = 24; +static_assert(sizeof(ServiceEntry32) >= kMinServiceSize, + "wrong minimum service length"); +static_assert(sizeof(ServiceEntry32) < kMaxServiceSize, + "wrong maximum service length"); +static_assert(sizeof(ServiceEntryWow64) >= kMinServiceSize, + "wrong minimum service length"); +static_assert(sizeof(ServiceEntryWow64) < kMaxServiceSize, + "wrong maximum service length"); struct ServiceFullThunk { union { - ServiceEntry original; - ServiceEntryW8 original_w8; - Wow64Entry wow_64; - Wow64EntryW8 wow_64_w8; + ServiceEntryWow64 original; + // Pad the entry to the maximum size. + char dummy[kMaxServiceSize]; }; int internal_thunk; // Dummy member to the beginning of the internal thunk. }; #pragma pack(pop) +bool IsWow64Process() { + // We don't need to use IsWow64Process2 as this returns the expected result + // when running in the ARM64 x86 emulator. + BOOL is_wow64 = FALSE; + return ::IsWow64Process(::GetCurrentProcess(), &is_wow64) && is_wow64; +} + +bool IsFunctionAService32(HANDLE process, void* target, void* local_thunk) { + ServiceEntry32 function_code; + SIZE_T read; + if (!::ReadProcessMemory(process, target, &function_code, + sizeof(function_code), &read)) { + return false; + } + + if (sizeof(function_code) != read) + return false; + + if (kMovEax != function_code.mov_eax || kCallEip != function_code.call_eip || + function_code.call_offset != 3 || kRet != function_code.ret_p || + kMovEdxEsp != function_code.mov_edx_esp || + kSysenter != function_code.sysenter || kRet2 != function_code.ret) { + return false; + } + + // Save the verified code + memcpy(local_thunk, &function_code, sizeof(function_code)); + + return true; +} + +bool IsFunctionAServiceWow64(HANDLE process, void* target, void* local_thunk) { + ServiceEntryWow64 function_code; + SIZE_T read; + if (!::ReadProcessMemory(process, target, &function_code, + sizeof(function_code), &read)) { + return false; + } + + if (sizeof(function_code) != read) + return false; + + if (kMovEax != function_code.mov_eax || kMovEdx != function_code.mov_edx || + kCallEdx != function_code.call_edx || kRet != function_code.ret) { + return false; + } + + // Save the verified code + memcpy(local_thunk, &function_code, sizeof(function_code)); + return true; +} + } // namespace namespace sandbox { @@ -224,69 +209,14 @@ } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { - ServiceEntry function_code; - SIZE_T read; - if (!::ReadProcessMemory(process_, target_, &function_code, - sizeof(function_code), &read)) { - return false; - } - - if (sizeof(function_code) != read) - return false; - - if (kMovEax != function_code.mov_eax || kMovEdx != function_code.mov_edx || - (kCallPtrEdx != function_code.call_ptr_edx && - kCallEdx != function_code.call_ptr_edx) || - kRet != function_code.ret) { - return false; - } - - // Find the system call pointer if we don't already have it. - if (kCallEdx != function_code.call_ptr_edx) { - DWORD ki_system_call; - if (!::ReadProcessMemory(process_, - base::bit_cast<const void*>(function_code.stub), - &ki_system_call, sizeof(ki_system_call), &read)) { - return false; - } - - if (sizeof(ki_system_call) != read) - return false; - - HMODULE module_1, module_2; - // last check, call_stub should point to a KiXXSystemCall function on ntdll - if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | - GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - base::bit_cast<const wchar_t*>(ki_system_call), - &module_1)) { - return false; - } - - if (ntdll_base_) { - // This path is only taken when running the unit tests. We want to be - // able to patch a buffer in memory, so target_ is not inside ntdll. - module_2 = ntdll_base_; - } else { - if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | - GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast<const wchar_t*>(target_), - &module_2)) - return false; - } - - if (module_1 != module_2) - return false; - } - - // Save the verified code - memcpy(local_thunk, &function_code, sizeof(function_code)); - - return true; + static bool is_wow64 = IsWow64Process(); + return is_wow64 ? IsFunctionAServiceWow64(process_, target_, local_thunk) + : IsFunctionAService32(process_, target_, local_thunk); } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { - ServiceEntry intercepted_code; + ServiceEntryWow64 intercepted_code; size_t bytes_to_write = sizeof(intercepted_code); ServiceFullThunk* full_local_thunk = reinterpret_cast<ServiceFullThunk*>(local_thunk); @@ -299,15 +229,15 @@ intercepted_code.mov_eax = kMovEax; intercepted_code.service_id = full_local_thunk->original.service_id; intercepted_code.mov_edx = kMovEdx; - intercepted_code.stub = + intercepted_code.mov_edx_param = base::bit_cast<ULONG>(&full_remote_thunk->internal_thunk); - intercepted_code.call_ptr_edx = kJmpEdx; + intercepted_code.call_edx = kJmpEdx; bytes_to_write = kMinServiceSize; if (relative_jump_) { intercepted_code.mov_eax = kJmp32; intercepted_code.service_id = relative_jump_; - bytes_to_write = offsetof(ServiceEntry, mov_edx); + bytes_to_write = offsetof(ServiceEntryWow64, mov_edx); } // setup the thunk @@ -343,7 +273,7 @@ bool ServiceResolverThunk::SaveOriginalFunction(void* local_thunk, void* remote_thunk) { - ServiceEntry function_code; + ServiceEntryWow64 function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) { @@ -379,100 +309,18 @@ return true; } -bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const { - Wow64Entry function_code; - SIZE_T read; - if (!::ReadProcessMemory(process_, target_, &function_code, - sizeof(function_code), &read)) { +bool ServiceResolverThunk::VerifyJumpTargetForTesting( + void* thunk_storage) const { + const size_t kJmp32Size = 5; + ServiceEntryWow64* patched = static_cast<ServiceEntryWow64*>(target_); + if (kJmp32 != patched->mov_eax) { return false; } - if (sizeof(function_code) != read) - return false; - - if (kMovEax != function_code.mov_eax || kXorEcx != function_code.xor_ecx || - kLeaEdx != function_code.lea_edx || kCallFs1 != function_code.call_fs1 || - kCallFs2 != function_code.call_fs2 || - kCallFs3 != function_code.call_fs3) { - return false; - } - - if ((kAddEsp1 == function_code.add_esp1 && - kAddEsp2 == function_code.add_esp2 && kRet == function_code.ret) || - kRet == function_code.add_esp1) { - // Save the verified code - memcpy(local_thunk, &function_code, sizeof(function_code)); - return true; - } - - return false; -} - -bool Wow64W8ResolverThunk::IsFunctionAService(void* local_thunk) const { - Wow64EntryW8 function_code; - SIZE_T read; - if (!::ReadProcessMemory(process_, target_, &function_code, - sizeof(function_code), &read)) { - return false; - } - - if (sizeof(function_code) != read) - return false; - - if (kMovEax != function_code.mov_eax || kCallFs1 != function_code.call_fs1 || - kCallFs2 != function_code.call_fs2 || - kCallFs3 != function_code.call_fs3 || kRet != function_code.ret) { - return false; - } - - // Save the verified code - memcpy(local_thunk, &function_code, sizeof(function_code)); - return true; -} - -bool Win8ResolverThunk::IsFunctionAService(void* local_thunk) const { - ServiceEntryW8 function_code; - SIZE_T read; - if (!::ReadProcessMemory(process_, target_, &function_code, - sizeof(function_code), &read)) { - return false; - } - - if (sizeof(function_code) != read) - return false; - - if (kMovEax != function_code.mov_eax || kCallEip != function_code.call_eip || - function_code.call_offset != 3 || kRet != function_code.ret_p || - kMovEdxEsp != function_code.mov_edx_esp || - kSysenter != function_code.sysenter || kRet2 != function_code.ret) { - return false; - } - - // Save the verified code - memcpy(local_thunk, &function_code, sizeof(function_code)); - - return true; -} - -bool Wow64W10ResolverThunk::IsFunctionAService(void* local_thunk) const { - Wow64EntryW10 function_code; - SIZE_T read; - if (!::ReadProcessMemory(process_, target_, &function_code, - sizeof(function_code), &read)) { - return false; - } - - if (sizeof(function_code) != read) - return false; - - if (kMovEax != function_code.mov_eax || kMovEdx != function_code.mov_edx || - kCallEdx != function_code.call_edx || kRet != function_code.ret) { - return false; - } - - // Save the verified code - memcpy(local_thunk, &function_code, sizeof(function_code)); - return true; + ULONG source_addr = base::bit_cast<ULONG>(target_); + ULONG target_addr = base::bit_cast<ULONG>(thunk_storage); + return target_addr + kMaxServiceSize - kJmp32Size - source_addr == + patched->service_id; } } // namespace sandbox
diff --git a/sandbox/win/src/service_resolver_64.cc b/sandbox/win/src/service_resolver_64.cc index dfe4637..9a80ca32 100644 --- a/sandbox/win/src/service_resolver_64.cc +++ b/sandbox/win/src/service_resolver_64.cc
@@ -282,9 +282,8 @@ return STATUS_SUCCESS; } -bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const { - NOTREACHED_NT(); - return false; +bool ServiceResolverThunk::VerifyJumpTargetForTesting(void*) const { + return true; } } // namespace sandbox
diff --git a/sandbox/win/src/service_resolver_unittest.cc b/sandbox/win/src/service_resolver_unittest.cc index 0d02d910..76687f3 100644 --- a/sandbox/win/src/service_resolver_unittest.cc +++ b/sandbox/win/src/service_resolver_unittest.cc
@@ -12,99 +12,53 @@ #include "base/bit_cast.h" #include "base/memory/raw_ptr.h" -#include "base/win/windows_version.h" #include "sandbox/win/src/resolver.h" #include "sandbox/win/src/sandbox_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { -class ResolverThunkTest { +// This is the concrete resolver used to perform service-call type functions +// inside ntdll.dll. +class ServiceResolverTest : public sandbox::ServiceResolverThunk { public: - virtual ~ResolverThunkTest() {} + // The service resolver needs a child process to write to. + explicit ServiceResolverTest(bool relaxed) + : sandbox::ServiceResolverThunk(::GetCurrentProcess(), relaxed) {} - virtual sandbox::ServiceResolverThunk* resolver() = 0; + ServiceResolverTest(const ServiceResolverTest&) = delete; + ServiceResolverTest& operator=(const ServiceResolverTest&) = delete; // Sets the interception target to the desired address. void set_target(void* target) { fake_target_ = target; } protected: - // Holds the address of the fake target. - raw_ptr<void> fake_target_; -}; - -// This is the concrete resolver used to perform service-call type functions -// inside ntdll.dll. -template <typename T> -class ResolverThunkTestImpl : public T, public ResolverThunkTest { - public: - // The service resolver needs a child process to write to. - explicit ResolverThunkTestImpl(bool relaxed) - : T(::GetCurrentProcess(), relaxed) {} - - ResolverThunkTestImpl(const ResolverThunkTestImpl&) = delete; - ResolverThunkTestImpl& operator=(const ResolverThunkTestImpl&) = delete; - - sandbox::ServiceResolverThunk* resolver() { return this; } - - protected: // Overrides Resolver::Init - virtual NTSTATUS Init(const void* target_module, - const void* interceptor_module, - const char* target_name, - const char* interceptor_name, - const void* interceptor_entry_point, - void* thunk_storage, - size_t storage_bytes) { + NTSTATUS Init(const void* target_module, + const void* interceptor_module, + const char* target_name, + const char* interceptor_name, + const void* interceptor_entry_point, + void* thunk_storage, + size_t storage_bytes) final { NTSTATUS ret = STATUS_SUCCESS; - ret = T::Init(target_module, interceptor_module, target_name, - interceptor_name, interceptor_entry_point, thunk_storage, - storage_bytes); + ret = sandbox::ServiceResolverThunk::Init( + target_module, interceptor_module, target_name, interceptor_name, + interceptor_entry_point, thunk_storage, storage_bytes); EXPECT_EQ(STATUS_SUCCESS, ret); this->target_ = fake_target_; return ret; } + + // Holds the address of the fake target. + raw_ptr<void> fake_target_; }; -typedef ResolverThunkTestImpl<sandbox::ServiceResolverThunk> WinXpResolverTest; - -#if !defined(_WIN64) -typedef ResolverThunkTestImpl<sandbox::Win8ResolverThunk> Win8ResolverTest; -typedef ResolverThunkTestImpl<sandbox::Wow64ResolverThunk> Wow64ResolverTest; -typedef ResolverThunkTestImpl<sandbox::Wow64W8ResolverThunk> - Wow64W8ResolverTest; -typedef ResolverThunkTestImpl<sandbox::Wow64W10ResolverThunk> - Wow64W10ResolverTest; -#endif - -const BYTE kJump32 = 0xE9; - -void CheckJump(void* source, void* target) { -#pragma pack(push) -#pragma pack(1) - struct Code { - BYTE jump; - ULONG delta; - }; -#pragma pack(pop) - -#if defined(_WIN64) - FAIL() << "Running 32-bit codepath"; -#else - Code* patched = reinterpret_cast<Code*>(source); - EXPECT_EQ(kJump32, patched->jump); - - ULONG source_addr = base::bit_cast<ULONG>(source); - ULONG target_addr = base::bit_cast<ULONG>(target); - EXPECT_EQ(target_addr + 19 - source_addr, patched->delta); -#endif -} - NTSTATUS PatchNtdllWithResolver(const char* function, bool relaxed, - ResolverThunkTest* thunk_test) { + ServiceResolverTest& resolver) { HMODULE ntdll_base = ::GetModuleHandle(L"ntdll.dll"); EXPECT_TRUE(ntdll_base); @@ -117,21 +71,20 @@ BYTE service[50]; memcpy(service, target, sizeof(service)); - thunk_test->set_target(service); + resolver.set_target(service); - sandbox::ServiceResolverThunk* resolver = thunk_test->resolver(); // Any pointer will do as an interception_entry_point - void* function_entry = resolver; - size_t thunk_size = resolver->GetThunkSize(); - std::unique_ptr<char[]> thunk(new char[thunk_size]); + void* function_entry = &resolver; + size_t thunk_size = resolver.GetThunkSize(); + std::unique_ptr<char[]> thunk = std::make_unique<char[]>(thunk_size); size_t used; - resolver->AllowLocalPatches(); + resolver.AllowLocalPatches(); - NTSTATUS ret = - resolver->Setup(ntdll_base, nullptr, function, nullptr, function_entry, - thunk.get(), thunk_size, &used); + NTSTATUS ret = resolver.Setup(ntdll_base, nullptr, function, nullptr, + function_entry, thunk.get(), thunk_size, &used); if (NT_SUCCESS(ret)) { + const BYTE kJump32 = 0xE9; EXPECT_EQ(thunk_size, used); EXPECT_NE(0, memcmp(service, target, sizeof(service))); EXPECT_NE(kJump32, service[0]); @@ -139,30 +92,18 @@ if (relaxed) { // It's already patched, let's patch again, and simulate a direct patch. service[0] = kJump32; - ret = resolver->Setup(ntdll_base, nullptr, function, nullptr, - function_entry, thunk.get(), thunk_size, &used); - CheckJump(service, thunk.get()); + ret = resolver.Setup(ntdll_base, nullptr, function, nullptr, + function_entry, thunk.get(), thunk_size, &used); + EXPECT_TRUE(resolver.VerifyJumpTargetForTesting(thunk.get())); } } return ret; } -std::unique_ptr<ResolverThunkTest> GetTestResolver(bool relaxed) { -#if defined(_WIN64) - return std::make_unique<WinXpResolverTest>(relaxed); -#else - base::win::OSInfo* os_info = base::win::OSInfo::GetInstance(); - if (os_info->IsWowX86OnAMD64()) - return std::make_unique<Wow64W10ResolverTest>(relaxed); - - return std::make_unique<Win8ResolverTest>(relaxed); -#endif -} - NTSTATUS PatchNtdll(const char* function, bool relaxed) { - std::unique_ptr<ResolverThunkTest> thunk_test = GetTestResolver(relaxed); - return PatchNtdllWithResolver(function, relaxed, thunk_test.get()); + ServiceResolverTest resolver(relaxed); + return PatchNtdllWithResolver(function, relaxed, resolver); } TEST(ServiceResolverTest, PatchesServices) { @@ -213,26 +154,26 @@ TEST(ServiceResolverTest, MultiplePatchedServices) { // We don't support "relaxed mode" for Win64 apps. #if !defined(_WIN64) - std::unique_ptr<ResolverThunkTest> thunk_test = GetTestResolver(true); - NTSTATUS ret = PatchNtdllWithResolver("NtClose", true, thunk_test.get()); + ServiceResolverTest thunk_test(true); + NTSTATUS ret = PatchNtdllWithResolver("NtClose", true, thunk_test); EXPECT_EQ(STATUS_SUCCESS, ret) << "NtClose, last error: " << ::GetLastError(); - ret = PatchNtdllWithResolver("NtCreateFile", true, thunk_test.get()); + ret = PatchNtdllWithResolver("NtCreateFile", true, thunk_test); EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateFile, last error: " << ::GetLastError(); - ret = PatchNtdllWithResolver("NtCreateMutant", true, thunk_test.get()); + ret = PatchNtdllWithResolver("NtCreateMutant", true, thunk_test); EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateMutant, last error: " << ::GetLastError(); - ret = PatchNtdllWithResolver("NtMapViewOfSection", true, thunk_test.get()); + ret = PatchNtdllWithResolver("NtMapViewOfSection", true, thunk_test); EXPECT_EQ(STATUS_SUCCESS, ret) << "NtMapViewOfSection, last error: " << ::GetLastError(); #endif } TEST(ServiceResolverTest, LocalPatchesAllowed) { - std::unique_ptr<ResolverThunkTest> thunk_test = GetTestResolver(true); + ServiceResolverTest resolver(true); HMODULE ntdll_base = ::GetModuleHandle(L"ntdll.dll"); ASSERT_TRUE(ntdll_base); @@ -245,26 +186,25 @@ BYTE service[50]; memcpy(service, target, sizeof(service)); - thunk_test->set_target(service); + resolver.set_target(service); - sandbox::ServiceResolverThunk* resolver = thunk_test->resolver(); // Any pointer will do as an interception_entry_point - void* function_entry = resolver; - size_t thunk_size = resolver->GetThunkSize(); - std::unique_ptr<char[]> thunk(new char[thunk_size]); + void* function_entry = &resolver; + size_t thunk_size = resolver.GetThunkSize(); + std::unique_ptr<char[]> thunk = std::make_unique<char[]>(thunk_size); size_t used; NTSTATUS ret = STATUS_UNSUCCESSFUL; // First try patching without having allowed local patches. - ret = resolver->Setup(ntdll_base, nullptr, kFunctionName, nullptr, - function_entry, thunk.get(), thunk_size, &used); + ret = resolver.Setup(ntdll_base, nullptr, kFunctionName, nullptr, + function_entry, thunk.get(), thunk_size, &used); EXPECT_FALSE(NT_SUCCESS(ret)); // Now allow local patches and check that things work. - resolver->AllowLocalPatches(); - ret = resolver->Setup(ntdll_base, nullptr, kFunctionName, nullptr, - function_entry, thunk.get(), thunk_size, &used); + resolver.AllowLocalPatches(); + ret = resolver.Setup(ntdll_base, nullptr, kFunctionName, nullptr, + function_entry, thunk.get(), thunk_size, &used); EXPECT_EQ(STATUS_SUCCESS, ret); }
diff --git a/services/network/public/cpp/first_party_sets_mojom_traits.cc b/services/network/public/cpp/first_party_sets_mojom_traits.cc index d07fa34..fed0c4a5 100644 --- a/services/network/public/cpp/first_party_sets_mojom_traits.cc +++ b/services/network/public/cpp/first_party_sets_mojom_traits.cc
@@ -5,6 +5,7 @@ #include "services/network/public/cpp/first_party_sets_mojom_traits.h" #include "base/containers/flat_map.h" +#include "base/ranges/algorithm.h" #include "base/types/optional_util.h" #include "base/version.h" #include "mojo/public/cpp/base/version_mojom_traits.h" @@ -155,13 +156,19 @@ return false; base::flat_map<net::SchemefulSite, net::FirstPartySetEntry> entries; - if (!sets.ReadSets(&entries)) + if (public_sets_version.IsValid() && !sets.ReadSets(&entries)) return false; base::flat_map<net::SchemefulSite, net::SchemefulSite> aliases; - if (!sets.ReadAliases(&aliases)) + if (public_sets_version.IsValid() && !sets.ReadAliases(&aliases)) return false; + if (!base::ranges::all_of(aliases, [&](const auto& pair) { + return entries.contains(pair.second); + })) { + return false; + } + net::FirstPartySetsContextConfig manual_config; if (!sets.ReadManualConfig(&manual_config)) return false;
diff --git a/services/network/public/cpp/first_party_sets_mojom_traits_unittest.cc b/services/network/public/cpp/first_party_sets_mojom_traits_unittest.cc index 79b1ac4..b799972 100644 --- a/services/network/public/cpp/first_party_sets_mojom_traits_unittest.cc +++ b/services/network/public/cpp/first_party_sets_mojom_traits_unittest.cc
@@ -14,12 +14,16 @@ #include "net/first_party_sets/first_party_sets_context_config.h" #include "net/first_party_sets/global_first_party_sets.h" #include "services/network/public/mojom/first_party_sets.mojom.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace network { namespace { +using testing::Key; +using testing::UnorderedElementsAre; + TEST(FirstPartySetsTraitsTest, Roundtrips_SiteIndex) { net::FirstPartySetEntry::SiteIndex original(1337); net::FirstPartySetEntry::SiteIndex round_tripped; @@ -151,6 +155,44 @@ EXPECT_FALSE(round_tripped.empty()); } +TEST(FirstPartySetsTraitsTest, GlobalFirstPartySets_InvalidVersion) { + net::SchemefulSite a(GURL("https://a.test")); + net::SchemefulSite b(GURL("https://b.test")); + net::SchemefulSite b_cctld(GURL("https://b.cctld")); + net::SchemefulSite c(GURL("https://c.test")); + + net::GlobalFirstPartySets original( + base::Version(), + /*entries=*/ + { + {a, + net::FirstPartySetEntry(a, net::SiteType::kPrimary, absl::nullopt)}, + {b, net::FirstPartySetEntry(a, net::SiteType::kAssociated, 0)}, + {c, + net::FirstPartySetEntry(a, net::SiteType::kService, absl::nullopt)}, + }, + /*aliases=*/{{b_cctld, b}}); + + original.ApplyManuallySpecifiedSet( + {{a, net::FirstPartySetEntry(a, net::SiteType::kPrimary, absl::nullopt)}, + {b, net::FirstPartySetEntry(a, net::SiteType::kAssociated, 0)}}); + + net::GlobalFirstPartySets round_tripped; + + EXPECT_TRUE( + mojo::test::SerializeAndDeserialize<network::mojom::GlobalFirstPartySets>( + original, round_tripped)); + + EXPECT_FALSE(round_tripped.empty()); + + // base::Version::operator== crashes for invalid versions, so we don't check + // equality of `round_tripped` and `original` that way. However, we can verify + // that the original entries and alias are not present in `round_tripped`: + EXPECT_THAT(round_tripped.FindEntries({a, b, b_cctld, c}, + net::FirstPartySetsContextConfig()), + UnorderedElementsAre(Key(a), Key(b))); +} + TEST(FirstPartySetsTraitsTest, RoundTrips_FirstPartySetsContextConfig) { net::SchemefulSite a(GURL("https://a.test")); net::SchemefulSite b(GURL("https://b.test"));
diff --git a/services/network/public/mojom/first_party_sets.mojom b/services/network/public/mojom/first_party_sets.mojom index a7b8beb..a852322f 100644 --- a/services/network/public/mojom/first_party_sets.mojom +++ b/services/network/public/mojom/first_party_sets.mojom
@@ -82,7 +82,9 @@ // This struct must match the class fields defined in // //net/first_party_sets/global_first_party_sets.h. struct GlobalFirstPartySets { - // The version of the public sets component. + // The version of the public sets component. This may be invalid if the + // "First-Party Sets" component has not been installed yet, or has been + // corrupted. Entries and aliases from invalid components are ignored. mojo_base.mojom.Version public_sets_version; // The mapping from site to FPS entry from public sets.
diff --git a/testing/buildbot/buildbot_json_magic_substitutions.py b/testing/buildbot/buildbot_json_magic_substitutions.py index 04407dd..4193f31 100644 --- a/testing/buildbot/buildbot_json_magic_substitutions.py +++ b/testing/buildbot/buildbot_json_magic_substitutions.py
@@ -170,12 +170,16 @@ # we swap which machines we're using. is_webgpu_cts = test_name.startswith('webgpu_cts') or test_config.get( 'telemetry_test_name') == 'webgpu_cts' - is_webgl_cts = 'webgl_conformance' in test_name or test_config.get( - 'telemetry_test_name') == 'webgl_conformance' + is_webgl_cts = (any(test_name in n + for n in ('webgl_conformance', 'webgl1_conformance', + 'webgl2_conformance')) + or test_config.get('telemetry_test_name') in ( + 'webgl1_conformance', 'webgl2_conformance')) if os_type == 'win' and (is_webgl_cts or is_webgpu_cts): for gpu in _GetGpusFromTestConfig(test_config): if gpu.startswith('8086'): - if is_webgpu_cts: + # Especially flaky on '8086:9bc5' per crbug.com/1392149 + if is_webgpu_cts or gpu.startswith('8086:9bc5'): return ['--jobs=1'] return ['--jobs=2']
diff --git a/testing/buildbot/buildbot_json_magic_substitutions_unittest.py b/testing/buildbot/buildbot_json_magic_substitutions_unittest.py index 4bcc208..b1d123b7 100755 --- a/testing/buildbot/buildbot_json_magic_substitutions_unittest.py +++ b/testing/buildbot/buildbot_json_magic_substitutions_unittest.py
@@ -202,7 +202,10 @@ amd_config = CreateConfigWithGpus(['1002:device1-driver']) for gpu_config in [intel_config, amd_config]: for name, telemetry_test_name in [('webgl_conformance', None), - (None, 'webgl_conformance')]: + ('webgl1_conformance', None), + ('webgl2_conformance', None), + (None, 'webgl1_conformance'), + (None, 'webgl2_conformance')]: is_intel = intel_config == gpu_config c = gpu_config.copy() if name:
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 84f5e79..077bc344 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1332,2865 +1332,6 @@ } ] }, - "Marshmallow 64 bit Tester": { - "gtest_tests": [ - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "absl_hardening_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "absl_hardening_tests", - "test_id_prefix": "ninja://third_party/abseil-cpp:absl_hardening_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "android_browsertests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 2 - }, - "test": "android_browsertests", - "test_id_prefix": "ninja://chrome/test:android_browsertests/" - }, - { - "args": [ - "--test-launcher-batch-limit=1", - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "android_sync_integration_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "android_sync_integration_tests", - "test_id_prefix": "ninja://chrome/test:android_sync_integration_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "android_webview_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "android_webview_unittests", - "test_id_prefix": "ninja://android_webview/test:android_webview_unittests/" - }, - { - "args": [ - "-v" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "angle_unittests", - "test_id_prefix": "ninja://third_party/angle/src/tests:angle_unittests/", - "use_isolated_scripts_api": true - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "base_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "base_unittests", - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "blink_common_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_common_unittests", - "test_id_prefix": "ninja://third_party/blink/common:blink_common_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "blink_heap_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_heap_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform/heap:blink_heap_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "blink_platform_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_platform_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform:blink_platform_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "webkit_unit_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "webkit_unit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "hard_timeout": 1200, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 6 - }, - "test": "blink_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/controller:blink_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "boringssl_crypto_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "boringssl_crypto_tests", - "test_id_prefix": "ninja://third_party/boringssl:boringssl_crypto_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "boringssl_ssl_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "boringssl_ssl_tests", - "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" - }, - { - "args": [ - "--gtest_filter=-*UsingRealWebcam*", - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "capture_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "capture_unittests", - "test_id_prefix": "ninja://media/capture:capture_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cast_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cast_unittests", - "test_id_prefix": "ninja://media/cast:cast_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cc_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cc_unittests", - "test_id_prefix": "ninja://cc:cc_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_modern_public_bundle_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_modern_public_bundle_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_modern_public_bundle_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_public_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_public_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_public_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--git-revision=${got_revision}" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_public_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "precommit_args": [ - "--gerrit-issue=${patch_issue}", - "--gerrit-patchset=${patch_set}", - "--buildbucket-id=${buildbucket_build_id}" - ], - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 14 - }, - "test": "chrome_public_test_apk", - "test_id_prefix": "ninja://chrome/android:chrome_public_test_apk/" - }, - { - "args": [ - "--shared-prefs-file=//chrome/android/shared_preference_files/test/vr_cardboard_skipdon_setupcomplete.json", - "--additional-apk=//third_party/gvr-android-sdk/test-apks/vr_services/vr_services_current.apk", - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_public_test_vr_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 2 - }, - "test": "chrome_public_test_vr_apk", - "test_id_prefix": "ninja://chrome/android:chrome_public_test_vr_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--git-revision=${got_revision}" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_public_unit_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "precommit_args": [ - "--gerrit-issue=${patch_issue}", - "--gerrit-patchset=${patch_set}", - "--buildbucket-id=${buildbucket_build_id}" - ], - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 2 - }, - "test": "chrome_public_unit_test_apk", - "test_id_prefix": "ninja://chrome/android:chrome_public_unit_test_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_webapk_integration_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_webapk_integration_tests", - "test_id_prefix": "ninja://chrome/test/android:chrome_webapk_integration_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "components_browsertests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "components_browsertests", - "test_id_prefix": "ninja://components:components_browsertests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "components_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 6 - }, - "test": "components_unittests", - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_browsertests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 15 - }, - "test": "content_browsertests", - "test_id_prefix": "ninja://content/test:content_browsertests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_shell_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test": "content_shell_test_apk", - "test_id_prefix": "ninja://content/shell/android:content_shell_test_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test": "content_unittests", - "test_id_prefix": "ninja://content/test:content_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "crashpad_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "crashpad_tests", - "test_id_prefix": "ninja://third_party/crashpad/crashpad:crashpad_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "crypto_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "crypto_unittests", - "test_id_prefix": "ninja://crypto:crypto_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "device_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "device_unittests", - "test_id_prefix": "ninja://device:device_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "display_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "display_unittests", - "test_id_prefix": "ninja://ui/display:display_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "events_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "events_unittests", - "test_id_prefix": "ninja://ui/events:events_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gcm_unit_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gcm_unit_tests", - "test_id_prefix": "ninja://google_apis/gcm:gcm_unit_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gfx_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gfx_unittests", - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gin_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gin_unittests", - "test_id_prefix": "ninja://gin:gin_unittests/" - }, - { - "args": [ - "--use-cmd-decoder=validating", - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gl_tests_validating" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "gl_tests_validating", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gl_tests", - "test_id_prefix": "ninja://gpu:gl_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gl_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gl_unittests", - "test_id_prefix": "ninja://ui/gl:gl_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "google_apis_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "google_apis_unittests", - "test_id_prefix": "ninja://google_apis:google_apis_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gpu_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gpu_unittests", - "test_id_prefix": "ninja://gpu:gpu_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gwp_asan_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gwp_asan_unittests", - "test_id_prefix": "ninja://components/gwp_asan:gwp_asan_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ipc_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ipc_tests", - "test_id_prefix": "ninja://ipc:ipc_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "latency_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "latency_unittests", - "test_id_prefix": "ninja://ui/latency:latency_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "libjingle_xmpp_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "libjingle_xmpp_unittests", - "test_id_prefix": "ninja://third_party/libjingle_xmpp:libjingle_xmpp_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "liburlpattern_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "liburlpattern_unittests", - "test_id_prefix": "ninja://third_party/liburlpattern:liburlpattern_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "media_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "media_unittests", - "test_id_prefix": "ninja://media:media_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "midi_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "midi_unittests", - "test_id_prefix": "ninja://media/midi:midi_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "mojo_test_apk", - "test_id_prefix": "ninja://mojo/public/java/system:mojo_test_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "mojo_unittests", - "test_id_prefix": "ninja://mojo:mojo_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "net_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test": "net_unittests", - "test_id_prefix": "ninja://net:net_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "sandbox_linux_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "sandbox_linux_unittests", - "test_id_prefix": "ninja://sandbox/linux:sandbox_linux_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "services_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "services_unittests", - "test_id_prefix": "ninja://services:services_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "shell_dialogs_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "shell_dialogs_unittests", - "test_id_prefix": "ninja://ui/shell_dialogs:shell_dialogs_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "skia_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "skia_unittests", - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "sql_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "sql_unittests", - "test_id_prefix": "ninja://sql:sql_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "storage_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "storage_unittests", - "test_id_prefix": "ninja://storage:storage_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_android_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ui_android_unittests", - "test_id_prefix": "ninja://ui/android:ui_android_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_base_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ui_base_unittests", - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_touch_selection_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ui_touch_selection_unittests", - "test_id_prefix": "ninja://ui/touch_selection:ui_touch_selection_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "unit_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 2 - }, - "test": "unit_tests", - "test_id_prefix": "ninja://chrome/test:unit_tests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "url_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "url_unittests", - "test_id_prefix": "ninja://url:url_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "viz_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "viz_unittests", - "test_id_prefix": "ninja://components/viz:viz_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "vr_android_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "vr_android_unittests", - "test_id_prefix": "ninja://chrome/browser/android/vr:vr_android_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "vr_common_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "vr_common_unittests", - "test_id_prefix": "ninja://chrome/browser/vr:vr_common_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "vr_pixeltests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "vr_pixeltests", - "test_id_prefix": "ninja://chrome/browser/vr:vr_pixeltests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "webview_instrumentation_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 7 - }, - "test": "webview_instrumentation_test_apk", - "test_id_prefix": "ninja://android_webview/test:webview_instrumentation_test_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "wtf_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "wtf_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform/wtf:wtf_unittests/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "zlib_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "zlib_unittests", - "test_id_prefix": "ninja://third_party/zlib:zlib_unittests/" - } - ] - }, "Nougat Phone Tester": { "gtest_tests": [ {
diff --git a/testing/buildbot/chromium.angle.json b/testing/buildbot/chromium.angle.json index 03fb7aad..8fdee70 100644 --- a/testing/buildbot/chromium.angle.json +++ b/testing/buildbot/chromium.angle.json
@@ -1235,7 +1235,7 @@ "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d11 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--webgl-conformance-version=2.0.1", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=4" + "--jobs=2" ], "isolate_name": "telemetry_gpu_integration_test", "merge": {
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 1158e37..83f3ecc 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -1116,117 +1116,6 @@ }, { "args": [ - "webgl2_conformance", - "--show-stdout", - "--browser=cros-chrome", - "--passthrough", - "-v", - "--stable-jobs", - "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --use-gl=angle --use-angle=gles --use-cmd-decoder=passthrough --force_high_performance_gpu", - "--webgl-conformance-version=2.0.1", - "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=1", - "--remote=127.0.0.1", - "--remote-ssh-port=9222", - "--magic-vm-cache=magic_cros_vm_cache" - ], - "isolate_name": "telemetry_gpu_integration_test", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "webgl2_conformance_gles_passthrough_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "should_retry_with_patch": false, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86", - "kvm": "1", - "os": "Ubuntu-18.04", - "pool": "chromium.tests" - } - ], - "idempotent": false, - "named_caches": [ - { - "name": "cros_vm", - "path": "magic_cros_vm_cache" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "cros_vm" - } - ] - }, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 20 - }, - "test_id_prefix": "ninja://chrome/test:telemetry_gpu_integration_test/" - }, - { - "args": [ - "webgl1_conformance", - "--show-stdout", - "--browser=cros-chrome", - "--passthrough", - "-v", - "--stable-jobs", - "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --use-gl=angle --use-angle=gles --use-cmd-decoder=passthrough --force_high_performance_gpu", - "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", - "--jobs=1", - "--remote=127.0.0.1", - "--remote-ssh-port=9222", - "--magic-vm-cache=magic_cros_vm_cache" - ], - "isolate_name": "telemetry_gpu_integration_test", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "webgl_conformance_gles_passthrough_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "should_retry_with_patch": false, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86", - "kvm": "1", - "os": "Ubuntu-18.04", - "pool": "chromium.tests" - } - ], - "idempotent": false, - "named_caches": [ - { - "name": "cros_vm", - "path": "magic_cros_vm_cache" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "cros_vm" - } - ] - }, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 20 - }, - "test_id_prefix": "ninja://chrome/test:telemetry_gpu_integration_test/" - }, - { - "args": [ "webgl1_conformance", "--show-stdout", "--browser=cros-chrome", @@ -5923,9 +5812,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -5937,8 +5826,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -6090,9 +5979,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -6104,8 +5993,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -6242,9 +6131,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -6256,8 +6145,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 3b087f9..3a13c19 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -3670,1949 +3670,6 @@ } ] }, - "Linux MSan Focal": { - "gtest_tests": [ - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "absl_hardening_tests", - "test_id_prefix": "ninja://third_party/abseil-cpp:absl_hardening_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "accessibility_unittests", - "test_id_prefix": "ninja://ui/accessibility:accessibility_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "angle_unittests", - "test_id_prefix": "ninja://third_party/angle/src/tests:angle_unittests/", - "use_isolated_scripts_api": true - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "app_shell_unittests", - "test_id_prefix": "ninja://extensions/shell:app_shell_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "aura_unittests", - "test_id_prefix": "ninja://ui/aura:aura_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "base_unittests", - "test_id_prefix": "ninja://base:base_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_common_unittests", - "test_id_prefix": "ninja://third_party/blink/common:blink_common_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_fuzzer_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform:blink_fuzzer_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_heap_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform/heap:blink_heap_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_platform_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform:blink_platform_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "name": "webkit_unit_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "blink_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/controller:blink_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "boringssl_crypto_tests", - "test_id_prefix": "ninja://third_party/boringssl:boringssl_crypto_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "boringssl_ssl_tests", - "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 10 - }, - "test": "browser_tests", - "test_id_prefix": "ninja://chrome/test:browser_tests/" - }, - { - "args": [ - "--gtest_filter=-*UsingRealWebcam*", - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "capture_unittests", - "test_id_prefix": "ninja://media/capture:capture_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cast_unittests", - "test_id_prefix": "ninja://media/cast:cast_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cc_unittests", - "test_id_prefix": "ninja://cc:cc_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_app_unittests", - "test_id_prefix": "ninja://chrome/test:chrome_app_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chromedriver_unittests", - "test_id_prefix": "ninja://chrome/test/chromedriver:chromedriver_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "color_unittests", - "test_id_prefix": "ninja://ui/color:color_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "components_browsertests", - "test_id_prefix": "ninja://components:components_browsertests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "components_unittests", - "test_id_prefix": "ninja://components:components_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "compositor_unittests", - "test_id_prefix": "ninja://ui/compositor:compositor_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 8 - }, - "test": "content_browsertests", - "test_id_prefix": "ninja://content/test:content_browsertests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "content_unittests", - "test_id_prefix": "ninja://content/test:content_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "crashpad_tests", - "test_id_prefix": "ninja://third_party/crashpad/crashpad:crashpad_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_tests", - "test_id_prefix": "ninja://components/cronet:cronet_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_unittests", - "test_id_prefix": "ninja://components/cronet:cronet_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "crypto_unittests", - "test_id_prefix": "ninja://crypto:crypto_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "dbus_unittests", - "test_id_prefix": "ninja://dbus:dbus_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "device_unittests", - "test_id_prefix": "ninja://device:device_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "display_unittests", - "test_id_prefix": "ninja://ui/display:display_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "events_unittests", - "test_id_prefix": "ninja://ui/events:events_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "extensions_browsertests", - "test_id_prefix": "ninja://extensions:extensions_browsertests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "extensions_unittests", - "test_id_prefix": "ninja://extensions:extensions_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "filesystem_service_unittests", - "test_id_prefix": "ninja://components/services/filesystem:filesystem_service_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gcm_unit_tests", - "test_id_prefix": "ninja://google_apis/gcm:gcm_unit_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gfx_unittests", - "test_id_prefix": "ninja://ui/gfx:gfx_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gin_unittests", - "test_id_prefix": "ninja://gin:gin_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "google_apis_unittests", - "test_id_prefix": "ninja://google_apis:google_apis_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gpu_unittests", - "test_id_prefix": "ninja://gpu:gpu_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "gwp_asan_unittests", - "test_id_prefix": "ninja://components/gwp_asan:gwp_asan_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "headless_browsertests", - "test_id_prefix": "ninja://headless:headless_browsertests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "headless_unittests", - "test_id_prefix": "ninja://headless:headless_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 3 - }, - "test": "interactive_ui_tests", - "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ipc_tests", - "test_id_prefix": "ninja://ipc:ipc_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "latency_unittests", - "test_id_prefix": "ninja://ui/latency:latency_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "libjingle_xmpp_unittests", - "test_id_prefix": "ninja://third_party/libjingle_xmpp:libjingle_xmpp_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "liburlpattern_unittests", - "test_id_prefix": "ninja://third_party/liburlpattern:liburlpattern_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "media_unittests", - "test_id_prefix": "ninja://media:media_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "message_center_unittests", - "test_id_prefix": "ninja://ui/message_center:message_center_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "midi_unittests", - "test_id_prefix": "ninja://media/midi:midi_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "mojo_core_unittests", - "test_id_prefix": "ninja://mojo/core:mojo_core_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "mojo_unittests", - "test_id_prefix": "ninja://mojo:mojo_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "nacl_loader_unittests", - "test_id_prefix": "ninja://components/nacl/loader:nacl_loader_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "native_theme_unittests", - "test_id_prefix": "ninja://ui/native_theme:native_theme_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "net_unittests", - "test_id_prefix": "ninja://net:net_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "openscreen_unittests", - "test_id_prefix": "ninja://chrome/browser/media/router:openscreen_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ozone_x11_unittests", - "test_id_prefix": "ninja://ui/ozone:ozone_x11_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "pdf_unittests", - "test_id_prefix": "ninja://pdf:pdf_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "perfetto_unittests", - "test_id_prefix": "ninja://third_party/perfetto:perfetto_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ppapi_unittests", - "test_id_prefix": "ninja://ppapi:ppapi_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "printing_unittests", - "test_id_prefix": "ninja://printing:printing_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "remoting_unittests", - "test_id_prefix": "ninja://remoting:remoting_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "sandbox_linux_unittests", - "test_id_prefix": "ninja://sandbox/linux:sandbox_linux_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "service_manager_unittests", - "test_id_prefix": "ninja://services/service_manager/tests:service_manager_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "shell_dialogs_unittests", - "test_id_prefix": "ninja://ui/shell_dialogs:shell_dialogs_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "skia_unittests", - "test_id_prefix": "ninja://skia:skia_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "snapshot_unittests", - "test_id_prefix": "ninja://ui/snapshot:snapshot_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "sql_unittests", - "test_id_prefix": "ninja://sql:sql_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "storage_unittests", - "test_id_prefix": "ninja://storage:storage_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "sync_integration_tests", - "test_id_prefix": "ninja://chrome/test:sync_integration_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ui_base_unittests", - "test_id_prefix": "ninja://ui/base:ui_base_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "ui_touch_selection_unittests", - "test_id_prefix": "ninja://ui/touch_selection:ui_touch_selection_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "unit_tests", - "test_id_prefix": "ninja://chrome/test:unit_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "url_unittests", - "test_id_prefix": "ninja://url:url_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "views_unittests", - "test_id_prefix": "ninja://ui/views:views_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "viz_unittests", - "test_id_prefix": "ninja://components/viz:viz_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "vr_common_unittests", - "test_id_prefix": "ninja://chrome/browser/vr:vr_common_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "vr_pixeltests", - "test_id_prefix": "ninja://chrome/browser/vr:vr_pixeltests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "wm_unittests", - "test_id_prefix": "ninja://ui/wm:wm_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "wtf_unittests", - "test_id_prefix": "ninja://third_party/blink/renderer/platform/wtf:wtf_unittests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "name": "xr_browser_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "xr_browser_tests", - "test_id_prefix": "ninja://chrome/test:xr_browser_tests/" - }, - { - "args": [ - "--test-launcher-print-test-stdio=always" - ], - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_gtest_merge.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86-64", - "os": "Ubuntu-20.04" - } - ], - "expiration": 10800, - "hard_timeout": 7200, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "zlib_unittests", - "test_id_prefix": "ninja://third_party/zlib:zlib_unittests/" - } - ] - }, "Linux Viz": { "additional_compile_targets": [ "all" @@ -18866,117 +16923,6 @@ }, { "args": [ - "webgl2_conformance", - "--show-stdout", - "--browser=cros-chrome", - "--passthrough", - "-v", - "--stable-jobs", - "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --use-gl=angle --use-angle=gles --use-cmd-decoder=passthrough --force_high_performance_gpu", - "--webgl-conformance-version=2.0.1", - "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=1", - "--remote=127.0.0.1", - "--remote-ssh-port=9222", - "--magic-vm-cache=magic_cros_vm_cache" - ], - "isolate_name": "telemetry_gpu_integration_test", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "webgl2_conformance_gles_passthrough_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "should_retry_with_patch": false, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86", - "kvm": "1", - "os": "Ubuntu-18.04", - "pool": "chromium.tests" - } - ], - "idempotent": false, - "named_caches": [ - { - "name": "cros_vm", - "path": "magic_cros_vm_cache" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "cros_vm" - } - ] - }, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 20 - }, - "test_id_prefix": "ninja://chrome/test:telemetry_gpu_integration_test/" - }, - { - "args": [ - "webgl1_conformance", - "--show-stdout", - "--browser=cros-chrome", - "--passthrough", - "-v", - "--stable-jobs", - "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --use-gl=angle --use-angle=gles --use-cmd-decoder=passthrough --force_high_performance_gpu", - "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", - "--jobs=1", - "--remote=127.0.0.1", - "--remote-ssh-port=9222", - "--magic-vm-cache=magic_cros_vm_cache" - ], - "isolate_name": "telemetry_gpu_integration_test", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "webgl_conformance_gles_passthrough_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "should_retry_with_patch": false, - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "cpu": "x86", - "kvm": "1", - "os": "Ubuntu-18.04", - "pool": "chromium.tests" - } - ], - "idempotent": false, - "named_caches": [ - { - "name": "cros_vm", - "path": "magic_cros_vm_cache" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "cros_vm" - } - ] - }, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 20 - }, - "test_id_prefix": "ninja://chrome/test:telemetry_gpu_integration_test/" - }, - { - "args": [ "webgl1_conformance", "--show-stdout", "--browser=cros-chrome", @@ -87397,9 +85343,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -87411,8 +85357,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -87534,9 +85480,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -87548,8 +85494,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -87661,9 +85607,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -87675,8 +85621,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -89017,9 +86963,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89030,8 +86976,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -89184,9 +87130,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89197,8 +87143,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -89336,9 +87282,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -89349,8 +87295,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -90872,9 +88818,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -90885,8 +88831,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -91039,9 +88985,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -91052,8 +88998,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -91191,9 +89137,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -91204,8 +89150,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -91973,9 +89919,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -91986,8 +89932,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -94805,6 +92751,39 @@ } ] }, + "mac-12-wpt-fyi-rel": { + "isolated_scripts": [ + { + "args": [ + "--child-processes=8", + "--log-wptreport", + "--xvfb" + ], + "experiment_percentage": 100, + "isolate_name": "wpt_tests_isolate_content_shell", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "wpt_tests_suite", + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "x86-64", + "os": "Mac-12" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 15 + }, + "test_id_prefix": "ninja://:wpt_tests_isolate_content_shell/" + } + ] + }, "mac-arm64-on-arm64-rel-reclient": { "additional_compile_targets": [ "all"
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index c826aac4..b0bd696 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -16218,7 +16218,7 @@ "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d11 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--webgl-conformance-version=2.0.1", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=4" + "--jobs=1" ], "isolate_name": "telemetry_gpu_integration_test", "merge": { @@ -16258,7 +16258,7 @@ "--stable-jobs", "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d11 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", - "--jobs=2" + "--jobs=1" ], "isolate_name": "telemetry_gpu_integration_test", "merge": { @@ -16298,7 +16298,7 @@ "--stable-jobs", "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d9 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", - "--jobs=2" + "--jobs=1" ], "isolate_name": "telemetry_gpu_integration_test", "merge": { @@ -16337,7 +16337,7 @@ "-v", "--stable-jobs", "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-angle=vulkan --use-cmd-decoder=passthrough --force_high_performance_gpu", - "--jobs=2" + "--jobs=1" ], "isolate_name": "telemetry_gpu_integration_test", "merge": { @@ -17850,7 +17850,7 @@ "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d11 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--webgl-conformance-version=2.0.1", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=4" + "--jobs=2" ], "isolate_name": "telemetry_gpu_integration_test", "merge": {
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 5792ac3..46d27de4 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -7123,7 +7123,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7144,7 +7144,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7165,7 +7165,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7187,7 +7187,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7208,7 +7208,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7229,7 +7229,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7250,7 +7250,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7271,7 +7271,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7292,7 +7292,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7313,7 +7313,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7335,7 +7335,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7356,7 +7356,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7377,7 +7377,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7398,7 +7398,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -7421,7 +7421,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7442,7 +7442,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7463,7 +7463,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7484,7 +7484,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7505,7 +7505,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7526,7 +7526,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7547,7 +7547,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7568,7 +7568,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7589,7 +7589,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7610,7 +7610,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -7632,7 +7632,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7653,7 +7653,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7674,7 +7674,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7695,7 +7695,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7716,7 +7716,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7737,7 +7737,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7758,7 +7758,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7779,7 +7779,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7800,7 +7800,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7821,7 +7821,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7842,7 +7842,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7863,7 +7863,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7884,7 +7884,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7905,7 +7905,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7926,7 +7926,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7947,7 +7947,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7968,7 +7968,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -7989,7 +7989,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8010,7 +8010,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8031,7 +8031,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8052,7 +8052,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -8095,7 +8095,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8116,7 +8116,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8137,7 +8137,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8158,7 +8158,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8179,7 +8179,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8200,7 +8200,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8221,7 +8221,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8242,7 +8242,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8263,7 +8263,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8284,7 +8284,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8305,7 +8305,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8326,7 +8326,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8347,7 +8347,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8368,7 +8368,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8389,7 +8389,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8410,7 +8410,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8431,7 +8431,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8452,7 +8452,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8473,7 +8473,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8494,7 +8494,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8515,7 +8515,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8536,7 +8536,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8557,7 +8557,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8578,7 +8578,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8599,7 +8599,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8620,7 +8620,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8641,7 +8641,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8662,7 +8662,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8683,7 +8683,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8704,7 +8704,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8725,7 +8725,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8746,7 +8746,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8767,7 +8767,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8788,7 +8788,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8809,7 +8809,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8830,7 +8830,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8852,7 +8852,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -8873,7 +8873,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Ubuntu-16.04" + "os": "Ubuntu-20.04" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" @@ -18604,11 +18604,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -18620,8 +18620,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -18785,11 +18785,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -18801,8 +18801,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [ @@ -18947,11 +18947,11 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots" ], - "description": "Run with ash-chrome version 110.0.5434.0", + "description": "Run with ash-chrome version 110.0.5434.2", "isolate_profile_data": true, "merge": { "args": [], @@ -18963,8 +18963,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v110.0.5434.0", - "revision": "version:110.0.5434.0" + "location": "lacros_version_skew_tests_v110.0.5434.2", + "revision": "version:110.0.5434.2" } ], "dimension_sets": [
diff --git a/testing/buildbot/chromium.perf.fyi.json b/testing/buildbot/chromium.perf.fyi.json index 0cf35ef..a5120dfd 100644 --- a/testing/buildbot/chromium.perf.fyi.json +++ b/testing/buildbot/chromium.perf.fyi.json
@@ -256,7 +256,7 @@ "--experimental-tbmv3-metrics", "-d", "--os-check=check", - "--system-image-dir=../../third_party/fuchsia-sdk/images-internal/chromebook-x64-release/sucrose_eng" + "--system-image-dir=workstation_eng.chromebook-x64" ], "isolate_name": "performance_web_engine_test_suite", "merge": {
diff --git a/testing/buildbot/filters/android.emulator_p.chrome_public_test_apk.filter b/testing/buildbot/filters/android.emulator_p.chrome_public_test_apk.filter index 7b327d8..a84cfcb 100644 --- a/testing/buildbot/filters/android.emulator_p.chrome_public_test_apk.filter +++ b/testing/buildbot/filters/android.emulator_p.chrome_public_test_apk.filter
@@ -119,6 +119,6 @@ -org.chromium.chrome.browser.autofill_assistant.AutofillAssistantPasswordManagerIntegrationTest* # crbug.com/1392774 --org.chromium.chrome.browser.display_cutout.DisplayCutoutTest.testViewportFitCover +-org.chromium.chrome.browser.display_cutout.DisplayCutoutTest.testViewportFitCover*
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index ba22f3f..78f8bf2 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1292,11 +1292,6 @@ 'android-pie-arm64-coverage-experimental-rel', # Does not generate profraw data. ], 'modifications': { - 'Marshmallow 64 bit Tester': { - 'swarming': { - 'shards': 14, - }, - }, 'Oreo Phone Tester': { # TODO(https://crbug.com/884413): Re-enable this once the tests are # either passing or there is more capacity. @@ -2126,7 +2121,6 @@ # Can't run on MSAN because gl_tests uses the hardware driver, # which isn't instrumented. 'Linux MSan Tests', - 'Linux MSan Focal', ], 'modifications': { # TODO(kbr): figure out a better way to specify blocks of @@ -2252,7 +2246,6 @@ # Can't run on MSAN because gl_unittests uses the hardware driver, # which isn't instrumented. 'Linux MSan Tests', - 'Linux MSan Focal', ], 'modifications': { 'Win10 FYI x64 Exp Release (Intel HD 630)': { @@ -2982,7 +2975,6 @@ 'android-pie-arm64-rel', 'android-pie-x86-rel', 'android-11-x86-rel', - 'Marshmallow 64 bit Tester', 'Nougat Phone Tester', 'ToTAndroid' ] @@ -3192,7 +3184,6 @@ 'Linux ChromiumOS MSan Tests', # https://crbug.com/831676 'Linux ChromiumOS MSan Focal', 'Linux MSan Tests', # https://crbug.com/831676 - 'Linux MSan Focal', # https://crbug.com/831676 ], 'replacements': { # TODO(crbug.com/1078982): Remove once the test is fixed on 10.15.4. @@ -3948,12 +3939,6 @@ 'shards': 2, }, }, - 'Marshmallow 64 bit Tester': { - # Increase timeout. See https://crbug.com/847229. - 'swarming': { - 'hard_timeout': 1200, - }, - }, }, }, 'webview_64_cts_tests': {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 7a86a62..14cf787b0 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -3522,9 +3522,6 @@ '--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json', '$$MAGIC_SUBSTITUTION_GPUParallelJobs', ], - 'chromeos_args': [ - '$$MAGIC_SUBSTITUTION_ChromeOSTelemetryRemote', - ], 'android_args': [ '$$MAGIC_SUBSTITUTION_GPUTelemetryNoRootForUnrootedDevices', ], @@ -3534,9 +3531,6 @@ 'swarming': { 'shards': 6, }, - 'chromeos_swarming': { - 'shards': 20, - }, }, }, @@ -5955,8 +5949,6 @@ ], 'gpu_chromeos_telemetry_tests': [ - 'gpu_webgl_conformance_gles_passthrough_telemetry_tests', - 'gpu_webgl2_conformance_gles_passthrough_telemetry_tests', 'gpu_webgl_conformance_telemetry_tests', ],
diff --git a/testing/buildbot/tryserver.chromium.win.json b/testing/buildbot/tryserver.chromium.win.json index a892139..e4b3e36 100644 --- a/testing/buildbot/tryserver.chromium.win.json +++ b/testing/buildbot/tryserver.chromium.win.json
@@ -673,7 +673,7 @@ "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=d3d11 --use-cmd-decoder=passthrough --force_high_performance_gpu", "--webgl-conformance-version=2.0.1", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl2_conformance_tests_output.json", - "--jobs=4" + "--jobs=2" ], "isolate_name": "telemetry_gpu_integration_test", "merge": {
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index 52f973c..4e5b58c 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -22,16 +22,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v110.0.5434.2/test_ash_chrome', ], - 'description': 'Run with ash-chrome version 110.0.5434.0', + 'description': 'Run with ash-chrome version 110.0.5434.2', 'identifier': 'Lacros version skew testing ash canary', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v110.0.5434.0', - 'revision': 'version:110.0.5434.0', + 'location': 'lacros_version_skew_tests_v110.0.5434.2', + 'revision': 'version:110.0.5434.2', }, ], },
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 834a8c2..837963d 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -603,17 +603,6 @@ 'junit_tests': 'cast_junit_tests', }, }, - 'Marshmallow 64 bit Tester': { - 'mixins': [ - 'has_native_resultdb_integration', - 'marshmallow', - 'bullhead', - ], - 'test_suites': { - 'gtest_tests': 'android_marshmallow_gtests', - }, - 'os_type': 'android', - }, 'Nougat Phone Tester': { 'test_suites': { 'gtest_tests': 'android_nougat_gtests', @@ -2724,22 +2713,6 @@ '--test-launcher-print-test-stdio=always', ], }, - 'Linux MSan Focal': { - 'mixins': [ - 'linux-focal', - 'x86-64', - ], - 'swarming': { - 'expiration': 10800, - 'hard_timeout': 7200, - }, - 'test_suites': { - 'gtest_tests': 'chromium_linux_and_gl_gtests', - }, - 'args': [ - '--test-launcher-print-test-stdio=always', - ], - }, 'Linux Viz': { 'mixins': [ 'linux-bionic', @@ -3500,6 +3473,15 @@ 'isolated_scripts': 'wpt_web_tests_input', }, }, + 'mac-12-wpt-fyi-rel': { + 'mixins': [ + 'mac_12_x64', + ], + 'test_suites': { + 'isolated_scripts': 'wpt_web_tests_content_shell', + }, + 'os_type': 'mac', + }, # TODO(crbug.com/1252626): remove this after the migration. 'mac-arm64-on-arm64-rel-reclient': { 'additional_compile_targets': [ @@ -5040,7 +5022,7 @@ }, 'Linux MSan Tests': { 'mixins': [ - 'linux-xenial', + 'linux-focal', 'x86-64', ], 'test_suites': {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index bf834a6..1988713 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -494,6 +494,7 @@ { "name": "Interact30", "params": { + "delay_minutes": "30", "require_interaction": "true" }, "enable_features": [ @@ -7242,22 +7243,17 @@ "params": { "MaxNumRepeatableQueries": "4", "OmniboxDynamicMaxAutocompleteIncreasedLimit": "15", - "OmniboxLocalZeroSuggestAgeThreshold": "90", "OmniboxMaxURLMatches": "8", - "PrefixSuggestIgnoreDuplicateVisits": "true", "PrivilegeRepeatableQueries": "true", "ScaleRepeatableQueriesScore": "true", - "UIMaxAutocompleteMatches": "10", - "ZeroSuggestIgnoreDuplicateVisits": "false" + "UIMaxAutocompleteMatches": "10" }, "enable_features": [ "AndroidAuxiliarySearch", - "LocalHistorySuggestRevamp", "NewTabPageTilesTitleWrapAround", "OmniboxDynamicMaxAutocomplete", "OmniboxFocusTriggersSRPZeroSuggest", "OmniboxHeaderPaddingUpdate", - "OmniboxLocalZeroSuggestAgeThreshold", "OmniboxMaxURLMatches", "OmniboxMostVisitedTilesDynamicSpacing", "OmniboxMostVisitedTilesFadingOnTablet", @@ -7279,15 +7275,8 @@ "experiments": [ { "name": "IOSExperiments", - "params": { - "OmniboxLocalZeroSuggestAgeThreshold": "90", - "PrefixSuggestIgnoreDuplicateVisits": "true", - "ZeroSuggestIgnoreDuplicateVisits": "false" - }, - "enable_features": [ - "LocalHistorySuggestRevamp", - "OmniboxLocalZeroSuggestAgeThreshold" - ] + "params": {}, + "enable_features": [] } ] }
diff --git a/third_party/blink/common/navigation/impression_mojom_traits.cc b/third_party/blink/common/navigation/impression_mojom_traits.cc index 3728037..01a7410 100644 --- a/third_party/blink/common/navigation/impression_mojom_traits.cc +++ b/third_party/blink/common/navigation/impression_mojom_traits.cc
@@ -10,7 +10,8 @@ bool StructTraits<blink::mojom::ImpressionDataView, blink::Impression>::Read( blink::mojom::ImpressionDataView data, blink::Impression* out) { - return data.ReadAttributionSrcToken(&out->attribution_src_token); + return data.ReadAttributionSrcToken(&out->attribution_src_token) && + data.ReadNavType(&out->nav_type); } } // namespace mojo
diff --git a/third_party/blink/common/widget/visual_properties_mojom_traits.cc b/third_party/blink/common/widget/visual_properties_mojom_traits.cc index 4bb2ef7..9e84b3f 100644 --- a/third_party/blink/common/widget/visual_properties_mojom_traits.cc +++ b/third_party/blink/common/widget/visual_properties_mojom_traits.cc
@@ -36,8 +36,6 @@ out->page_scale_factor = data.page_scale_factor(); out->compositing_scale_factor = data.compositing_scale_factor(); out->is_pinch_gesture_active = data.is_pinch_gesture_active(); - out->virtual_keyboard_resize_height_physical_px = - data.virtual_keyboard_resize_height_physical_px(); return true; }
diff --git a/third_party/blink/perf_tests/editing/many_spans_with_move_backward_character.html b/third_party/blink/perf_tests/editing/many_spans_with_move_backward_character.html new file mode 100644 index 0000000..4405d126 --- /dev/null +++ b/third_party/blink/perf_tests/editing/many_spans_with_move_backward_character.html
@@ -0,0 +1,46 @@ +<!doctype html> +<style> +#sample { + font: 10px/14px monospace; + width: 80ch; + border: solid 3px green; + padding: 5px; + height: 300px; + overflow: scroll; +} +span { + background: rgba(250, 250, 250); +} +</style> +<script src="../resources/runner.js"></script> +<script src="../paint/resources/paint.js"></script> +<div id="sample" contenteditable></div> +<script> +const NUMBER_OF_ELEMENTS = 1000 * 10; +const MOVE_COUNT = NUMBER_OF_ELEMENTS / 10; +const selection = window.getSelection(); +const sample = document.getElementById('sample'); +PerfTestRunner.measureTime({ + description: 'Measures performance of Selection#collapse() with many spans.', + + setup: function() { + sample.innerHTML = ''; + for (let index = 0; index < NUMBER_OF_ELEMENTS; ++index) { + const span = document.createElement('span'); + span.innerHTML = `${index} `; + span.setAttribute('id', `e${index}`); + sample.appendChild(span); + if (index % 100 === 99) + sample.appendChild(document.createElement('br')); + } + }, + + run: function() { + const start = document.getElementById(`e${NUMBER_OF_ELEMENTS - 1}`); + const end = document.getElementById(`e${NUMBER_OF_ELEMENTS -100}`); + selection.collapse(start.firstChild, 0); + for (let i = 0; i < MOVE_COUNT; ++i) + selection.modify('extend', 'backward', 'character'); + }, +}); +</script>
diff --git a/third_party/blink/perf_tests/editing/many_spans_with_select_all.html b/third_party/blink/perf_tests/editing/many_spans_with_select_all.html new file mode 100644 index 0000000..3d16ad1 --- /dev/null +++ b/third_party/blink/perf_tests/editing/many_spans_with_select_all.html
@@ -0,0 +1,45 @@ +<!doctype html> +<style> +#sample { + font: 10px/14px monospace; + width: 80ch; + border: solid 3px green; + padding: 5px; + height: 300px; + overflow: scroll; +} +span { + background: rgba(250, 250, 250); +} +</style> +<script src="../resources/runner.js"></script> +<script src="../paint/resources/paint.js"></script> +<div id="sample" contenteditable></div> +<script> +const NUMBER_OF_ELEMENTS = 1000 * 10; +const SELECT_ALL_COUNT = NUMBER_OF_ELEMENTS / 10; +const selection = window.getSelection(); +const sample = document.getElementById('sample'); +PerfTestRunner.measureTime({ + description: 'Measures performance of Selection#collapse() with many spans.', + + setup: function() { + sample.innerHTML = ''; + for (let index = 0; index < NUMBER_OF_ELEMENTS; ++index) { + const span = document.createElement('span'); + span.innerHTML = `${index} `; + span.setAttribute('id', `e${index}`); + sample.appendChild(span); + if (index % 100 === 99) + sample.appendChild(document.createElement('br')); + } + }, + + run: function() { + for (let i = 0; i < SELECT_ALL_COUNT; ++i) { + selection.collapse(sample, 0); + document.execCommand('selectAll'); + } + }, +}); +</script>
diff --git a/third_party/blink/public/common/attribution_reporting/DEPS b/third_party/blink/public/common/attribution_reporting/DEPS index c02fc2f..b39ccc36 100644 --- a/third_party/blink/public/common/attribution_reporting/DEPS +++ b/third_party/blink/public/common/attribution_reporting/DEPS
@@ -1,3 +1,3 @@ include_rules = [ - "+components/attribution_reporting/os_registration.h", + "+components/attribution_reporting", ]
diff --git a/third_party/blink/public/common/attribution_reporting/mojom_traits.h b/third_party/blink/public/common/attribution_reporting/mojom_traits.h index 3011e19..c84bd4f 100644 --- a/third_party/blink/public/common/attribution_reporting/mojom_traits.h +++ b/third_party/blink/public/common/attribution_reporting/mojom_traits.h
@@ -10,11 +10,14 @@ #include <utility> #include "components/attribution_reporting/os_registration.h" +#include "components/attribution_reporting/suitable_origin.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/common_export.h" #include "third_party/blink/public/mojom/conversions/attribution_data_host.mojom-shared.h" #include "url/gurl.h" +#include "url/mojom/origin_mojom_traits.h" #include "url/mojom/url_gurl_mojom_traits.h" +#include "url/origin.h" namespace mojo { @@ -32,6 +35,31 @@ template <> struct BLINK_COMMON_EXPORT + StructTraits<blink::mojom::AttributionSuitableOriginDataView, + attribution_reporting::SuitableOrigin> { + static const url::Origin& origin( + const attribution_reporting::SuitableOrigin& origin) { + return *origin; + } + + static bool Read(blink::mojom::AttributionSuitableOriginDataView data, + attribution_reporting::SuitableOrigin* out) { + url::Origin origin; + if (!data.ReadOrigin(&origin)) + return false; + + auto suitable_origin = + attribution_reporting::SuitableOrigin::Create(std::move(origin)); + if (!suitable_origin) + return false; + + *out = std::move(*suitable_origin); + return true; + } +}; + +template <> +struct BLINK_COMMON_EXPORT StructTraits<blink::mojom::AttributionTriggerDedupKeyDataView, uint64_t> { static uint64_t value(uint64_t debug_key) { return debug_key; }
diff --git a/third_party/blink/public/common/navigation/impression.h b/third_party/blink/public/common/navigation/impression.h index 75af99a..2557ea8 100644 --- a/third_party/blink/public/common/navigation/impression.h +++ b/third_party/blink/public/common/navigation/impression.h
@@ -7,6 +7,7 @@ #include "third_party/blink/public/common/common_export.h" #include "third_party/blink/public/common/tokens/tokens.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom.h" namespace blink { @@ -20,6 +21,7 @@ // Indicates the attributionsrc request associated with `this`. // Data parameters will be used from the attributionsrc response. AttributionSrcToken attribution_src_token; + blink::mojom::AttributionNavigationType nav_type; }; } // namespace blink
diff --git a/third_party/blink/public/common/navigation/impression_mojom_traits.h b/third_party/blink/public/common/navigation/impression_mojom_traits.h index 34cac6b..09934f20 100644 --- a/third_party/blink/public/common/navigation/impression_mojom_traits.h +++ b/third_party/blink/public/common/navigation/impression_mojom_traits.h
@@ -9,6 +9,7 @@ #include "third_party/blink/public/common/common_export.h" #include "third_party/blink/public/common/navigation/impression.h" #include "third_party/blink/public/common/tokens/tokens.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom.h" #include "third_party/blink/public/mojom/conversions/conversions.mojom.h" namespace mojo { @@ -20,6 +21,10 @@ const blink::Impression& r) { return r.attribution_src_token; } + static blink::mojom::AttributionNavigationType nav_type( + const blink::Impression& r) { + return r.nav_type; + } static bool Read(blink::mojom::ImpressionDataView r, blink::Impression* out); };
diff --git a/third_party/blink/public/common/widget/visual_properties.h b/third_party/blink/public/common/widget/visual_properties.h index 3976640..00373f08 100644 --- a/third_party/blink/public/common/widget/visual_properties.h +++ b/third_party/blink/public/common/widget/visual_properties.h
@@ -88,11 +88,6 @@ // controls shrink blink size etc. cc::BrowserControlsParams browser_controls_params; - // If shown and resizing the renderer, returns the height of the virtual - // keyboard in physical pixels. Otherwise, returns 0. Always 0 in a - // non-outermost main frame. - int virtual_keyboard_resize_height_physical_px = 0; - // Whether or not the focused node should be scrolled into view after the // resize. bool scroll_focused_node_into_view = false;
diff --git a/third_party/blink/public/common/widget/visual_properties_mojom_traits.h b/third_party/blink/public/common/widget/visual_properties_mojom_traits.h index 0ee9e77..4c788d2 100644 --- a/third_party/blink/public/common/widget/visual_properties_mojom_traits.h +++ b/third_party/blink/public/common/widget/visual_properties_mojom_traits.h
@@ -80,11 +80,6 @@ return r.zoom_level; } - static int virtual_keyboard_resize_height_physical_px( - const blink::VisualProperties& r) { - return r.virtual_keyboard_resize_height_physical_px; - } - static double page_scale_factor(const blink::VisualProperties& r) { DCHECK_GT(r.page_scale_factor, 0); return r.page_scale_factor;
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 71b3132..a37f954 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -546,6 +546,10 @@ mojom = "blink.mojom.AttributionTriggerDedupKey" cpp = "uint64_t" }, + { + mojom = "blink.mojom.AttributionSuitableOrigin" + cpp = "::attribution_reporting::SuitableOrigin" + }, ] traits_headers = [ "//third_party/blink/public/common/attribution_reporting/mojom_traits.h" ] traits_public_deps = [ "//components/attribution_reporting" ]
diff --git a/third_party/blink/public/mojom/conversions/attribution_data_host.mojom b/third_party/blink/public/mojom/conversions/attribution_data_host.mojom index 2bcea37..b362682 100644 --- a/third_party/blink/public/mojom/conversions/attribution_data_host.mojom +++ b/third_party/blink/public/mojom/conversions/attribution_data_host.mojom
@@ -13,6 +13,12 @@ uint64 value; }; +// Encapsulates a potentially trustworthy origin. Equivalent to +// attribution_reporting::SuitableOrigin. +struct AttributionSuitableOrigin { + url.mojom.Origin origin; +}; + // Filter data for selectively matching attribution sources and triggers. // See https://github.com/WICG/attribution-reporting-api/blob/main/EVENT.md#optional-attribution-filters // for details. @@ -51,10 +57,10 @@ // For sources associated with a navigation, the destination site must be // same-site with the final committed url of the navigation. If they are not // same-site, this source will be ignored by the browser. - url.mojom.Origin destination; + AttributionSuitableOrigin destination; // Origin that will receive all attribution reports associated with this source. - url.mojom.Origin reporting_origin; + AttributionSuitableOrigin reporting_origin; // Data that will be sent in attribution reports to identify this source. uint64 source_event_id = 0; @@ -124,7 +130,7 @@ struct AttributionTriggerData { // Origin that registered this trigger, used to determine which source this // trigger is associated with. - url.mojom.Origin reporting_origin; + AttributionSuitableOrigin reporting_origin; // List of all event trigger data objects declared by the event trigger // header. This data is arbitrarily set by the reporting_origin.
diff --git a/third_party/blink/public/mojom/conversions/attribution_reporting.mojom b/third_party/blink/public/mojom/conversions/attribution_reporting.mojom index 4660895..8f9080e 100644 --- a/third_party/blink/public/mojom/conversions/attribution_reporting.mojom +++ b/third_party/blink/public/mojom/conversions/attribution_reporting.mojom
@@ -4,6 +4,14 @@ module blink.mojom; +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum AttributionNavigationType { + kAnchor = 0, + kWindowOpen = 1, + kContextMenu = 2, +}; + // Indicates whether OS-level attribution is enabled. // See https://github.com/WICG/attribution-reporting-api/blob/main/app_to_web.md. enum AttributionOsSupport {
diff --git a/third_party/blink/public/mojom/conversions/conversions.mojom b/third_party/blink/public/mojom/conversions/conversions.mojom index f08d5cd..fc2df18 100644 --- a/third_party/blink/public/mojom/conversions/conversions.mojom +++ b/third_party/blink/public/mojom/conversions/conversions.mojom
@@ -5,6 +5,7 @@ module blink.mojom; import "third_party/blink/public/mojom/conversions/attribution_data_host.mojom"; +import "third_party/blink/public/mojom/conversions/attribution_reporting.mojom"; import "third_party/blink/public/mojom/tokens/tokens.mojom"; // Mojo struct to represent blink::Impression native struct. @@ -13,6 +14,7 @@ // API parameters will be used from the the `AttributionDataHost` // that is associated with `attribution_src_token`. AttributionSrcToken attribution_src_token; + AttributionNavigationType nav_type; }; // Sent from renderer to browser process when a resource request matching the @@ -31,5 +33,6 @@ // `attribution_src_token` can be used to associate `data_host` with an // `Impression` object in the browser process. RegisterNavigationDataHost(pending_receiver<AttributionDataHost> data_host, - AttributionSrcToken attribution_src_token); + AttributionSrcToken attribution_src_token, + AttributionNavigationType nav_type); };
diff --git a/third_party/blink/public/mojom/render_accessibility.mojom b/third_party/blink/public/mojom/render_accessibility.mojom index 5655a4a..9c09e46 100644 --- a/third_party/blink/public/mojom/render_accessibility.mojom +++ b/third_party/blink/public/mojom/render_accessibility.mojom
@@ -7,6 +7,7 @@ import "ui/accessibility/ax_enums.mojom"; import "ui/accessibility/mojom/ax_action_data.mojom"; import "ui/accessibility/mojom/ax_event.mojom"; +import "ui/accessibility/mojom/ax_mode.mojom"; import "ui/accessibility/mojom/ax_relative_bounds.mojom"; import "ui/accessibility/mojom/ax_tree_id.mojom"; import "ui/accessibility/mojom/ax_tree_update.mojom"; @@ -88,7 +89,7 @@ // match the one set for such frame from the browser process. |ax_mode| should // contain at least the ui::AXMode::kWebContents value to enable accessibility // support for web contents. See ui/accessibility/ax_mode.h for valid values. - SetMode(uint32 ax_mode); + SetMode(ax.mojom.AXMode ax_mode); // Kills the renderer. Sent when there is a fatal error in the accessibility // tree and the maximum number of resets has been hit.
diff --git a/third_party/blink/public/mojom/widget/visual_properties.mojom b/third_party/blink/public/mojom/widget/visual_properties.mojom index 3c10634..b7e7b3b3 100644 --- a/third_party/blink/public/mojom/widget/visual_properties.mojom +++ b/third_party/blink/public/mojom/widget/visual_properties.mojom
@@ -100,8 +100,4 @@ // frame. gfx.mojom.Rect window_controls_overlay_rect; - // If shown and resizing the renderer, returns the height of the virtual - // keyboard in physical pixels. Otherwise, returns 0. Always 0 in a - // non-outermost main frame. - uint32 virtual_keyboard_resize_height_physical_px; };
diff --git a/third_party/blink/renderer/core/accessibility/ax_context.cc b/third_party/blink/renderer/core/accessibility/ax_context.cc index 7255209..76e3d93 100644 --- a/third_party/blink/renderer/core/accessibility/ax_context.cc +++ b/third_party/blink/renderer/core/accessibility/ax_context.cc
@@ -25,9 +25,9 @@ DCHECK(document_); DCHECK(document_->IsActive()); DCHECK(document_->ExistingAXObjectCache()); - DCHECK_EQ( - ax_mode_.mode(), - document_->ExistingAXObjectCache()->GetAXMode().mode() & ax_mode_.mode()); + DCHECK_EQ(ax_mode_.flags(), + document_->ExistingAXObjectCache()->GetAXMode().flags() & + ax_mode_.flags()); return *document_->ExistingAXObjectCache(); } @@ -46,9 +46,9 @@ ax_mode_ = mode; document_->AXContextModeChanged(); - DCHECK_EQ( - ax_mode_.mode(), - document_->ExistingAXObjectCache()->GetAXMode().mode() & ax_mode_.mode()); + DCHECK_EQ(ax_mode_.flags(), + document_->ExistingAXObjectCache()->GetAXMode().flags() & + ax_mode_.flags()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/editing/compare_positions.cc b/third_party/blink/renderer/core/editing/compare_positions.cc index de782d1..8e0d275 100644 --- a/third_party/blink/renderer/core/editing/compare_positions.cc +++ b/third_party/blink/renderer/core/editing/compare_positions.cc
@@ -32,6 +32,8 @@ namespace { +constexpr int kInvalidOffset = -1; + template <typename Traversal> int16_t SlowComparePositions(const Node* container_a, int offset_a, @@ -136,6 +138,8 @@ STATIC_ONLY(Comparator); public: + // Integer offset version of `ComparePositions()`. + // // Returns // -1 if `node_a` is before `node_b` // 0 if `node_a == node_b` @@ -150,6 +154,98 @@ const Node* container_b, int offset_b, bool* disconnected) { + return ComparePositionsInternal(container_a, IntAsOffset(offset_a), + container_b, IntAsOffset(offset_b), + disconnected); + } + + // Integer/Node offset version of `ComparePositions()`. + // + // Returns + // -1 if `node_a` is before `node_b` + // 0 if `node_a == node_b` + // 1 if `node_a` is after `node_b` + // where + // * `node_a == Traversal::ChildAt(*container_a, offset_a)` + // * `node_b == Traversal::ChildAt(*container_a, offset_b)` + // and set `disconnected` to true if `node_a` and `node_b` are in different + // tree scopes. + static int16_t ComparePositions(const Node* container_a, + int offset_a, + const Node* child_a, + const Node* container_b, + int offset_b, + const Node* child_b, + bool* disconnected = nullptr) { + if (offset_a == kInvalidOffset && offset_b == kInvalidOffset) { + return ComparePositionsInternal(container_a, NodeAsOffset(child_a), + container_b, NodeAsOffset(child_b), + disconnected); + } + + if (offset_a == kInvalidOffset) { + return ComparePositionsInternal(container_a, NodeAsOffset(child_a), + container_b, IntAsOffset(offset_b), + disconnected); + } + + if (offset_b == kInvalidOffset) { + return ComparePositionsInternal(container_a, IntAsOffset(offset_a), + container_b, NodeAsOffset(child_b), + disconnected); + } + + return ComparePositionsInternal(container_a, IntAsOffset(offset_a), + container_b, IntAsOffset(offset_b), + disconnected); + } + + private: + enum Result : int16_t { + kAIsBeforeB = -1, + kAIsEqualToB = 0, + kAIsAfterB = 1, + }; + + // The wrapper class of `int` offset. + class IntAsOffset { + STACK_ALLOCATED(); + + public: + explicit IntAsOffset(int value) : value_(value) {} + int Get() const { return value_; } + + private: + int value_; + }; + + // The wrapper class of offset in `Node*` before position. + class NodeAsOffset { + STACK_ALLOCATED(); + + public: + explicit NodeAsOffset(const Node* value) : value_(value) {} + const Node* Get() const { return value_; } + + private: + const Node* value_; + }; + + // Returns + // -1 if `child_a` is before `child_b` + // 0 if `child_a == child_b` + // 1 if `child_a` is after `child_b` + // where + // * `child_a == Traversal::ChildAt(*container_a, offset_a)` + // * `child_b == Traversal::ChildAt(*container_a, offset_b)` + // and set `disconnected` to true if `child_a` and `child_b` are in different + // tree scopes. + template <typename OffsetA, typename OffsetB> + static int16_t ComparePositionsInternal(const Node* container_a, + OffsetA offset_a, + const Node* container_b, + OffsetB offset_b, + bool* disconnected) { DCHECK(container_a); DCHECK(container_b); @@ -164,13 +260,8 @@ // see DOM2 traversal & range section 2.5 // Case 1: both points have the same container - if (container_a == container_b) { - if (offset_a == offset_b) - return kAIsEqualToB; - if (offset_a < offset_b) - return kAIsBeforeB; - return kAIsAfterB; - } + if (container_a == container_b) + return CompareNodesInSameParent(offset_a.Get(), offset_b.Get()); // Case 2: node C (container B or an ancestor) is a child node of A, e.g. // * A < B @@ -180,8 +271,11 @@ // * A == C2 // A // `<a>...<c2>...<b>...B...</b>...</c2>...</a>` - if (const Node* node_c2 = FindChildnInAncestors(*container_b, *container_a)) - return CompareNodesInSameParent(offset_a, node_c2, kAIsBeforeB); + if (const Node* node_c2 = + FindChildnInAncestors(*container_b, *container_a)) { + return CompareNodesInSameParent( + offset_a.Get(), Traversal::PreviousSibling(*node_c2), kAIsBeforeB); + } // Case 3: node C (container A or an ancestor) is a child node of B, e.g. // * B < A @@ -191,8 +285,11 @@ // * B == C3 // B // `<b>...<c3>...<a>...A...</a>...</b>` - if (const Node* node_c3 = FindChildnInAncestors(*container_a, *container_b)) - return -CompareNodesInSameParent(offset_b, node_c3, kAIsBeforeB); + if (const Node* node_c3 = + FindChildnInAncestors(*container_a, *container_b)) { + return -CompareNodesInSameParent( + offset_b.Get(), Traversal::PreviousSibling(*node_c3), kAIsBeforeB); + } // case 4: containers A & B are siblings, or children of siblings // ### we need to do a traversal here instead @@ -215,59 +312,113 @@ return CompareNodesInSameParent(adjusted_child_a, adjusted_child_b); } - private: - enum Result : int16_t { - kAIsBeforeB = -1, - kAIsEqualToB = 0, - kAIsAfterB = 1, - }; - - // Returns where `offset_b = Traversal::Index(*child_b)`: + // Returns // -1 if `offset_a < offset_b` // 0 if `offset_a == offset_b` // 1 if `offset_a > offset_b` + // where ``` + // offset_b = child_before_position_b + // ? Traversal::Index(*child_before_position_b) + 1 + // : 0 ``` // The number of iteration is `std::min(offset_a, offset_b)`. static Result CompareNodesInSameParent( int offset_a, - const Node* child_b, + const Node* child_before_position_b, Result result_of_a_is_equal_to_b = kAIsEqualToB) { - DCHECK(child_b); - int offset_b = 0; - for (const Node& child_a : - Traversal::ChildrenOf(*Traversal::Parent(*child_b))) { - if (child_a == child_b || offset_a == offset_b) { - const int diff = offset_a - offset_b; - return !diff ? result_of_a_is_equal_to_b - : diff > 0 ? kAIsAfterB - : kAIsBeforeB; - } - ++offset_b; + if (!child_before_position_b) + return !offset_a ? result_of_a_is_equal_to_b : kAIsAfterB; + if (!offset_a) + return kAIsBeforeB; + // Starts from offset 1 and after `child_before_position_b`. + const Node& child_b = *child_before_position_b; + int offset = 1; + for (const Node& child : + Traversal::ChildrenOf(*Traversal::Parent(child_b))) { + if (offset_a == offset) + return child == child_b ? result_of_a_is_equal_to_b : kAIsBeforeB; + if (child == child_b) + return kAIsAfterB; + ++offset; } NOTREACHED(); return result_of_a_is_equal_to_b; } + static int16_t CompareNodesInSameParent( + int offset_a, + int offset_b, + Result result_of_a_is_equal_to_b = kAIsEqualToB) { + if (offset_a == offset_b) + return result_of_a_is_equal_to_b; + return offset_a < offset_b ? kAIsBeforeB : kAIsAfterB; + } + + static int16_t CompareNodesInSameParent(const Node* child_before_position_a, + int offset_b) { + return -CompareNodesInSameParent(offset_b, child_before_position_a); + } + // Returns // -1 if `Traversal::Index(*child_a) < Traversal::Index(*child_b)` // 0 if `Traversal::Index(*child_a) == Traversal::Index(*child_b)` // 1 if `Traversal::Index(*child_a) > Traversal::Index(*child_b)` - // The number of iteration is `std::min(offset_a, offset_b)`. - static Result CompareNodesInSameParent( + // `child_a` and `child_b` should be in a same parent nod or `nullptr`. + // + // When `child_a` < `child_b`. ``` + // child_a child_b + /// <-- backward_a --|-- forward_a --><-- backward_b --|-- forward_b --> + // |------------------+---------------------------------+----------------| + // ``` + // When `child_a` > `child_b`. ``` + // child_b child_a + /// <-- backward_b --|-- forward_b --><-- backward_a --|-- forward_a --> + // |------------------+---------------------------------+----------------| + // ``` + // + // The maximum number of iterations is `number_of_children / 4`. + // + // The minimum number of iterations is: ``` + // std::min(offset_a, offset_b, + // abs(offset_a - offset_b), + // number_of_children - offset_a, + // number_of_children - offset_b) + // where + // `offset_a` == `Traversal::Index(*child_a)` + // `offset_b` == `Traversal::Index(*child_b)` + // + // ``` + // Note: We call this function both "node before position" and "node after + // position" cases. For "node after position" case, `child_a` and `child_b` + // should not be `nullptr`. + static int16_t CompareNodesInSameParent( const Node* child_a, const Node* child_b, Result result_of_a_is_equal_to_b = kAIsEqualToB) { - DCHECK(child_a); - DCHECK(child_b); if (child_a == child_b) return result_of_a_is_equal_to_b; + if (!child_a) + return kAIsBeforeB; + if (!child_b) + return kAIsAfterB; DCHECK_EQ(Traversal::Parent(*child_a), Traversal::Parent(*child_b)); - for (const Node& child : - Traversal::ChildrenOf(*Traversal::Parent(*child_a))) { - if (child == child_a) - return child == child_b ? result_of_a_is_equal_to_b : kAIsBeforeB; - if (child == child_b) + const Node* backward_a = child_a; + const Node* forward_a = child_a; + const Node* backward_b = child_b; + const Node* forward_b = child_b; + + for (;;) { + if (!backward_a || !forward_b) + return kAIsBeforeB; + if (!forward_a || !backward_b || backward_a == forward_b) return kAIsAfterB; + if (forward_a == backward_b) + return kAIsBeforeB; + backward_a = Traversal::PreviousSibling(*backward_a); + forward_a = Traversal::NextSibling(*forward_a); + backward_b = Traversal::PreviousSibling(*backward_b); + forward_b = Traversal::NextSibling(*forward_b); } + NOTREACHED(); return result_of_a_is_equal_to_b; } @@ -316,9 +467,10 @@ container_a, offset_a, container_b, offset_b, disconnected); } +// Note: We should not this function outside this file. // Compare two positions, taking into account the possibility that one or both // could be inside a shadow tree. Only works for non-null values. -int16_t ComparePositions(const Position& a, const Position& b) { +int16_t SlowComparePositions(const Position& a, const Position& b) { DCHECK(a.IsNotNull()); DCHECK(b.IsNotNull()); const TreeScope* common_scope = Position::CommonAncestorTreeScope(a, b); @@ -350,6 +502,57 @@ return result ? result : bias; } +int16_t ComparePositions(const Position& position_a, + const Position& position_b) { + if (!RuntimeEnabledFeatures::FastComparePositionsEnabled()) + return SlowComparePositions(position_a, position_b); + + DCHECK(position_a.IsNotNull()); + DCHECK(position_b.IsNotNull()); + + const TreeScope* common_scope = + Position::CommonAncestorTreeScope(position_a, position_b); + + DCHECK(common_scope); + if (!common_scope) + return 0; + + Node* const container_a = position_a.ComputeContainerNode(); + Node* const node_a = common_scope->AncestorInThisScope(container_a); + DCHECK(node_a); + const bool has_descendant_a = node_a != container_a; + + Node* const container_b = position_b.ComputeContainerNode(); + Node* const node_b = common_scope->AncestorInThisScope(container_b); + DCHECK(node_b); + const bool has_descendant_b = node_b != container_b; + + const int offset_a = position_a.IsOffsetInAnchor() && !has_descendant_a + ? position_a.OffsetInContainerNode() + : kInvalidOffset; + + const int offset_b = position_b.IsOffsetInAnchor() && !has_descendant_b + ? position_b.OffsetInContainerNode() + : kInvalidOffset; + + Node* const child_a = position_a.IsOffsetInAnchor() || has_descendant_a + ? nullptr + : position_a.ComputeNodeBeforePosition(); + + Node* const child_b = position_b.IsOffsetInAnchor() || has_descendant_b + ? nullptr + : position_b.ComputeNodeBeforePosition(); + + const int16_t bias = node_a != node_b ? 0 + : has_descendant_a ? 1 + : has_descendant_b ? -1 + : 0; + + const int16_t result = Comparator<NodeTraversal>::ComparePositions( + node_a, offset_a, child_a, node_b, offset_b, child_b); + return result ? result : bias; +} + int16_t ComparePositions(const PositionWithAffinity& a, const PositionWithAffinity& b) { return ComparePositions(a.GetPosition(), b.GetPosition()); @@ -359,8 +562,9 @@ return ComparePositions(a.DeepEquivalent(), b.DeepEquivalent()); } -int16_t ComparePositions(const PositionInFlatTree& position_a, - const PositionInFlatTree& position_b) { +// Note: We should not this function outside this file. +int16_t SlowComparePositions(const PositionInFlatTree& position_a, + const PositionInFlatTree& position_b) { DCHECK(position_a.IsNotNull()); DCHECK(position_b.IsNotNull()); @@ -372,4 +576,35 @@ offset_b); } +int16_t ComparePositions(const PositionInFlatTree& position_a, + const PositionInFlatTree& position_b) { + DCHECK(position_a.IsNotNull()); + DCHECK(position_b.IsNotNull()); + + if (!RuntimeEnabledFeatures::FastComparePositionsEnabled()) + return SlowComparePositions(position_a, position_b); + + Node* const container_a = position_a.ComputeContainerNode(); + Node* const container_b = position_b.ComputeContainerNode(); + + const int offset_a = position_a.IsOffsetInAnchor() + ? position_a.OffsetInContainerNode() + : kInvalidOffset; + + const int offset_b = position_b.IsOffsetInAnchor() + ? position_b.OffsetInContainerNode() + : kInvalidOffset; + + Node* const child_a = position_a.IsOffsetInAnchor() + ? nullptr + : position_a.ComputeNodeBeforePosition(); + + Node* const child_b = position_b.IsOffsetInAnchor() + ? nullptr + : position_b.ComputeNodeBeforePosition(); + + return Comparator<FlatTreeTraversal>::ComparePositions( + container_a, offset_a, child_a, container_b, offset_b, child_b); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/DEPS b/third_party/blink/renderer/core/frame/DEPS index 24243e14..eea3e23 100644 --- a/third_party/blink/renderer/core/frame/DEPS +++ b/third_party/blink/renderer/core/frame/DEPS
@@ -3,12 +3,16 @@ "+base/run_loop.h", ], "attribution_response_parsing\.cc": [ - "+components/attribution_reporting/aggregation_keys.h", - "+components/attribution_reporting/constants.h", - "+components/attribution_reporting/filters.h", + "+components/attribution_reporting", ], "attribution_response_parsing_test\.cc": [ - "+components/attribution_reporting/constants.h", + "+components/attribution_reporting", + ], + "attribution_src_loader\.cc": [ + "+components/attribution_reporting", + ], + "attribution_src_loader_test\.cc": [ + "+components/attribution_reporting", ], "child_frame_compositing_helper\.h": [ "+components/viz/common/surfaces/surface_id.h",
diff --git a/third_party/blink/renderer/core/frame/attribution_response_parsing.cc b/third_party/blink/renderer/core/frame/attribution_response_parsing.cc index 62bc1ab..ec9bbd9 100644 --- a/third_party/blink/renderer/core/frame/attribution_response_parsing.cc +++ b/third_party/blink/renderer/core/frame/attribution_response_parsing.cc
@@ -16,7 +16,9 @@ #include "components/attribution_reporting/aggregation_keys.h" #include "components/attribution_reporting/constants.h" #include "components/attribution_reporting/filters.h" +#include "components/attribution_reporting/suitable_origin.h" #include "third_party/abseil-cpp/absl/numeric/int128.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/mojom/conversions/attribution_data_host.mojom-blink.h" #include "third_party/blink/renderer/platform/json/json_parser.h" #include "third_party/blink/renderer/platform/json/json_values.h" @@ -205,11 +207,12 @@ String destination_string; if (!object->GetString("destination", &destination_string)) return false; - scoped_refptr<const SecurityOrigin> destination = - SecurityOrigin::CreateFromString(destination_string); - if (!destination->IsPotentiallyTrustworthy()) + absl::optional<attribution_reporting::SuitableOrigin> destination = + attribution_reporting::SuitableOrigin::Create( + SecurityOrigin::CreateFromString(destination_string)->ToUrlOrigin()); + if (!destination) return false; - source_data.destination = std::move(destination); + source_data.destination = std::move(*destination); // Treat invalid source_event_id, expiry, event_report_window, // aggregatable_report_window, priority, and debug key as if they were
diff --git a/third_party/blink/renderer/core/frame/attribution_response_parsing_test.cc b/third_party/blink/renderer/core/frame/attribution_response_parsing_test.cc index ec69332..34ca235 100644 --- a/third_party/blink/renderer/core/frame/attribution_response_parsing_test.cc +++ b/third_party/blink/renderer/core/frame/attribution_response_parsing_test.cc
@@ -11,6 +11,8 @@ #include "base/test/metrics/histogram_tester.h" #include "components/attribution_reporting/constants.h" +#include "components/attribution_reporting/suitable_origin.h" +#include "components/attribution_reporting/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/numeric/int128.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -25,6 +27,8 @@ namespace { +using ::attribution_reporting::SuitableOrigin; + using FilterValues = WTF::HashMap<String, WTF::Vector<String>>; class FilterValuesBuilder { @@ -566,8 +570,7 @@ } TEST(AttributionResponseParsingTest, ParseTriggerRegistrationHeader) { - const auto reporting_origin = - SecurityOrigin::CreateFromString("https://r.test"); + const auto reporting_origin = *SuitableOrigin::Deserialize("https://r.test"); const struct { String description; @@ -661,8 +664,8 @@ EXPECT_EQ(valid, !test_case.expected.is_null()) << test_case.description; if (test_case.expected) { - EXPECT_EQ(test_case.expected->reporting_origin->ToUrlOrigin(), - trigger_data.reporting_origin->ToUrlOrigin()) + EXPECT_EQ(test_case.expected->reporting_origin, + trigger_data.reporting_origin) << test_case.description; EXPECT_EQ(test_case.expected->event_triggers, trigger_data.event_triggers) @@ -697,8 +700,7 @@ } TEST(AttributionResponseParsingTest, ParseSourceRegistrationHeader) { - const auto reporting_origin = - SecurityOrigin::CreateFromString("https://r.test"); + const auto reporting_origin = *SuitableOrigin::Deserialize("https://r.test"); const struct { String description; @@ -721,8 +723,7 @@ "destination": "https://d.test" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -749,8 +750,7 @@ "destination": "https://d.test" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -770,8 +770,7 @@ "destination": "https://d.test" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -791,8 +790,7 @@ "destination": "https://d.test" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/1, /*expiry=*/absl::nullopt, @@ -826,8 +824,7 @@ "priority": "5" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -847,8 +844,7 @@ "priority": 5 })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -868,8 +864,7 @@ "priority": "abc" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -889,8 +884,7 @@ "expiry": "5" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/base::Seconds(5), @@ -910,8 +904,7 @@ "expiry": 5 })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -931,8 +924,7 @@ "expiry": "abc" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -953,8 +945,7 @@ "event_report_window": "10" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/base::Seconds(5), @@ -975,8 +966,7 @@ "event_report_window": "NaN" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/base::Seconds(5), @@ -997,8 +987,7 @@ "aggregatable_report_window": "10" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/base::Seconds(5), @@ -1019,8 +1008,7 @@ "aggregatable_report_window": "NaN" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/base::Seconds(5), @@ -1040,8 +1028,7 @@ "debug_key": "5" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -1061,8 +1048,7 @@ "filter_data": {"SOURCE_TYPE": []} })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -1093,8 +1079,7 @@ "a": {"b": {"c": {"d": "e"}}} })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -1114,8 +1099,7 @@ "debug_reporting": true })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -1135,8 +1119,7 @@ "debug_reporting": "true" })json", mojom::blink::AttributionSourceData::New( - /*destination=*/SecurityOrigin::CreateFromString( - "https://d.test"), + /*destination=*/*SuitableOrigin::Deserialize("https://d.test"), /*reporting_origin=*/reporting_origin, /*source_event_id=*/0, /*expiry=*/absl::nullopt, @@ -1161,12 +1144,11 @@ EXPECT_EQ(valid, !test_case.expected.is_null()) << test_case.description; if (test_case.expected) { - EXPECT_EQ(test_case.expected->destination->ToUrlOrigin(), - source_data.destination->ToUrlOrigin()) + EXPECT_EQ(test_case.expected->destination, source_data.destination) << test_case.description; - EXPECT_EQ(test_case.expected->reporting_origin->ToUrlOrigin(), - source_data.reporting_origin->ToUrlOrigin()) + EXPECT_EQ(test_case.expected->reporting_origin, + source_data.reporting_origin) << test_case.description; EXPECT_EQ(test_case.expected->source_event_id,
diff --git a/third_party/blink/renderer/core/frame/attribution_src_loader.cc b/third_party/blink/renderer/core/frame/attribution_src_loader.cc index f2f097c..2ac2a094 100644 --- a/third_party/blink/renderer/core/frame/attribution_src_loader.cc +++ b/third_party/blink/renderer/core/frame/attribution_src_loader.cc
@@ -12,6 +12,7 @@ #include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_functions.h" #include "base/notreached.h" +#include "components/attribution_reporting/suitable_origin.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/http/structured_headers.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -108,12 +109,6 @@ /*invalid_parameter=*/json); } -bool IsValidReportingOrigin(const SecurityOrigin* origin) { - return origin && origin->IsPotentiallyTrustworthy() && - (origin->Protocol() == WTF::g_https_atom || - origin->Protocol() == WTF::g_http_atom); -} - bool SubframeHasAllowedContainerPolicy(LocalFrame* frame) { DCHECK(frame->Parent()); const FramePolicy& frame_policy = frame->Owner()->GetFramePolicy(); @@ -134,11 +129,12 @@ : public GarbageCollected<AttributionSrcLoader::ResourceClient>, public RawResourceClient { public: - // `associated_with_navigation` indicates whether the attribution data + // `nav_type` being non-nullopt indicates whether the attribution data // produced by this client will need to be associated with a navigation. - ResourceClient(AttributionSrcLoader* loader, - SrcType type, - bool associated_with_navigation) + ResourceClient( + AttributionSrcLoader* loader, + SrcType type, + absl::optional<mojom::blink::AttributionNavigationType> nav_type) : loader_(loader), type_(type) { DCHECK(loader_); DCHECK(loader_->local_frame_); @@ -148,12 +144,13 @@ loader_->local_frame_->GetRemoteNavigationAssociatedInterfaces() ->GetInterface(&conversion_host); - if (associated_with_navigation) { + if (nav_type.has_value()) { // Create a new token which will be used to identify `data_host_` in the // browser process. attribution_src_token_ = AttributionSrcToken(); conversion_host->RegisterNavigationDataHost( - data_host_.BindNewPipeAndPassReceiver(), *attribution_src_token_); + data_host_.BindNewPipeAndPassReceiver(), *attribution_src_token_, + *nav_type); } else { // Send the data host normally. conversion_host->RegisterDataHost( @@ -179,7 +176,7 @@ } void HandleResponseHeaders( - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, const AtomicString& source_json, const AtomicString& trigger_json, uint64_t request_id); @@ -192,11 +189,11 @@ void HandleSourceRegistration( const AtomicString& json, - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, uint64_t request_id); void HandleTriggerRegistration( const AtomicString& json, - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, uint64_t request_id); // RawResourceClient: @@ -239,30 +236,32 @@ void AttributionSrcLoader::Register(const KURL& src_url, HTMLElement* element) { CreateAndSendRequest(src_url, element, SrcType::kUndetermined, - /*associated_with_navigation=*/false); + /*nav_type=*/absl::nullopt); } absl::optional<Impression> AttributionSrcLoader::RegisterNavigation( const KURL& src_url, + mojom::blink::AttributionNavigationType nav_type, HTMLElement* element) { // TODO(apaseltiner): Add tests to ensure that this method can't be used to // register triggers. ResourceClient* client = - CreateAndSendRequest(src_url, element, SrcType::kSource, - /*associated_with_navigation=*/true); + CreateAndSendRequest(src_url, element, SrcType::kSource, nav_type); if (!client) return absl::nullopt; DCHECK(client->attribution_src_token()); - return blink::Impression{.attribution_src_token = - *client->attribution_src_token()}; + return blink::Impression{ + .attribution_src_token = *client->attribution_src_token(), + .nav_type = nav_type}; } AttributionSrcLoader::ResourceClient* -AttributionSrcLoader::CreateAndSendRequest(const KURL& src_url, - HTMLElement* element, - SrcType src_type, - bool associated_with_navigation) { +AttributionSrcLoader::CreateAndSendRequest( + const KURL& src_url, + HTMLElement* element, + SrcType src_type, + absl::optional<mojom::blink::AttributionNavigationType> nav_type) { // Detached frames cannot/should not register new attributionsrcs. if (!local_frame_->IsAttached()) return nullptr; @@ -283,20 +282,19 @@ Document* document = window->document(); if (document->IsPrerendering()) { - document->AddPostPrerenderingActivationStep( - WTF::BindOnce(base::IgnoreResult(&AttributionSrcLoader::DoRegistration), - WrapPersistentIfNeeded(this), src_url, src_type, - associated_with_navigation)); + document->AddPostPrerenderingActivationStep(WTF::BindOnce( + base::IgnoreResult(&AttributionSrcLoader::DoRegistration), + WrapPersistentIfNeeded(this), src_url, src_type, nav_type)); return nullptr; } - return DoRegistration(src_url, src_type, associated_with_navigation); + return DoRegistration(src_url, src_type, nav_type); } AttributionSrcLoader::ResourceClient* AttributionSrcLoader::DoRegistration( const KURL& src_url, SrcType src_type, - bool associated_with_navigation) { + absl::optional<mojom::blink::AttributionNavigationType> nav_type) { if (!local_frame_->IsAttached()) return nullptr; @@ -308,6 +306,7 @@ request.SetKeepalive(true); request.SetRequestContext(mojom::blink::RequestContextType::ATTRIBUTION_SRC); + bool associated_with_navigation = nav_type.has_value(); const char* eligible = [src_type, associated_with_navigation]() -> const char* { switch (src_type) { @@ -331,8 +330,7 @@ params.MutableOptions().initiator_info.name = fetch_initiator_type_names::kAttributionsrc; - auto* client = MakeGarbageCollected<ResourceClient>( - this, src_type, associated_with_navigation); + auto* client = MakeGarbageCollected<ResourceClient>(this, src_type, nav_type); ++num_resource_clients_; // TODO(https://crbug.com/1374121): If this registration is @@ -348,7 +346,7 @@ return client; } -scoped_refptr<const SecurityOrigin> +absl::optional<attribution_reporting::SuitableOrigin> AttributionSrcLoader::ReportingOriginForUrlIfValid( const KURL& url, HTMLElement* element, @@ -369,13 +367,13 @@ }; if (!RuntimeEnabledFeatures::AttributionReportingEnabled(window)) - return nullptr; + return absl::nullopt; if (!window->IsFeatureEnabled( mojom::blink::PermissionsPolicyFeature::kAttributionReporting)) { maybe_log_audit_issue( AttributionReportingIssueType::kPermissionPolicyDisabled); - return nullptr; + return absl::nullopt; } if (local_frame_->Parent() && @@ -387,17 +385,21 @@ if (!window->IsSecureContext()) { maybe_log_audit_issue(AttributionReportingIssueType::kInsecureContext, window->GetSecurityContext().GetSecurityOrigin()); - return nullptr; + return absl::nullopt; } - scoped_refptr<const SecurityOrigin> reporting_origin = + scoped_refptr<const SecurityOrigin> security_origin = SecurityOrigin::Create(url); - if (!url.ProtocolIsInHTTPFamily() || - !reporting_origin->IsPotentiallyTrustworthy()) { + + absl::optional<attribution_reporting::SuitableOrigin> reporting_origin = + attribution_reporting::SuitableOrigin::Create( + security_origin->ToUrlOrigin()); + + if (!url.ProtocolIsInHTTPFamily() || !reporting_origin) { maybe_log_audit_issue( AttributionReportingIssueType::kUntrustworthyReportingOrigin, - reporting_origin.get()); - return nullptr; + security_origin.get()); + return absl::nullopt; } UseCounter::Count(window, mojom::blink::WebFeature::kConversionAPIAll); @@ -461,7 +463,7 @@ return false; const uint64_t request_id = request.InspectorId(); - scoped_refptr<const SecurityOrigin> reporting_origin = + absl::optional<attribution_reporting::SuitableOrigin> reporting_origin = ReportingOriginForUrlIfValid(response.ResponseUrl(), /*element=*/nullptr, request_id); if (!reporting_origin) @@ -522,8 +524,8 @@ // for redirect chain, or not create the client at all. auto* client = MakeGarbageCollected<ResourceClient>( - this, src_type, /*associated_with_navigation=*/false); - client->HandleResponseHeaders(std::move(reporting_origin), source_json, + this, src_type, /*nav_type=*/absl::nullopt); + client->HandleResponseHeaders(std::move(*reporting_origin), source_json, trigger_json, resource->InspectorId()); client->Finish(); return true; @@ -586,7 +588,7 @@ if (source_json.IsNull() && trigger_json.IsNull()) return; - scoped_refptr<const SecurityOrigin> reporting_origin = + absl::optional<attribution_reporting::SuitableOrigin> reporting_origin = loader_->ReportingOriginForUrlIfValid(response.ResponseUrl(), /*element=*/nullptr, request_id); if (!reporting_origin) @@ -598,16 +600,15 @@ // Attribution-Reporting-Register-OS-Trigger headers. } - HandleResponseHeaders(std::move(reporting_origin), source_json, trigger_json, + HandleResponseHeaders(std::move(*reporting_origin), source_json, trigger_json, request_id); } void AttributionSrcLoader::ResourceClient::HandleResponseHeaders( - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, const AtomicString& source_json, const AtomicString& trigger_json, uint64_t request_id) { - DCHECK(IsValidReportingOrigin(reporting_origin.get())); DCHECK(!source_json.IsNull() || !trigger_json.IsNull()); switch (type_) { @@ -657,11 +658,10 @@ void AttributionSrcLoader::ResourceClient::HandleSourceRegistration( const AtomicString& json, - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, uint64_t request_id) { DCHECK_EQ(type_, SrcType::kSource); DCHECK(!json.IsNull()); - DCHECK(IsValidReportingOrigin(reporting_origin.get())); auto source_data = mojom::blink::AttributionSourceData::New(); source_data->reporting_origin = std::move(reporting_origin); @@ -680,11 +680,10 @@ void AttributionSrcLoader::ResourceClient::HandleTriggerRegistration( const AtomicString& json, - scoped_refptr<const SecurityOrigin> reporting_origin, + attribution_reporting::SuitableOrigin reporting_origin, uint64_t request_id) { DCHECK_EQ(type_, SrcType::kTrigger); DCHECK(!json.IsNull()); - DCHECK(IsValidReportingOrigin(reporting_origin.get())); auto trigger_data = mojom::blink::AttributionTriggerData::New(); trigger_data->reporting_origin = std::move(reporting_origin);
diff --git a/third_party/blink/renderer/core/frame/attribution_src_loader.h b/third_party/blink/renderer/core/frame/attribution_src_loader.h index a9a52d8..12ee885475 100644 --- a/third_party/blink/renderer/core/frame/attribution_src_loader.h +++ b/third_party/blink/renderer/core/frame/attribution_src_loader.h
@@ -8,14 +8,18 @@ #include <stddef.h> #include <stdint.h> -#include "base/memory/scoped_refptr.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom-blink-forward.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/forward.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/wtf/forward.h" +namespace attribution_reporting { +class SuitableOrigin; +} // namespace attribution_reporting + namespace blink { class HTMLElement; @@ -24,7 +28,6 @@ class Resource; class ResourceRequest; class ResourceResponse; -class SecurityOrigin; struct Impression; @@ -60,8 +63,10 @@ // navigation, for example a click on an anchor tag. Returns an Impression // which identifies the attributionsrc request and notifies the browser to // begin tracking it. - absl::optional<Impression> RegisterNavigation(const KURL& attribution_src, - HTMLElement* element = nullptr); + absl::optional<Impression> RegisterNavigation( + const KURL& attribution_src, + mojom::blink::AttributionNavigationType nav_type, + HTMLElement* element = nullptr); // Returns true if `url` can be used as an attributionsrc: its scheme is HTTP // or HTTPS, its origin is potentially trustworthy, the document's permission @@ -90,24 +95,26 @@ // Represents what events are able to be registered from an attributionsrc. enum class SrcType { kUndetermined, kSource, kTrigger }; - ResourceClient* DoRegistration(const KURL& src_url, - SrcType src_type, - bool associated_with_navigation); + ResourceClient* DoRegistration( + const KURL& src_url, + SrcType src_type, + absl::optional<mojom::blink::AttributionNavigationType> nav_type); // Returns the reporting origin corresponding to `url` if its protocol is in // the HTTP family, its origin is potentially trustworthy, and attribution is - // allowed. Returns `nullptr` otherwise, and reports a DevTools issue using - // `element` and `request_id if `log_issues` is true. - scoped_refptr<const SecurityOrigin> ReportingOriginForUrlIfValid( - const KURL& url, - HTMLElement* element, - absl::optional<uint64_t> request_id, - bool log_issues = true); + // allowed. Returns `absl::nullopt` otherwise, and reports a DevTools issue + // using `element` and `request_id if `log_issues` is true. + absl::optional<attribution_reporting::SuitableOrigin> + ReportingOriginForUrlIfValid(const KURL& url, + HTMLElement* element, + absl::optional<uint64_t> request_id, + bool log_issues = true); - ResourceClient* CreateAndSendRequest(const KURL& src_url, - HTMLElement* element, - SrcType src_type, - bool associated_with_navigation); + ResourceClient* CreateAndSendRequest( + const KURL& src_url, + HTMLElement* element, + SrcType src_type, + absl::optional<mojom::blink::AttributionNavigationType> nav_type); // Returns whether OS-level attribution is supported. bool HasOsSupport() const;
diff --git a/third_party/blink/renderer/core/frame/attribution_src_loader_test.cc b/third_party/blink/renderer/core/frame/attribution_src_loader_test.cc index 3985b7ad..c59cefe 100644 --- a/third_party/blink/renderer/core/frame/attribution_src_loader_test.cc +++ b/third_party/blink/renderer/core/frame/attribution_src_loader_test.cc
@@ -151,7 +151,8 @@ void RegisterNavigationDataHost( mojo::PendingReceiver<mojom::blink::AttributionDataHost> data_host, - const blink::AttributionSrcToken& attribution_src_token) override {} + const blink::AttributionSrcToken& attribution_src_token, + blink::mojom::AttributionNavigationType type) override {} mojo::AssociatedReceiver<mojom::blink::ConversionHost> receiver_{this}; base::OnceClosure quit_; @@ -339,14 +340,17 @@ RegisterMockedURLLoad(url, test::CoreTestDataPath("foo.html")); for (size_t i = 0; i < AttributionSrcLoader::kMaxConcurrentRequests; ++i) { - EXPECT_TRUE(attribution_src_loader_->RegisterNavigation(url)); + EXPECT_TRUE(attribution_src_loader_->RegisterNavigation( + url, mojom::blink::AttributionNavigationType::kAnchor)); } - EXPECT_FALSE(attribution_src_loader_->RegisterNavigation(url)); + EXPECT_FALSE(attribution_src_loader_->RegisterNavigation( + url, mojom::blink::AttributionNavigationType::kAnchor)); url_test_helpers::ServeAsynchronousRequests(); - EXPECT_TRUE(attribution_src_loader_->RegisterNavigation(url)); + EXPECT_TRUE(attribution_src_loader_->RegisterNavigation( + url, mojom::blink::AttributionNavigationType::kAnchor)); } TEST_F(AttributionSrcLoaderTest, Referrer) { @@ -390,7 +394,9 @@ KURL url = ToKURL("https://example1.com/foo.html"); RegisterMockedURLLoad(url, test::CoreTestDataPath("foo.html")); - attribution_src_loader_->RegisterNavigation(url, /*element=*/nullptr); + attribution_src_loader_->RegisterNavigation( + url, mojom::blink::AttributionNavigationType::kAnchor, + /*element=*/nullptr); url_test_helpers::ServeAsynchronousRequests(); @@ -462,7 +468,9 @@ KURL url = ToKURL("https://example1.com/foo.html"); RegisterMockedURLLoad(url, test::CoreTestDataPath("foo.html")); - attribution_src_loader_->RegisterNavigation(url, /*element=*/nullptr); + attribution_src_loader_->RegisterNavigation( + url, mojom::blink::AttributionNavigationType::kAnchor, + /*element=*/nullptr); url_test_helpers::ServeAsynchronousRequests();
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 2132094..fa798b2 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
@@ -1619,10 +1619,6 @@ widget_base_->SetVisibleViewportSizeInDIPs( visual_properties.visible_viewport_size); - virtual_keyboard_resize_height_physical_px_ = - visual_properties.virtual_keyboard_resize_height_physical_px; - DCHECK(!virtual_keyboard_resize_height_physical_px_ || ForTopMostMainFrame()); - if (ForMainFrame()) { if (!AutoResizeMode()) { size_ = widget_base_->DIPsToCeiledBlinkSpace(visual_properties.new_size); @@ -4385,11 +4381,6 @@ may_throttle_if_undrawn_frames); } -int WebFrameWidgetImpl::GetVirtualKeyboardResizeHeight() const { - DCHECK(!virtual_keyboard_resize_height_physical_px_ || ForTopMostMainFrame()); - return virtual_keyboard_resize_height_physical_px_; -} - bool WebFrameWidgetImpl::GetMayThrottleIfUndrawnFramesForTesting() { return widget_base_->LayerTreeHost() ->GetMayThrottleIfUndrawnFramesForTesting();
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h index ba78ca7..e511842 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
@@ -312,8 +312,6 @@ void SetLayerTreeDebugState(const cc::LayerTreeDebugState& state) override; void SetMayThrottleIfUndrawnFrames( bool may_throttle_if_undrawn_frames) override; - int GetVirtualKeyboardResizeHeight() const override; - bool GetMayThrottleIfUndrawnFramesForTesting(); // WebFrameWidget overrides. @@ -951,10 +949,6 @@ // than the WebViewImpl::size_ since isn't set in auto resize mode. absl::optional<gfx::Size> size_; - // The amount the top-most widget has been resized by the virtual keyboard, - // in physical pixels. - int virtual_keyboard_resize_height_physical_px_ = 0; - static bool ignore_input_events_; const viz::FrameSinkId frame_sink_id_;
diff --git a/third_party/blink/renderer/core/html/html_anchor_element.cc b/third_party/blink/renderer/core/html/html_anchor_element.cc index 5a3cdfa..94aa8dc 100644 --- a/third_party/blink/renderer/core/html/html_anchor_element.cc +++ b/third_party/blink/renderer/core/html/html_anchor_element.cc
@@ -27,6 +27,7 @@ #include "base/metrics/histogram_macros.h" #include "base/time/time.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom-blink.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/mojom/input/focus_type.mojom-blink.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink.h" @@ -550,7 +551,8 @@ if (!attribution_src_value.empty()) { frame_request.SetImpression( frame->GetAttributionSrcLoader()->RegisterNavigation( - GetDocument().CompleteURL(attribution_src_value), this)); + GetDocument().CompleteURL(attribution_src_value), + mojom::blink::AttributionNavigationType::kAnchor, this)); } // If the impression could not be set, or if the value was null, mark that @@ -559,7 +561,8 @@ frame->GetAttributionSrcLoader()->CanRegister( completed_url, this, /*request_id=*/absl::nullopt)) { - frame_request.SetImpression(blink::Impression()); + frame_request.SetImpression(blink::Impression{ + .nav_type = mojom::blink::AttributionNavigationType::kAnchor}); } }
diff --git a/third_party/blink/renderer/core/html/html_meta_element.cc b/third_party/blink/renderer/core/html/html_meta_element.cc index 7fa5ccd..e301a28 100644 --- a/third_party/blink/renderer/core/html/html_meta_element.cc +++ b/third_party/blink/renderer/core/html/html_meta_element.cc
@@ -41,6 +41,7 @@ #include "third_party/blink/renderer/core/loader/http_equiv.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" +#include "third_party/blink/renderer/core/speculation_rules/document_speculation_rules.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h" #include "third_party/blink/renderer/platform/weborigin/security_policy.h" @@ -648,9 +649,18 @@ UseCounter::Count(&GetDocument(), WebFeature::kHTMLMetaElementReferrerPolicyOutsideHead); } - + network::mojom::ReferrerPolicy old_referrer_policy = + GetExecutionContext()->GetReferrerPolicy(); GetExecutionContext()->ParseAndSetReferrerPolicy(content_value, kPolicySourceMetaTag); + network::mojom::ReferrerPolicy new_referrer_policy = + GetExecutionContext()->GetReferrerPolicy(); + if (old_referrer_policy != new_referrer_policy) { + if (auto* document_rules = + DocumentSpeculationRules::FromIfExists(GetDocument())) { + document_rules->DocumentReferrerPolicyChanged(); + } + } } else if (EqualIgnoringASCIICase(name_value, "handheldfriendly") && EqualIgnoringASCIICase(content_value, "true")) { ProcessViewportContentAttribute("width=device-width",
diff --git a/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc b/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc index 3adc9c2..28320f92 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_test.cc
@@ -16,8 +16,11 @@ class LayoutNGTextTest : public NGLayoutTest { protected: + static constexpr unsigned kIncludeSnappedWidth = 1; + std::string GetItemsAsString(const LayoutText& layout_text, - int num_glyphs = 0) { + int num_glyphs = 0, + unsigned flags = 0) { if (layout_text.NeedsCollectInlines()) return "LayoutText has NeedsCollectInlines"; if (!layout_text.HasValidInlineItems()) @@ -48,6 +51,8 @@ if (num_glyphs) stream << " #glyphs=" << num_glyphs; #endif + if (flags & kIncludeSnappedWidth) + stream << " width=" << shape_result->SnappedWidth(); } stream << "}" << std::endl; } @@ -325,6 +330,20 @@ GetItemsAsString(*text.GetLayoutObject())); } +// https://crbug.com/1391668 +TEST_F(LayoutNGTextTest, SetTextWithOffsetInsertSameCharacters) { + LoadAhem(); + InsertStyleElement("body { font: 10px/15px Ahem; } b { font-size: 50px; }"); + SetBodyInnerHTML(u"<p><b id=target>a</b>aa</p>"); + Text& text = To<Text>(*GetElementById("target")->firstChild()); + text.insertData(0, "aa", ASSERT_NO_EXCEPTION); + + EXPECT_EQ( + "*{'aaa', ShapeResult=0+3 width=\"150\"}\n" + "{'aa', ShapeResult=3+2 width=\"20\"}\n", + GetItemsAsString(*text.GetLayoutObject(), 0, kIncludeSnappedWidth)); +} + TEST_F(LayoutNGTextTest, SetTextWithOffsetNoRelocation) { SetBodyInnerHTML(u"<pre id=target><a>abc</a>XYZ<b>def</b></pre>"); Text& text = To<Text>(*GetElementById("target")->firstChild()->nextSibling());
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc index 97dd3599..55b30b25 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
@@ -120,7 +120,7 @@ const Vector<const ShapeResult*> reusable_shape_results = CollectReusableShapeResults(start_offset, end_offset, - start_item.Direction()); + font.PrimaryFont(), start_item.Direction()); if (reusable_shape_results.empty()) return Reshape(start_item, font, start_offset, end_offset); @@ -165,6 +165,7 @@ Vector<const ShapeResult*> CollectReusableShapeResults( unsigned start_offset, unsigned end_offset, + const SimpleFontData* primary_font, TextDirection direction) { DCHECK_LT(start_offset, end_offset); Vector<const ShapeResult*> shape_results; @@ -180,11 +181,14 @@ break; if (item->EndOffset() < start_offset) continue; - if (!item->TextShapeResult() || item->Direction() != direction) + const ShapeResult* const shape_result = item->TextShapeResult(); + if (!shape_result || item->Direction() != direction) continue; - if (item->TextShapeResult()->IsAppliedSpacing()) + if (shape_result->PrimaryFont() != primary_font) continue; - shape_results.push_back(item->TextShapeResult()); + if (shape_result->IsAppliedSpacing()) + continue; + shape_results.push_back(shape_result); } return shape_results; }
diff --git a/third_party/blink/renderer/core/page/context_menu_controller.cc b/third_party/blink/renderer/core/page/context_menu_controller.cc index 46a2431..1aaeec8 100644 --- a/third_party/blink/renderer/core/page/context_menu_controller.cc +++ b/third_party/blink/renderer/core/page/context_menu_controller.cc
@@ -41,6 +41,7 @@ #include "third_party/blink/public/common/input/web_menu_source_type.h" #include "third_party/blink/public/common/navigation/impression.h" #include "third_party/blink/public/mojom/context_menu/context_menu.mojom-blink.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom-blink.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/public/web/web_plugin.h" #include "third_party/blink/public/web/web_text_check_client.h" @@ -779,6 +780,7 @@ selected_frame->GetAttributionSrcLoader()->RegisterNavigation( selected_frame->GetDocument()->CompleteURL( attribution_src_value), + mojom::blink::AttributionNavigationType::kContextMenu, /*element=*/anchor); } @@ -788,7 +790,8 @@ selected_frame->GetAttributionSrcLoader()->CanRegister( result.AbsoluteLinkURL(), /*element=*/anchor, /*request_id=*/absl::nullopt)) { - data.impression = blink::Impression(); + data.impression = blink::Impression{ + .nav_type = mojom::blink::AttributionNavigationType::kContextMenu}; } } }
diff --git a/third_party/blink/renderer/core/page/context_menu_controller_test.cc b/third_party/blink/renderer/core/page/context_menu_controller_test.cc index f40e2e62..a74c02a 100644 --- a/third_party/blink/renderer/core/page/context_menu_controller_test.cc +++ b/third_party/blink/renderer/core/page/context_menu_controller_test.cc
@@ -2077,6 +2077,10 @@ EXPECT_EQ(context_menu_data.impression.has_value(), test_case.impression_expected); + if (context_menu_data.impression.has_value()) { + EXPECT_EQ(context_menu_data.impression->nav_type, + mojom::blink::AttributionNavigationType::kContextMenu); + } } }
diff --git a/third_party/blink/renderer/core/page/create_window.cc b/third_party/blink/renderer/core/page/create_window.cc index 5f2c0f4..8ef69906 100644 --- a/third_party/blink/renderer/core/page/create_window.cc +++ b/third_party/blink/renderer/core/page/create_window.cc
@@ -31,6 +31,7 @@ #include "services/metrics/public/cpp/ukm_builders.h" #include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/mojom/conversions/attribution_reporting.mojom-blink.h" #include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h" #include "third_party/blink/public/mojom/window_features/window_features.mojom-blink.h" #include "third_party/blink/public/web/web_view_client.h" @@ -222,7 +223,9 @@ window_features.impression = dom_window->GetFrame() ->GetAttributionSrcLoader() - ->RegisterNavigation(dom_window->CompleteURL(decoded)); + ->RegisterNavigation( + dom_window->CompleteURL(decoded), + mojom::blink::AttributionNavigationType::kWindowOpen); } // If the impression could not be set, or if the value was empty, mark @@ -232,7 +235,8 @@ url, /*element=*/nullptr, /*request_id=*/absl::nullopt)) { - window_features.impression = blink::Impression(); + window_features.impression = blink::Impression{ + .nav_type = mojom::blink::AttributionNavigationType::kWindowOpen}; } } }
diff --git a/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.cc b/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.cc index 16c4e2c..fcbd19e 100644 --- a/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.cc +++ b/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.cc
@@ -241,6 +241,14 @@ QueueUpdateSpeculationCandidates(); } +void DocumentSpeculationRules::DocumentReferrerPolicyChanged() { + if (!initialized_) + return; + + InvalidateAllLinks(); + QueueUpdateSpeculationCandidates(); +} + void DocumentSpeculationRules::Trace(Visitor* visitor) const { Supplement::Trace(visitor); visitor->Trace(rule_sets_);
diff --git a/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.h b/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.h index 9fb2d09..84d2e2b 100644 --- a/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.h +++ b/third_party/blink/renderer/core/speculation_rules/document_speculation_rules.h
@@ -53,6 +53,7 @@ const AtomicString& new_value); void ReferrerPolicyAttributeChanged(HTMLAnchorElement* link); void RelAttributeChanged(HTMLAnchorElement* link); + void DocumentReferrerPolicyChanged(); void Trace(Visitor*) const override;
diff --git a/third_party/blink/renderer/core/speculation_rules/speculation_rule_set_test.cc b/third_party/blink/renderer/core/speculation_rules/speculation_rule_set_test.cc index d11ba75..6e19cdf 100644 --- a/third_party/blink/renderer/core/speculation_rules/speculation_rule_set_test.cc +++ b/third_party/blink/renderer/core/speculation_rules/speculation_rule_set_test.cc
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/core/html/html_area_element.h" #include "third_party/blink/renderer/core/html/html_div_element.h" #include "third_party/blink/renderer/core/html/html_head_element.h" +#include "third_party/blink/renderer/core/html/html_meta_element.h" #include "third_party/blink/renderer/core/html/html_script_element.h" #include "third_party/blink/renderer/core/inspector/console_message_storage.h" #include "third_party/blink/renderer/core/loader/empty_clients.h" @@ -1896,5 +1897,42 @@ ElementsAre(HasReferrerPolicy(network::mojom::ReferrerPolicy::kNever))); } +TEST_F(DocumentRulesTest, ReferrerMetaChangeShouldInvalidateCandidates) { + DummyPageHolder page_holder; + StubSpeculationHost speculation_host; + Document& document = page_holder.GetDocument(); + + AddAnchor(*document.body(), "https://foo.com/abc"); + String speculation_script = R"( + {"prefetch": [ + {"source": "document", "where": {"href_matches": "https://foo.com/*"}} + ]} + )"; + PropagateRulesToStubSpeculationHost(page_holder, speculation_host, + speculation_script); + const auto& candidates = speculation_host.candidates(); + EXPECT_THAT( + candidates, + ElementsAre(HasReferrerPolicy( + network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin))); + + auto* meta = + MakeGarbageCollected<HTMLMetaElement>(document, CreateElementFlags()); + meta->setAttribute(html_names::kNameAttr, "referrer"); + meta->setAttribute(html_names::kContentAttr, "strict-origin"); + + PropagateRulesToStubSpeculationHostWithMicrotasksScope( + page_holder, speculation_host, + [&]() { document.head()->appendChild(meta); }); + EXPECT_THAT(candidates, ElementsAre(HasReferrerPolicy( + network::mojom::ReferrerPolicy::kStrictOrigin))); + + PropagateRulesToStubSpeculationHostWithMicrotasksScope( + page_holder, speculation_host, + [&]() { meta->setAttribute(html_names::kContentAttr, "same-origin"); }); + EXPECT_THAT(candidates, ElementsAre(HasReferrerPolicy( + network::mojom::ReferrerPolicy::kSameOrigin))); +} + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/core/view_transition/view_transition_style_tracker.cc b/third_party/blink/renderer/core/view_transition/view_transition_style_tracker.cc index ccb225a..babd3f5 100644 --- a/third_party/blink/renderer/core/view_transition/view_transition_style_tracker.cc +++ b/third_party/blink/renderer/core/view_transition/view_transition_style_tracker.cc
@@ -36,7 +36,6 @@ #include "third_party/blink/renderer/core/view_transition/view_transition_utils.h" #include "third_party/blink/renderer/platform/data_resource_helper.h" #include "third_party/blink/renderer/platform/geometry/layout_size.h" -#include "third_party/blink/renderer/platform/widget/frame_widget.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" @@ -1041,12 +1040,10 @@ top += controls.TopHeight() - controls.TopMinHeight(); if (controls.BottomShownRatio()) bottom += controls.BottomHeight() - controls.BottomMinHeight(); - - bottom += document.GetFrame() - ->GetWidgetForLocalRoot() - ->GetVirtualKeyboardResizeHeight(); } + // TODO(bokan): Account for virtual-keyboard + // A left-side scrollbar (i.e. in an RTL writing-mode) should overlay the // snapshot viewport as well. This cannot currently happen in Chrome but it // can in other browsers. Handle this case in the event
diff --git a/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc b/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc index 7efd7ea6f..6e7faad 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc
@@ -168,8 +168,8 @@ AXObjectCacheImpl& cache = AXObjectCache(); AXObject* descendant = ActiveDescendant(); cache.PostNotification(this, ax::mojom::Event::kHide); - if (descendant) // TODO(accessibility) Try removing. Line below is enough. - cache.MarkAXObjectDirtyWithCleanLayout(this); + if (descendant) + cache.PostNotification(this, ax::mojom::Event::kChildrenChanged); cache.MarkAXSubtreeDirtyWithCleanLayout(ParentObject()); }
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 277e2844b..611b8c2 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -4737,7 +4737,8 @@ DCHECK(!IsDetached()) << "None of the above should be able to detach |this|: " << ToString(true, true); - AXObjectCache().MarkAXObjectDirtyWithCleanLayout(this); + AXObjectCache().PostNotification(this, + ax::mojom::blink::Event::kChildrenChanged); } void AXNodeObject::SelectedOptions(AXObjectVector& options) const {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index 8813a2b..d9adf34c 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -2478,7 +2478,6 @@ if (obj) { obj->ChildrenChangedWithCleanLayout(); - modification_count_++; // TODO(accessibility) Only needed for <select> size changes. // This can turn into a DCHECK if the shadow DOM is used for <select> // elements instead of AXMenuList* and AXListBox* classes. @@ -3609,7 +3608,7 @@ DCHECK(!obj->IsDetached()); if (!obj->NeedsToUpdateChildren()) { obj->SetNeedsToUpdateChildren(); - MarkAXObjectDirty(obj); + PostNotification(obj, ax::mojom::blink::Event::kChildrenChanged); } } }
diff --git a/third_party/blink/renderer/modules/accessibility/ax_relation_cache.cc b/third_party/blink/renderer/modules/accessibility/ax_relation_cache.cc index c4f0116..63ef84b 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_relation_cache.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_relation_cache.cc
@@ -680,9 +680,8 @@ DCHECK(child); if (child->IsDetached()) return; - if (AXObject* new_parent = object_cache_->RestoreParentOrPrune(child)) { - object_cache_->ChildrenChanged(new_parent); - } + if (AXObject* new_parent = object_cache_->RestoreParentOrPrune(child)) + ChildrenChanged(new_parent); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_virtual_object.cc b/third_party/blink/renderer/modules/accessibility/ax_virtual_object.cc index be4c43a..dcee88c4 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_virtual_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_virtual_object.cc
@@ -69,7 +69,7 @@ void AXVirtualObject::ChildrenChangedWithCleanLayout() { ClearChildren(); - AXObjectCache().MarkAXObjectDirtyWithCleanLayout(this); + AXObjectCache().PostNotification(this, ax::mojom::Event::kChildrenChanged); } const AtomicString& AXVirtualObject::GetAOMPropertyOrARIAAttribute(
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.h b/third_party/blink/renderer/platform/fonts/shaping/shape_result.h index 24b7ea60..4ca11cf0 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.h +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.h
@@ -169,6 +169,7 @@ LayoutUnit SnappedWidth() const { return LayoutUnit::FromFloatCeil(width_); } unsigned NumCharacters() const { return num_characters_; } unsigned NumGlyphs() const { return num_glyphs_; } + const SimpleFontData* PrimaryFont() const { return primary_font_.get(); } // TODO(eae): Remove start_x and return value once ShapeResultBuffer has been // removed.
diff --git a/third_party/blink/renderer/platform/graphics/bitmap_image.cc b/third_party/blink/renderer/platform/graphics/bitmap_image.cc index bec446e..e0c2513 100644 --- a/third_party/blink/renderer/platform/graphics/bitmap_image.cc +++ b/third_party/blink/renderer/platform/graphics/bitmap_image.cc
@@ -175,11 +175,8 @@ bool BitmapImage::ShouldReportByteSizeUMAs(bool data_now_completely_received) { if (!decoder_) return false; - // Ensures that refactoring to check truthiness of ByteSize() method is - // equivalent to the previous use of Data() and does not mess up UMAs. - DCHECK_EQ(!decoder_->ByteSize(), !decoder_->Data()); return !all_data_received_ && data_now_completely_received && - decoder_->ByteSize() && IsSizeAvailable(); + decoder_->ByteSize() != 0 && IsSizeAvailable(); } Image::SizeAvailability BitmapImage::SetData(scoped_refptr<SharedBuffer> data,
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 33f5f98..4100a83 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1284,6 +1284,7 @@ }, { name: "FirstPartySets", + status: "experimental", }, { name: "FirstRectForRangeVertical", @@ -2611,7 +2612,8 @@ { // Enabled when blink::features::kStorageAccessAPI is enabled. name: "StorageAccessAPI", - status: "test", + status: "experimental", + implied_by: ["FirstPartySets"], }, { name: "StorageAccessAPIForOriginExtension",
diff --git a/third_party/blink/renderer/platform/widget/frame_widget.h b/third_party/blink/renderer/platform/widget/frame_widget.h index 669b180..8a92e32 100644 --- a/third_party/blink/renderer/platform/widget/frame_widget.h +++ b/third_party/blink/renderer/platform/widget/frame_widget.h
@@ -283,12 +283,6 @@ // CompositorFrames. See https://crbug.com/1232173 for more details. virtual void SetMayThrottleIfUndrawnFrames( bool may_throttle_if_undrawn_frames) = 0; - - // Returns, in physical pixels, the amount that the widget has been resized - // by the virtual keyboard. The virtual keyboard always insets a widget from - // the bottom so only the height can be affected. Only the outermost main - // frame's widget returns a non-zero value. - virtual int GetVirtualKeyboardResizeHeight() const = 0; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/widget/widget_base.cc b/third_party/blink/renderer/platform/widget/widget_base.cc index a7dd02b..81b95185 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.cc +++ b/third_party/blink/renderer/platform/widget/widget_base.cc
@@ -56,6 +56,7 @@ #include "ui/display/display.h" #include "ui/display/screen_info.h" #include "ui/gfx/geometry/dip_util.h" +#include "ui/gfx/presentation_feedback.h" #if BUILDFLAG(IS_ANDROID) #include "third_party/blink/renderer/platform/widget/compositing/android_webview/synchronous_layer_tree_frame_sink.h" @@ -84,7 +85,7 @@ void OnDidPresentForceDrawFrame( mojom::blink::Widget::ForceRedrawCallback callback, - base::TimeTicks presentation_timestamp) { + const gfx::PresentationFeedback& feedback) { std::move(callback).Run(); } @@ -333,7 +334,7 @@ void WidgetBase::ForceRedraw( mojom::blink::Widget::ForceRedrawCallback callback) { - LayerTreeHost()->RequestSuccessfulPresentationTimeForNextFrame( + LayerTreeHost()->RequestPresentationTimeForNextFrame( base::BindOnce(&OnDidPresentForceDrawFrame, std::move(callback))); LayerTreeHost()->SetNeedsCommitWithForcedRedraw();
diff --git a/third_party/blink/renderer/platform/wtf/BUILD.gn b/third_party/blink/renderer/platform/wtf/BUILD.gn index 3cff0258..9772b10 100644 --- a/third_party/blink/renderer/platform/wtf/BUILD.gn +++ b/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -221,6 +221,7 @@ "//base/allocator:buildflags", "//build:chromeos_buildflags", "//third_party/blink/public/common:common", + "//third_party/modp_b64", # TODO(tkent): WTF should not depend on it. "//third_party/blink/public/common:headers",
diff --git a/third_party/blink/renderer/platform/wtf/text/base64.cc b/third_party/blink/renderer/platform/wtf/text/base64.cc index b85b493..72fd07d 100644 --- a/third_party/blink/renderer/platform/wtf/text/base64.cc +++ b/third_party/blink/renderer/platform/wtf/text/base64.cc
@@ -27,100 +27,13 @@ #include <limits.h> #include "third_party/blink/renderer/platform/wtf/text/string_buffer.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" +#include "third_party/modp_b64/modp_b64.h" namespace WTF { -static const char kBase64EncMap[64] = { - 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, - 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, - 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, - 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, - 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, - 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2B, 0x2F}; - -static const char kBase64DecMap[128] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F, - 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, - 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, - 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00}; - namespace { -class Base64EncoderImpl { - public: - explicit Base64EncoderImpl(wtf_size_t len); - - wtf_size_t out_length() const { return out_length_; } - void Encode(base::span<const uint8_t> data, base::span<char> out) const; - - private: - wtf_size_t in_length_ = 0; - wtf_size_t out_length_ = 0; -}; - -Base64EncoderImpl::Base64EncoderImpl(wtf_size_t len) { - if (!len) - return; - - // If the input string is pathologically large, just return nothing. - // Note: Keep this in sync with the "outLength" computation below. - // Rather than being perfectly precise, this is a bit conservative. - const unsigned kMaxInputBufferSize = UINT_MAX / 77 * 76 / 4 * 3 - 2; - if (len > kMaxInputBufferSize) - return; - - in_length_ = len; - out_length_ = ((len + 2) / 3) * 4; -} - -void Base64EncoderImpl::Encode(base::span<const uint8_t> data, - base::span<char> out) const { - DCHECK_EQ(in_length_, data.size()); - DCHECK_EQ(out_length_, out.size()); - DCHECK_NE(0u, out.size()); - - auto len = data.size(); - unsigned sidx = 0; - unsigned didx = 0; - - // 3-byte to 4-byte conversion + 0-63 to ascii printable conversion - if (len > 1) { - while (sidx < len - 2) { - out[didx++] = kBase64EncMap[(data[sidx] >> 2) & 077]; - out[didx++] = kBase64EncMap[((data[sidx + 1] >> 4) & 017) | - ((data[sidx] << 4) & 077)]; - out[didx++] = kBase64EncMap[((data[sidx + 2] >> 6) & 003) | - ((data[sidx + 1] << 2) & 077)]; - out[didx++] = kBase64EncMap[data[sidx + 2] & 077]; - sidx += 3; - } - } - - if (sidx < len) { - out[didx++] = kBase64EncMap[(data[sidx] >> 2) & 077]; - if (sidx < len - 1) { - out[didx++] = kBase64EncMap[((data[sidx + 1] >> 4) & 017) | - ((data[sidx] << 4) & 077)]; - out[didx++] = kBase64EncMap[(data[sidx + 1] << 2) & 077]; - } else { - out[didx++] = kBase64EncMap[(data[sidx] << 4) & 077]; - } - } - - // Add padding - while (didx < out.size()) { - out[didx] = '='; - ++didx; - } -} - // https://infra.spec.whatwg.org/#ascii-whitespace // Matches the definition of IsHTMLSpace in html_parser_idioms.h. template <typename CharType> @@ -130,132 +43,82 @@ character == '\r' || character == '\f'); } +ModpDecodePolicy GetModpPolicy(Base64DecodePolicy policy) { + switch (policy) { + case Base64DecodePolicy::kForgiving: + return ModpDecodePolicy::kForgiving; + case Base64DecodePolicy::kNoPaddingValidation: + return ModpDecodePolicy::kNoPaddingValidation; + } +} + +// Invokes modp_b64 without stripping whitespace. +bool Base64DecodeRaw(const StringView& in, + Vector<char>& out, + Base64DecodePolicy policy) { + // Using StringUTF8Adaptor means we avoid allocations if the string is 8-bit + // ascii, which is likely given that base64 is required to be ascii. + StringUTF8Adaptor adaptor(in); + out.resize(modp_b64_decode_len(adaptor.size())); + size_t output_size = modp_b64_decode(out.data(), adaptor.data(), adaptor.size(), + GetModpPolicy(policy)); + if (output_size == MODP_B64_ERROR) + return false; + + out.resize(output_size); + return true; +} + } // namespace String Base64Encode(base::span<const uint8_t> data) { - Base64EncoderImpl encoder(data.size()); - auto size = encoder.out_length(); - if (size == 0) + size_t encode_len = modp_b64_encode_data_len(data.size()); + CHECK_LE(data.size(), MODP_B64_MAX_INPUT_LEN); + StringBuffer<LChar> result(encode_len); + if (encode_len == 0) return String(); - - StringBuffer<LChar> result(size); - base::span<char> result_span(reinterpret_cast<char*>(result.Characters()), - result.length()); - encoder.Encode(data, result_span); + const size_t output_size = modp_b64_encode_data( + reinterpret_cast<char*>(result.Characters()), + reinterpret_cast<const char*>(data.data()), data.size()); + DCHECK_EQ(output_size, encode_len); return result.Release(); } void Base64Encode(base::span<const uint8_t> data, Vector<char>& out) { - Base64EncoderImpl encoder(data.size()); - auto size = encoder.out_length(); - if (size == 0) { + size_t encode_len = modp_b64_encode_data_len(data.size()); + CHECK_LE(data.size(), MODP_B64_MAX_INPUT_LEN); + if (encode_len == 0) { out.clear(); return; } - - out.resize(size); - encoder.Encode(data, out); -} - -template <typename T> -static inline bool Base64DecodeInternal(const T* data, - unsigned length, - Vector<char>& out, - Base64DecodePolicy policy) { - out.clear(); - if (!length) - return true; - - out.Grow(length); - - unsigned equals_sign_count = 0; - unsigned out_length = 0; - bool had_error = false; - for (unsigned idx = 0; idx < length; ++idx) { - UChar ch = data[idx]; - if (ch == '=') { - ++equals_sign_count; - // There should never be more than 2 padding characters. - if (policy == Base64DecodePolicy::kForgiving && equals_sign_count > 2) { - had_error = true; - break; - } - } else if (('0' <= ch && ch <= '9') || ('A' <= ch && ch <= 'Z') || - ('a' <= ch && ch <= 'z') || ch == '+' || ch == '/') { - if (equals_sign_count) { - had_error = true; - break; - } - out[out_length++] = kBase64DecMap[ch]; - } else if (policy == Base64DecodePolicy::kNoPaddingValidation || - !IsAsciiWhitespace(ch)) { - had_error = true; - break; - } - } - - if (out_length < out.size()) - out.Shrink(out_length); - - if (had_error) - return false; - - if (!out_length) - return !equals_sign_count; - - // There should be no padding if length is a multiple of 4. - // We use (outLength + equalsSignCount) instead of length because we don't - // want to account for ignored ascii whitespace. - if (policy == Base64DecodePolicy::kForgiving && equals_sign_count && - (out_length + equals_sign_count) % 4) - return false; - - // Valid data is (n * 4 + [0,2,3]) characters long. - if ((out_length % 4) == 1) - return false; - - // 4-byte to 3-byte conversion - out_length -= (out_length + 3) / 4; - if (!out_length) - return false; - - unsigned sidx = 0; - unsigned didx = 0; - if (out_length > 1) { - while (didx < out_length - 2) { - out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); - out[didx + 1] = - (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); - out[didx + 2] = (((out[sidx + 2] << 6) & 255) | (out[sidx + 3] & 077)); - sidx += 4; - didx += 3; - } - } - - if (didx < out_length) - out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); - - if (++didx < out_length) - out[didx] = (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); - - if (out_length < out.size()) - out.Shrink(out_length); - - return true; + out.resize(encode_len); + const size_t output_size = modp_b64_encode_data( + out.data(), reinterpret_cast<const char*>(data.data()), data.size()); + DCHECK_EQ(output_size, encode_len); } bool Base64Decode(const StringView& in, Vector<char>& out, Base64DecodePolicy policy) { - if (in.empty()) - return Base64DecodeInternal<LChar>(nullptr, 0, out, policy); - - if (in.Is8Bit()) { - return Base64DecodeInternal<LChar>(in.Characters8(), in.length(), out, - policy); + switch (policy) { + case Base64DecodePolicy::kForgiving: { + // https://infra.spec.whatwg.org/#forgiving-base64-decode + // Step 1 is to remove all whitespace. However, checking for whitespace + // slows down the "happy" path. Since any whitespace will fail normal + // decoding from modp_b64_decode, just try again if we detect a failure. + // This shouldn't be much slower for whitespace inputs. + // + // TODO(csharrison): Most callers use String inputs so ToString() should + // be fast. Still, we should add a RemoveCharacters method to StringView + // to avoid a double allocation for non-String-backed StringViews. + return Base64DecodeRaw(in, out, policy) || + Base64DecodeRaw(in.ToString().RemoveCharacters(&IsAsciiWhitespace), + out, policy); + } + case Base64DecodePolicy::kNoPaddingValidation: { + return Base64DecodeRaw(in, out, policy); + } } - return Base64DecodeInternal<UChar>(in.Characters16(), in.length(), out, - policy); } bool Base64UnpaddedURLDecode(const String& in, Vector<char>& out) {
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 51f0ab8..b4c7869 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -1828,6 +1828,8 @@ { 'paths': [ 'third_party/blink/renderer/core/frame/attribution_response_parsing.cc', + 'third_party/blink/renderer/core/frame/attribution_src_loader.cc', + 'third_party/blink/renderer/core/frame/attribution_src_loader.h', ], 'allowed': [ 'attribution_reporting:.*',
diff --git a/third_party/blink/tools/diff_wpt_results.py b/third_party/blink/tools/diff_wpt_results.py index 305b729..9611785 100755 --- a/third_party/blink/tools/diff_wpt_results.py +++ b/third_party/blink/tools/diff_wpt_results.py
@@ -47,11 +47,13 @@ # Extend this script to compare the results between wptrunner/Chrome # and rwt/content_shell on Linux PRODUCTS = PRODUCTS + [ - 'chrome_linux', 'content_shell', 'wpt_content_shell_linux' + 'chrome_linux', 'content_shell', 'wpt_content_shell_linux', + 'wpt_content_shell_win10' ] PRODUCTS_TO_STEPNAMES.update({ 'chrome_linux': 'wpt_tests_suite', - 'wpt_content_shell_linux': 'wpt_tests_suite', + 'wpt_content_shell_linux': 'wpt_tests_suite_linux', + 'wpt_content_shell_win10': 'wpt_tests_suite_win10', 'content_shell': 'blink_wpt_tests' }) PRODUCTS_TO_BUILDER_NAME = { @@ -59,6 +61,7 @@ 'chrome_android': 'android-chrome-pie-x86-wpt-fyi-rel', 'chrome_linux': 'linux-wpt-fyi-rel', 'wpt_content_shell_linux': 'linux-wpt-content-shell-fyi-rel', + 'wpt_content_shell_win10': 'win10-wpt-content-shell-fyi-rel', 'content_shell': "Linux Tests" } @@ -66,7 +69,10 @@ 'chrome_public_wpt': ['chrome_public_wpt on Ubuntu-16.04 or Ubuntu-18.04'], 'system_webview_wpt': ['system_webview_wpt on Ubuntu-16.04 or Ubuntu-18.04'], - 'wpt_tests_suite': ['wpt_tests_suite (experimental) on Ubuntu-18.04'], + 'wpt_tests_suite_linux': + ['wpt_tests_suite (experimental) on Ubuntu-18.04'], + 'wpt_tests_suite_win10': + ['wpt_tests_suite (experimental) on Windows-10-19042'], 'blink_wpt_tests': ['blink_wpt_tests on Ubuntu-18.04'] } @@ -286,8 +292,8 @@ # names to their results map tests_to_actual_results = {} tests_to_baseline_results = {} - if (args.product_to_compare.startswith('chrome_linux') or - args.product_to_compare.startswith('wpt_content_shell_linux')): + if (args.product_to_compare.startswith('chrome_linux') + or args.product_to_compare.startswith('wpt_content_shell')): path = '/external/wpt' else: path = '' @@ -295,8 +301,8 @@ actual_results_json['tests'], path=path) - if (args.baseline_product.startswith('chrome_linux') or - args.baseline_product.startswith('wpt_content_shell_linux')): + if (args.baseline_product.startswith('chrome_linux') + or args.baseline_product.startswith('wpt_content_shell')): path = '/external/wpt' else: path = ''
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 829cc5a..a5fb4fb 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -4588,7 +4588,7 @@ # Sheriff 2020-06-17 crbug.com/1092975 http/tests/inspector-protocol/target/target-expose-devtools-protocol.js [ Failure Pass ] -crbug.com/1096493 external/wpt/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https.html [ Failure ] +crbug.com/1385294 external/wpt/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https.html [ Crash Failure Pass Timeout ] crbug.com/1097005 http/tests/devtools/console/console-object-preview.js [ Crash Failure Pass Timeout ] crbug.com/1097005 http/tests/devtools/console/console-preserve-scroll.js [ Crash Failure Pass Timeout ] @@ -6358,6 +6358,7 @@ crbug.com/1378078 [ Debug Linux ] media/controls/slow-doubletap.html [ Failure ] crbug.com/1385491 [ Win ] external/wpt/selection/user-select-on-input-and-contenteditable.html [ Skip Timeout ] crbug.com/1385538 [ Win ] http/tests/serviceworker/postmessage-cross-process.html [ Failure ] +crbug.com/1385538 [ Linux ] http/tests/serviceworker/postmessage-cross-process.html [ Failure ] crbug.com/1377056 [ Debug Linux ] payments/payment-request-interface.html [ Failure ] crbug.com/1377056 [ Mac ] payments/payment-request-interface.html [ Failure ] crbug.com/1385919 [ Win ] external/wpt/css/selectors/focus-visible-018-2.html [ Skip Timeout ] @@ -6370,6 +6371,10 @@ crbug.com/1385929 [ Win ] editing/selection/mouse/mouse-selection-vertical-lr.html [ Timeout ] crbug.com/1385929 [ Win ] editing/selection/mouse/mouse-selection-horizontal.html [ Timeout ] crbug.com/1392480 [ Win ] wpt_internal/hid/hidDevice_reports.https.window.html [ Timeout ] +crbug.com/1386214 [ Win ] external/wpt/html/semantics/forms/the-input-element/selection-pointer.html [ Skip Timeout ] +crbug.com/1386214 [ Win ] external/wpt/html/semantics/forms/the-input-element/show-picker-user-gesture.html [ Skip Timeout ] +crbug.com/1392516 [ Win ] pointer-lock/wheel-event-cancelable.html [ Timeout ] +crbug.com/1392517 [ Debug Linux ] http/tests/serviceworker/postmessage-after-terminate.html [ Failure ] # Sheriff 2022-10-07 crbug.com/1372556 [ Linux ] external/wpt/css/css-text/text-transform/text-transform-capitalize-* [ Failure Pass ]
diff --git a/third_party/blink/web_tests/accessibility/aria-owns-sends-notification.html b/third_party/blink/web_tests/accessibility/aria-owns-sends-notification.html index b51a093..eaf63d69 100644 --- a/third_party/blink/web_tests/accessibility/aria-owns-sends-notification.html +++ b/third_party/blink/web_tests/accessibility/aria-owns-sends-notification.html
@@ -13,6 +13,7 @@ assert_equals(axFutureParent.childrenCount, 0); var expected_notifications = new Set(); + expected_notifications.add("ChildrenChanged"); expected_notifications.add("MarkDirty"); while (expected_notifications.size) { @@ -34,7 +35,7 @@ var child = document.createElement("li"); child.id = "future_child"; futureParent.parentElement.appendChild(child); -}, "A mark dirty notification is fired when an aria-owned child gets added to the tree."); +}, "A children changed notification is fired when an aria-owned child gets added to the tree."); </script> <div id="container2"> @@ -53,7 +54,7 @@ var axList1 = accessibilityController.accessibleElementById("list1"); assert_equals(axList1.childrenCount, 0, "No children before setting aria-owns"); var listener = t.step_func((notification) => { - assert_equals(notification, "MarkDirty"); + assert_equals(notification, "ChildrenChanged"); assert_equals(axList1.childrenCount, 1, "One child after setting aria-owns"); axList1.removeNotificationListener(listener); @@ -63,7 +64,7 @@ var list1 = document.getElementById("list1"); list1.setAttribute("aria-owns", "item1"); -}, "A mark dirty notification is fired when an aria-owned attribute is added to an element that causes it to reparent another element to become its child."); +}, "A children changed notification is fired when an aria-owned attribute is added to an element that causes it to reparent another element to become its child."); </script> <div id="container3"> @@ -84,7 +85,7 @@ var axList2 = accessibilityController.accessibleElementById("newlist2"); assert_equals(axList2.childrenCount, 1); var listener = t.step_func((notification) => { - assert_equals(notification, "MarkDirty"); + assert_equals(notification, "ChildrenChanged"); assert_equals(axList2.childrenCount, 0); assert_equals(axList1.childrenCount, 1); @@ -96,5 +97,5 @@ list1.setAttribute("aria-owns", "newitem1"); assert_equals(axList1.childrenCount, 1); assert_equals(axList2.childrenCount, 0); -}, "A mark dirty notification is fired on the old parent when one of its children gets reparented to another element due to aria-owns."); +}, "A children changed notification is fired on the old parent when one of its children gets reparented to another element due to aria-owns."); </script>
diff --git a/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt new file mode 100644 index 0000000..891983b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any-expected.txt
@@ -0,0 +1,24 @@ +This is a testharness.js-based test. +PASS move(name) to rename a file +PASS get a handle to a moved file +PASS move(name) to rename a file the same name +PASS move("") to rename a file fails +PASS move(name) can be called multiple times +PASS move(name) with a name with a trailing period should fail +PASS move(name) with a name with invalid characters should fail +PASS move(name) while the file has an open writable fails +FAIL move(name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +PASS move(dir, name) to rename a file +PASS move(dir, name) to rename a file the same name +PASS move(dir) to move a file to a new directory +PASS move(dir, "") to move a file to a new directory fails +PASS move(dir, name) to move a file to a new directory +PASS move(dir) can be called multiple times +PASS move(dir, name) can be called multiple times +PASS move(dir, name) with a name with invalid characters should fail +PASS move(dir) while the file has an open writable fails +PASS move(dir, name) while the file has an open writable fails +FAIL move(dir) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +FAIL move(dir, name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt new file mode 100644 index 0000000..891983b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fs/FileSystemFileHandle-move.https.any.worker-expected.txt
@@ -0,0 +1,24 @@ +This is a testharness.js-based test. +PASS move(name) to rename a file +PASS get a handle to a moved file +PASS move(name) to rename a file the same name +PASS move("") to rename a file fails +PASS move(name) can be called multiple times +PASS move(name) with a name with a trailing period should fail +PASS move(name) with a name with invalid characters should fail +PASS move(name) while the file has an open writable fails +FAIL move(name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +PASS move(dir, name) to rename a file +PASS move(dir, name) to rename a file the same name +PASS move(dir) to move a file to a new directory +PASS move(dir, "") to move a file to a new directory fails +PASS move(dir, name) to move a file to a new directory +PASS move(dir) can be called multiple times +PASS move(dir, name) can be called multiple times +PASS move(dir, name) with a name with invalid characters should fail +PASS move(dir) while the file has an open writable fails +PASS move(dir, name) while the file has an open writable fails +FAIL move(dir) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +FAIL move(dir, name) while the destination file has an open writable fails assert_unreached: Should have rejected: undefined Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-av1.html b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-av1.html deleted file mode 100644 index 24cfcb8f..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-av1.html +++ /dev/null
@@ -1,43 +0,0 @@ -<!doctype html> -<meta charset=utf-8> -<meta name="timeout" content="long"> -<title>AV1 scalabilityMode</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/webrtc/RTCRtpParameters-helper.js"></script> -<script src="/webrtc/RTCPeerConnection-helper.js"></script> -<script src="/webrtc-svc/svc-helper.js"></script> -<script> - 'use strict'; - - createScalabilityTest('video/AV1', [ - "L1T1", - "L1T2", - "L1T3", - "L2T1", - "L2T2", - "L2T3", - "L3T1", - "L3T2", - "L3T3", - "L2T1h", - "L2T2h", - "L2T3h", - "S2T1", - "S2T2", - "S2T3", - "S2T1h", - "S2T2h", - "S2T3h", - "S3T1", - "S3T2", - "S3T3", - "S3T1h", - "S3T2h", - "S3T3h", - "L2T2_KEY", - "L2T3_KEY", - "L3T2_KEY", - "L3T3_KEY" - ]); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-expected.txt index 816a2534..79d1d575 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-expected.txt
@@ -1,10 +1,30 @@ This is a testharness.js-based test. +PASS [0] video/VP8 - L1T2 should produce valid video content +PASS [1] video/VP8 - L1T3 should produce valid video content +PASS [2] video/VP9 - L1T2 should produce valid video content +PASS [3] video/VP9 - L1T3 should produce valid video content +PASS [4] video/AV1 - L1T2 should produce valid video content +PASS [5] video/AV1 - L1T3 should produce valid video content +PASS [6] video/AV1 - L2T1 should produce valid video content +PASS [7] video/AV1 - L2T1h should produce valid video content +PASS [8] video/AV1 - L2T1_KEY should produce valid video content +PASS [9] video/AV1 - L2T2 should produce valid video content +PASS [10] video/AV1 - L2T2_KEY should produce valid video content +PASS [11] video/AV1 - L2T2_KEY_SHIFT should produce valid video content +PASS [12] video/AV1 - L3T1 should produce valid video content +PASS [13] video/AV1 - L3T3 should produce valid video content +PASS [14] video/AV1 - L3T3_KEY should produce valid video content +PASS [15] video/AV1 - S2T1 should produce valid video content PASS Setting and updating scalabilityMode to a legal value should be accepted PASS Sender capabilities should include at least some scalability modes PASS Not setting sendEncodings results in no mode info before negotiation PASS Not setting a scalability mode results in no mode set before negotiation FAIL Not setting a scalability mode results in some mode set after negotiation assert_true: expected true got false -PASS Setting a scalability mode to nonsense throws an exception +FAIL Setting a scalability mode to nonsense throws an exception assert_throws_dom: function "() => { + pc.addTransceiver('video', { + sendEncodings: [{scalabilityMode: 'TotalNonsense'}], + }); + }" did not throw FAIL L3T3 on VP8 should return something other than L3T3 assert_not_equals: got disallowed value "L3T3" Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-h264.html b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-h264.html deleted file mode 100644 index 2a595a8..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-h264.html +++ /dev/null
@@ -1,18 +0,0 @@ -<!doctype html> -<meta charset=utf-8> -<meta name="timeout" content="long"> -<title>H264 scalabilityMode</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/webrtc/RTCRtpParameters-helper.js"></script> -<script src="/webrtc/RTCPeerConnection-helper.js"></script> -<script src="/webrtc-svc/svc-helper.js"></script> -<script> - 'use strict'; - - createScalabilityTest('video/H264', [ - "L1T1", - "L1T2", - "L1T3" - ]); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp8.html b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp8.html deleted file mode 100644 index 1708ab1..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp8.html +++ /dev/null
@@ -1,18 +0,0 @@ -<!doctype html> -<meta charset=utf-8> -<meta name="timeout" content="long"> -<title>VP8 scalabilityMode</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/webrtc/RTCRtpParameters-helper.js"></script> -<script src="/webrtc/RTCPeerConnection-helper.js"></script> -<script src="/webrtc-svc/svc-helper.js"></script> -<script> - 'use strict'; - - createScalabilityTest('video/VP8', [ - "L1T1", - "L1T2", - "L1T3" - ]); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp9.html b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp9.html deleted file mode 100644 index f1f4923..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability-vp9.html +++ /dev/null
@@ -1,43 +0,0 @@ -<!doctype html> -<meta charset=utf-8> -<meta name="timeout" content="long"> -<title>VP9 scalabilityMode</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/webrtc/RTCRtpParameters-helper.js"></script> -<script src="/webrtc/RTCPeerConnection-helper.js"></script> -<script src="/webrtc-svc/svc-helper.js"></script> -<script> - 'use strict'; - - createScalabilityTest('video/VP9', [ - "L1T1", - "L1T2", - "L1T3", - "L2T1", - "L2T2", - "L2T3", - "L3T1", - "L3T2", - "L3T3", - "L2T1h", - "L2T2h", - "L2T3h", - "S2T1", - "S2T2", - "S2T3", - "S2T1h", - "S2T2h", - "S2T3h", - "S3T1", - "S3T2", - "S3T3", - "S3T1h", - "S3T2h", - "S3T3h", - "L2T2_KEY", - "L2T3_KEY", - "L3T2_KEY", - "L3T3_KEY" - ]); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability.html b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability.html index d8b1c6e..c32a128 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability.html +++ b/third_party/blink/web_tests/external/wpt/webrtc-svc/RTCRtpParameters-scalability.html
@@ -1,6 +1,5 @@ <!doctype html> <meta charset=utf-8> -<meta name="timeout" content="long"> <title>RTCRtpParameters encodings</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -13,6 +12,46 @@ // Test is based on the following editor draft: // https://w3c.github.io/webrtc-svc/ + // Get the first encoding in param.encodings. + // Asserts that param.encodings has at least one element. + function getFirstEncoding(param) { + const { encodings } = param; + assert_equals(encodings.length, 1); + return encodings[0]; + } + + const capabilities = RTCRtpSender.getCapabilities('video'); + let index = 0; + for (const codec of capabilities.codecs) { + if ('scalabilityModes' in codec && codec.scalabilityModes.length > 0) { + for (const scalabilityMode of codec.scalabilityModes) { + promise_test(async t => { + const v = document.createElement('video'); + v.autoplay = true; + const pc1 = new RTCPeerConnection(); + const pc2 = new RTCPeerConnection(); + t.add_cleanup(() => pc1.close()); + t.add_cleanup(() => pc2.close()); + const stream1 = await getNoiseStream({ video: { signal: 100 , width: 60, height: 60} }); + const [track1] = stream1.getTracks(); + t.add_cleanup(() => track1.stop()); + const transceiver = pc1.addTransceiver(track1, { + sendEncodings: [{ scalabilityMode: scalabilityMode }], + }); + transceiver.setCodecPreferences([codec]); + const haveTrackEvent = new Promise(r => pc2.ontrack = r); + exchangeIceCandidates(pc1, pc2); + await exchangeOfferAnswer(pc1, pc2); + v.srcObject = new MediaStream([(await haveTrackEvent).track]); + await new Promise(r => v.onloadedmetadata = r); + await detectSignal(t, v, 100); + const sendParams = pc1.getSenders()[0].getParameters(); + assert_equals(sendParams.encodings[0].scalabilityMode, scalabilityMode); + }, `[${index++}] ${codec.mimeType} - ${scalabilityMode} should produce valid video content`); + } + } + } + promise_test(async t => { const pc = new RTCPeerConnection(); t.add_cleanup(() => pc.close()); @@ -45,78 +84,81 @@ assert_true(svcSupported); }, `Sender capabilities should include at least some scalability modes`); - promise_test(async t => { +promise_test(async t => { + const pc = new RTCPeerConnection(); + t.add_cleanup(() => pc.close()); + const { sender } = pc.addTransceiver('video'); + const param = sender.getParameters(); + assert_equals(param.encodings.length, 0); +}, 'Not setting sendEncodings results in no mode info before negotiation'); + +promise_test(async t => { + const pc = new RTCPeerConnection(); + t.add_cleanup(() => pc.close()); + const { sender } = pc.addTransceiver('video', { + sendEncodings: [{}], + }); + const param = sender.getParameters(); + const encoding = getFirstEncoding(param); + + assert_true(!('scalabilityMode' in encoding)); +}, 'Not setting a scalability mode results in no mode set before negotiation'); + +promise_test(async t => { + const pc1 = new RTCPeerConnection(); + const pc2 = new RTCPeerConnection(); + t.add_cleanup(() => pc1.close()); + t.add_cleanup(() => pc2.close()); + const { sender } = pc1.addTransceiver('video', { + sendEncodings: [{}], + }); + const param = sender.getParameters(); + const encoding = getFirstEncoding(param); + + exchangeIceCandidates(pc1, pc2); + await exchangeOfferAnswer(pc1, pc2); + const param2 = sender.getParameters(); + const encoding2 = getFirstEncoding(param); + assert_true('scalabilityMode' in encoding2); +}, 'Not setting a scalability mode results in some mode set after negotiation'); + +promise_test(async t => { const pc = new RTCPeerConnection(); - t.add_cleanup(() => pc.close()); - const { sender } = pc.addTransceiver('video'); - const param = sender.getParameters(); - assert_equals(param.encodings.length, 0); - }, 'Not setting sendEncodings results in no mode info before negotiation'); - - promise_test(async t => { - const pc = new RTCPeerConnection(); - t.add_cleanup(() => pc.close()); - const { sender } = pc.addTransceiver('video', { - sendEncodings: [{}], + t.add_cleanup(() => pc.close()); + assert_throws_dom('OperationError', () => { + pc.addTransceiver('video', { + sendEncodings: [{scalabilityMode: 'TotalNonsense'}], }); - const param = sender.getParameters(); - const encoding = getFirstEncoding(param); + }); +}, 'Setting a scalability mode to nonsense throws an exception'); - assert_true(!('scalabilityMode' in encoding)); - }, 'Not setting a scalability mode results in no mode set before negotiation'); - promise_test(async t => { - const pc1 = new RTCPeerConnection(); - const pc2 = new RTCPeerConnection(); - t.add_cleanup(() => pc1.close()); - t.add_cleanup(() => pc2.close()); - const { sender } = pc1.addTransceiver('video', { - sendEncodings: [{}], - }); - const param = sender.getParameters(); - const encoding = getFirstEncoding(param); +promise_test(async t => { + const v = document.createElement('video'); + v.autoplay = true; + const pc1 = new RTCPeerConnection(); + const pc2 = new RTCPeerConnection(); + t.add_cleanup(() => pc1.close()); + t.add_cleanup(() => pc2.close()); + const transceiver = pc1.addTransceiver('video', { + sendEncodings: [{ scalabilityMode: 'L3T3' }], + }); + // Before negotiation, the mode should be preserved. + const param = transceiver.sender.getParameters(); + const encoding = getFirstEncoding(param); + assert_true('scalabilityMode' in encoding); + // If L3T3 is not supported at all, abort test. + assert_implements_optional(encoding.scalabilityMode === 'L3T3'); + // Pick a codec known to not have L3T3 support + const capabilities = RTCRtpSender.getCapabilities('video'); + const codec = capabilities.codecs.find(c => c.mimeType === 'video/VP8'); + assert_true(codec !== undefined); + transceiver.setCodecPreferences([codec]); + exchangeIceCandidates(pc1, pc2); + await exchangeOfferAnswer(pc1, pc2); + const sendParams = pc1.getSenders()[0].getParameters(); + assert_not_equals(sendParams.encodings[0].scalabilityMode, 'L3T3'); +}, 'L3T3 on VP8 should return something other than L3T3'); - exchangeIceCandidates(pc1, pc2); - await exchangeOfferAnswer(pc1, pc2); - const param2 = sender.getParameters(); - const encoding2 = getFirstEncoding(param); - assert_true('scalabilityMode' in encoding2); - }, 'Not setting a scalability mode results in some mode set after negotiation'); - promise_test(async t => { - const pc = new RTCPeerConnection(); - t.add_cleanup(() => pc.close()); - assert_throws_dom('OperationError', () => { - pc.addTransceiver('video', { - sendEncodings: [{scalabilityMode: 'TotalNonsense'}], - }); - }); - }, 'Setting a scalability mode to nonsense throws an exception'); - - promise_test(async t => { - const v = document.createElement('video'); - v.autoplay = true; - const pc1 = new RTCPeerConnection(); - const pc2 = new RTCPeerConnection(); - t.add_cleanup(() => pc1.close()); - t.add_cleanup(() => pc2.close()); - const transceiver = pc1.addTransceiver('video', { - sendEncodings: [{ scalabilityMode: 'L3T3' }], - }); - // Before negotiation, the mode should be preserved. - const param = transceiver.sender.getParameters(); - const encoding = getFirstEncoding(param); - assert_true('scalabilityMode' in encoding); - // If L3T3 is not supported at all, abort test. - assert_implements_optional(encoding.scalabilityMode === 'L3T3'); - // Pick a codec known to not have L3T3 support - const capabilities = RTCRtpSender.getCapabilities('video'); - const codec = capabilities.codecs.find(c => c.mimeType === 'video/VP8'); - assert_true(codec !== undefined); - transceiver.setCodecPreferences([codec]); - exchangeIceCandidates(pc1, pc2); - await exchangeOfferAnswer(pc1, pc2); - const sendParams = pc1.getSenders()[0].getParameters(); - assert_not_equals(sendParams.encodings[0].scalabilityMode, 'L3T3'); - }, 'L3T3 on VP8 should return something other than L3T3'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc-svc/svc-helper.js b/third_party/blink/web_tests/external/wpt/webrtc-svc/svc-helper.js deleted file mode 100644 index e73ccfa7..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc-svc/svc-helper.js +++ /dev/null
@@ -1,50 +0,0 @@ -function supportsCodec(mimeType) { - return RTCRtpSender.getCapabilities('video').codecs.filter(c => c.mimeType == mimeType).length() > 0; -} - -async function supportsScalabilityMode(mimeType, scalabilityMode) { - let result = await navigator.mediaCapabilities.encodingInfo({ - type: 'webrtc', - video: { - contentType: mimeType, - width: 60, - height: 60, - bitrate: 10000, - framerate: 30, - scalabilityMode: scalabilityMode - } - }); - return result.supported; -} - -function createScalabilityTest(mimeType, scalabilityModes) { - for (const scalabilityMode of scalabilityModes) { - promise_test(async t => { - assert_implements_optional( - supportsScalabilityMode(mimeType, scalabilityMode), - `${mimeType} supported` - ); - const v = document.createElement('video'); - v.autoplay = true; - const pc1 = new RTCPeerConnection(); - const pc2 = new RTCPeerConnection(); - t.add_cleanup(() => pc1.close()); - t.add_cleanup(() => pc2.close()); - const stream1 = await getNoiseStream({ video: { signal: 100, width: 60, height: 60 } }); - const [track1] = stream1.getTracks(); - t.add_cleanup(() => track1.stop()); - const transceiver = pc1.addTransceiver(track1, { - sendEncodings: [{ scalabilityMode: scalabilityMode }], - }); - transceiver.setCodecPreferences(RTCRtpSender.getCapabilities('video').codecs.filter(c => c.mimeType == mimeType)); - const haveTrackEvent = new Promise(r => pc2.ontrack = r); - exchangeIceCandidates(pc1, pc2); - await exchangeOfferAnswer(pc1, pc2); - v.srcObject = new MediaStream([(await haveTrackEvent).track]); - await new Promise(r => v.onloadedmetadata = r); - await detectSignal(t, v, 100); - const sendParams = pc1.getSenders()[0].getParameters(); - assert_equals(sendParams.encodings[0].scalabilityMode, scalabilityMode); - }, `${mimeType} - ${scalabilityMode} should produce valid video content`); - } -}
diff --git a/third_party/blink/web_tests/flag-specific/disable-layout-ng/accessibility/aria-owns-sends-notification-expected.txt b/third_party/blink/web_tests/flag-specific/disable-layout-ng/accessibility/aria-owns-sends-notification-expected.txt index 07bd145e..f48253f9 100644 --- a/third_party/blink/web_tests/flag-specific/disable-layout-ng/accessibility/aria-owns-sends-notification-expected.txt +++ b/third_party/blink/web_tests/flag-specific/disable-layout-ng/accessibility/aria-owns-sends-notification-expected.txt
@@ -1,6 +1,6 @@ This is a testharness.js-based test. -PASS A mark dirty notification is fired when an aria-owned child gets added to the tree. -PASS A mark dirty notification is fired when an aria-owned attribute is added to an element that causes it to reparent another element to become its child. -PASS A mark dirty notification is fired on the old parent when one of its children gets reparented to another element due to aria-owns. +PASS A children changed notification is fired when an aria-owned child gets added to the tree. +FAIL A children changed notification is fired when an aria-owned attribute is added to an element that causes it to reparent another element to become its child. assert_equals: expected "ChildrenChanged" but got "MarkDirty" +PASS A children changed notification is fired on the old parent when one of its children gets reparented to another element due to aria-owns. Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js index 4e7c769..9d9f6f9c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js +++ b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js
@@ -12,6 +12,9 @@ return message; } + + const frameTargetSession = SDK.targetManager.mainFrameTarget().sessionId; + var messages = [ 'some wrong string', '{}', @@ -19,26 +22,26 @@ '{"id":1,"method":1}', '{"id":2,"method":"resourceContent"}', '{"id":3,"method":"DOM.test"}', - '{"id":4,"method":"DOM.requestChildNodes"}', - '{"id":5,"method":"DOM.requestChildNodes","params":[]}', - '{"id":6,"method":"DOM.requestChildNodes","params":{}}', - '{"id":7,"method":"DOM.requestChildNodes","params":{"nodeId":"not a number"}}', - '{"id":8,"method":"DOM.test"}', - '{"id":9,"method":"DOM.test" }', - '{"id":10,"method": "DOM.test" }', - '{"id":11,"method" : "DOM.test" }', - '{"id":12, "method" : "DOM.test" }', - '{"id": 13, "method" : "DOM.test" }', - '{"id" : 14, "method" : "DOM.test" }', - '{ "id" : 15, "method" : "DOM.test" }', - '{ "id"\n :\r 16,\t "method" : "DOM.test" }', + `{"id":4,"method":"DOM.requestChildNodes", "sessionId": "${frameTargetSession}"}`, + `{"id":5,"method":"DOM.requestChildNodes","params":[], "sessionId": "${frameTargetSession}"}`, + `{"id":6,"method":"DOM.requestChildNodes","params":{}, "sessionId": "${frameTargetSession}"}`, + `{"id":7,"method":"DOM.requestChildNodes","params":{"nodeId":"not a number"}, "sessionId": "${frameTargetSession}"}`, + `{"id":8,"method":"DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id":9,"method":"DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id":10,"method": "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id":11,"method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id":12, "method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id": 13, "method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{"id" : 14, "method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{ "id" : 15, "method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, + `{ "id"\n :\r 16,\t "method" : "DOM.test", "sessionId": "${frameTargetSession}"}`, ]; var numberOfReports = 0; ProtocolClient.InspectorBackend.reportProtocolError = function(error, message) { if (numberOfReports < messages.length) { - TestRunner.addObject(trimErrorMessage(message)); + TestRunner.addObject(trimErrorMessage(message), {'sessionId': 'skip'}); TestRunner.addResult('-------------------------------------------------------'); }
diff --git a/third_party/blink/web_tests/resources/testharness.js b/third_party/blink/web_tests/resources/testharness.js index 7ac36321..55aaa582 100644 --- a/third_party/blink/web_tests/resources/testharness.js +++ b/third_party/blink/web_tests/resources/testharness.js
@@ -2246,7 +2246,8 @@ ReadOnlyError: 0, VersionError: 0, OperationError: 0, - NotAllowedError: 0 + NotAllowedError: 0, + OptOutError: 0 }; var code_name_map = {};
diff --git a/third_party/modp_b64/README.chromium b/third_party/modp_b64/README.chromium index 8d218df8..4fdd7c5a 100644 --- a/third_party/modp_b64/README.chromium +++ b/third_party/modp_b64/README.chromium
@@ -17,3 +17,5 @@ - Extended the API so callers can avoid overload for base64 encode - Removed big endian support entirely - Removed std::string APIs +- Added multiple decoding options to support Blink callers +- Added modp_b64_encode_data which doesn't append a null terminator
diff --git a/third_party/modp_b64/modp_b64.cc b/third_party/modp_b64/modp_b64.cc index b8db38b5..2901a8f 100644 --- a/third_party/modp_b64/modp_b64.cc +++ b/third_party/modp_b64/modp_b64.cc
@@ -49,24 +49,7 @@ #define BADCHAR 0x01FFFFFF -/** - * you can control if we use padding by commenting out this - * next line. However, I highly recommend you use padding and not - * using it should only be for compatability with a 3rd party. - * Also, 'no padding' is not tested! - */ -#define DOPAD 1 - -/* - * if we aren't doing padding - * set the pad character to NULL - */ -#ifndef DOPAD -#undef CHARPAD -#define CHARPAD '\0' -#endif - -size_t modp_b64_encode(char* dest, const char* str, size_t len) +size_t modp_b64_encode_data(char* dest, const char* str, size_t len) { size_t i = 0; uint8_t* p = (uint8_t*) dest; @@ -102,28 +85,42 @@ *p++ = CHARPAD; } - *p = '\0'; return p - (uint8_t*)dest; } -size_t modp_b64_decode(char* dest, const char* src, size_t len) -{ - if (len == 0) return 0; +size_t modp_b64_encode(char* dest, const char* str, size_t len) { + size_t output_size = modp_b64_encode_data(dest, str, len); + dest[output_size] = '\0'; + return output_size; +} -#ifdef DOPAD - /* - * if padding is used, then the message must be at least - * 4 chars and be a multiple of 4 - */ - if (len < 4 || (len % 4 != 0)) return MODP_B64_ERROR; /* error */ - /* there can be at most 2 pad chars at the end */ - if (src[len-1] == CHARPAD) { +size_t do_decode_padding(const char* src, size_t len, ModpDecodePolicy policy) { + if (policy == ModpDecodePolicy::kNoPaddingValidation) { + while (len > 0 && src[len - 1] == CHARPAD) { len--; - if (src[len -1] == CHARPAD) { - len--; - } } -#endif + } else { + const size_t remainder = len % 4; + if (policy == ModpDecodePolicy::kStrict && (remainder != 0 || len < 4)) + return MODP_B64_ERROR; + if (remainder == 0) { + if (src[len - 1] == CHARPAD) { + len--; + if (src[len - 1] == CHARPAD) { + len--; + } + } + } + } + return len % 4 == 1 ? MODP_B64_ERROR : len; +} + +size_t modp_b64_decode(char* dest, const char* src, size_t len, ModpDecodePolicy policy) +{ + if (len == 0 || + (len = do_decode_padding(src, len, policy)) == MODP_B64_ERROR) { + return len; + } size_t i; int leftover = len % 4;
diff --git a/third_party/modp_b64/modp_b64.h b/third_party/modp_b64/modp_b64.h index 32e9891..9d11f811 100644 --- a/third_party/modp_b64/modp_b64.h +++ b/third_party/modp_b64/modp_b64.h
@@ -37,17 +37,16 @@ * len contains the number of bytes in the src * dest should be allocated by the caller to contain * at least modp_b64_encode_len(len) bytes (see below) - * This will contain the null-terminated b64 encoded result - * returns length of the destination string plus the ending null byte - * i.e. the result will be equal to strlen(dest) + 1 + * This will contain the (non-null terminated) b64 bytes. + * returns length of the destination string. * * Example - * + * * \code * char* src = ...; * int srclen = ...; //the length of number of bytes in src * char* dest = (char*) malloc(modp_b64_encode_len); - * int len = modp_b64_encode(dest, src, sourcelen); + * int len = modp_b64_encode_data(dest, src, sourcelen); * if (len == -1) { * printf("Error\n"); * } else { @@ -56,6 +55,17 @@ * \endcode * */ +size_t modp_b64_encode_data(char* dest, const char* str, size_t len); + +/** + * Same as modp_b64_encode_data, but additionally sets a null terminator at the + * end of `dest` (i.e. at dest[output_size]). + * Like modp_b64_encode_data, returns the length of the destination string (i.e. + * not counting the null terminator). + * + * TODO(csharrison): Consider removing this once all callers migrate to + * modp_b64_encode_data. + */ size_t modp_b64_encode(char* dest, const char* str, size_t len); /** @@ -79,11 +89,27 @@ * if (len == -1) { error } * \endcode */ -size_t modp_b64_decode(char* dest, const char* src, size_t len); +enum class ModpDecodePolicy { + // src length must be divisible by 4, with a max of 2 pad chars. + kStrict, + + // Matches the infra spec: https://infra.spec.whatwg.org/#forgiving-base64 + // _except_ for ignoring whitespace (Step 1). + kForgiving, + + // src length % 4 must not equal 1, after stripping all pad chars. + // Accepts any number of pad chars. + kNoPaddingValidation, +}; +size_t modp_b64_decode( + char* dest, + const char* src, + size_t len, + ModpDecodePolicy policy = ModpDecodePolicy::kStrict); /** - * The maximum input that can be passed into modp_b64_encode. Lengths beyond - * this will overflow modp_b64_encode_len. + * The maximum input that can be passed into modp_b64_encode{_data}. + * Lengths beyond this will overflow modp_b64_encode_len. * * This works because modp_b64_encode_len(A) computes: * ceiling[max_len / 3] * 4 + 1 @@ -91,23 +117,27 @@ * = floor[(SIZE_MAX-1)/4] * 4 + 1 * <= SIZE_MAX-1 + 1 * = SIZE_MAX + * + * Note: technically modp_b64_encode_data can take one extra byte, but for + * simplicity the bound is shared between the two functions. */ #define MODP_B64_MAX_INPUT_LEN ((SIZE_MAX - 1) / 4 * 3) /** * Given a source string of length len, this returns the amount of - * memory the destination string should have. + * memory the destination string should have, for modp_b64_encode_data and + * modp_b64_encode, respectively. * * remember, this is integer math * 3 bytes turn into 4 chars - * ceiling[len / 3] * 4 + 1 + * ceiling[len / 3] * 4 * - * +1 is for any extra null. * - * WARNING: This expression will overflow if the A is above + * WARNING: These expressions will overflow if the A is above * MODP_B64_MAX_INPUT_LEN. The caller must check this bound first. */ -#define modp_b64_encode_len(A) ((A+2)/3 * 4 + 1) +#define modp_b64_encode_data_len(A) ((A + 2) / 3 * 4) +#define modp_b64_encode_len(A) (modp_b64_encode_data_len(A) + 1) /** * Given a base64 string of length len,
diff --git a/third_party/nearby/README.chromium b/third_party/nearby/README.chromium index f6ecbff..26cf4f0 100644 --- a/third_party/nearby/README.chromium +++ b/third_party/nearby/README.chromium
@@ -1,7 +1,7 @@ Name: Nearby Connections Library Short Name: Nearby URL: https://github.com/google/nearby -Version: a3b6058753fb9f9590194f68e3853c2787fcf279 +Version: c499d18af696bf73b36a5db8c3388e01b5c41b0c License: Apache 2.0 License File: LICENSE Security Critical: yes
diff --git a/third_party/wpt_tools/README.chromium b/third_party/wpt_tools/README.chromium index 89b8e77a..4275ed16 100644 --- a/third_party/wpt_tools/README.chromium +++ b/third_party/wpt_tools/README.chromium
@@ -1,7 +1,7 @@ Name: web-platform-tests - Test Suites for Web Platform specifications Short Name: wpt URL: https://github.com/web-platform-tests/wpt/ -Version: 4fe944a225480573ce60e0e93d7200398b1cecac +Version: d0d9cbe29465cfb9a420bad5799090e68d014dcf License: LICENSES FOR W3C TEST SUITES (https://www.w3.org/Consortium/Legal/2008/03-bsd-license.html) License File: NOT_SHIPPED Security Critical: no
diff --git a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/browsers/base.py b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/browsers/base.py index d723912..5b590ad 100644 --- a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/browsers/base.py +++ b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/browsers/base.py
@@ -87,9 +87,7 @@ """Abstract class serving as the basis for Browser implementations. The Browser is used in the TestRunnerManager to start and stop the browser - process, and to check the state of that process. This class also acts as a - context manager, enabling it to do browser-specific setup at the start of - the testrun and cleanup after the run is complete. + process, and to check the state of that process. :param logger: Structured logger to use for output. """ @@ -101,13 +99,6 @@ def __init__(self, logger): self.logger = logger - def __enter__(self): - self.setup() - return self - - def __exit__(self, *args, **kwargs): - self.cleanup() - def setup(self): """Used for browser-specific setup that happens at the start of a test run""" pass
diff --git a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testloader.py b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testloader.py index ed290ae9..0cb5f499 100644 --- a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testloader.py +++ b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testloader.py
@@ -1,12 +1,13 @@ # mypy: allow-untyped-defs import hashlib +import itertools import json import os from urllib.parse import urlsplit from abc import ABCMeta, abstractmethod from queue import Empty -from collections import defaultdict, deque +from collections import defaultdict, deque, namedtuple from . import manifestinclude from . import manifestexpected @@ -359,24 +360,26 @@ return test_source_cls, test_source_kwargs, chunker_kwargs +TestGroup = namedtuple("TestGroup", ["group", "test_type", "metadata"]) + + class TestSource: __metaclass__ = ABCMeta def __init__(self, test_queue): self.test_queue = test_queue - self.current_group = None - self.current_metadata = None + self.current_group = TestGroup(None, None, None) self.logger = structured.get_default_logger() if self.logger is None: self.logger = structured.structuredlog.StructuredLogger("TestSource") @abstractmethod #@classmethod (doesn't compose with @abstractmethod in < 3.3) - def make_queue(cls, tests, **kwargs): # noqa: N805 + def make_queue(cls, tests_by_type, **kwargs): # noqa: N805 pass @abstractmethod - def tests_by_group(cls, tests, **kwargs): # noqa: N805 + def tests_by_group(cls, tests_by_type, **kwargs): # noqa: N805 pass @classmethod @@ -384,42 +387,43 @@ return {"scope": "/"} def group(self): - if not self.current_group or len(self.current_group) == 0: + if not self.current_group.group or len(self.current_group.group) == 0: try: - self.current_group, self.current_metadata = self.test_queue.get(block=True, timeout=5) + self.current_group = self.test_queue.get(block=True, timeout=5) except Empty: self.logger.warning("Timed out getting test group from queue") - return None, None - return self.current_group, self.current_metadata + return TestGroup(None, None, None) + return self.current_group @classmethod def add_sentinal(cls, test_queue, num_of_workers): # add one sentinal for each worker for _ in range(num_of_workers): - test_queue.put((None, None)) + test_queue.put(TestGroup(None, None, None)) class GroupedSource(TestSource): @classmethod - def new_group(cls, state, test, **kwargs): + def new_group(cls, state, test_type, test, **kwargs): raise NotImplementedError @classmethod - def make_queue(cls, tests, **kwargs): + def make_queue(cls, tests_by_type, **kwargs): mp = mpcontext.get_context() test_queue = mp.Queue() groups = [] state = {} - for test in tests: - if cls.new_group(state, test, **kwargs): - group_metadata = cls.group_metadata(state) - groups.append((deque(), group_metadata)) + for test_type, tests in tests_by_type.items(): + for test in tests: + if cls.new_group(state, test_type, test, **kwargs): + group_metadata = cls.group_metadata(state) + groups.append(TestGroup(deque(), test_type, group_metadata)) - group, metadata = groups[-1] - group.append(test) - test.update_metadata(metadata) + group, _, metadata = groups[-1] + group.append(test) + test.update_metadata(metadata) for item in groups: test_queue.put(item) @@ -427,51 +431,57 @@ return test_queue @classmethod - def tests_by_group(cls, tests, **kwargs): + def tests_by_group(cls, tests_by_type, **kwargs): groups = defaultdict(list) state = {} current = None - for test in tests: - if cls.new_group(state, test, **kwargs): - current = cls.group_metadata(state)['scope'] - groups[current].append(test.id) + for test_type, tests in tests_by_type.items(): + for test in tests: + if cls.new_group(state, test_type, test, **kwargs): + current = cls.group_metadata(state)['scope'] + groups[current].append(test.id) return groups class SingleTestSource(TestSource): @classmethod - def make_queue(cls, tests, **kwargs): + def make_queue(cls, tests_by_type, **kwargs): mp = mpcontext.get_context() test_queue = mp.Queue() - processes = kwargs["processes"] - queues = [deque([]) for _ in range(processes)] - metadatas = [cls.group_metadata(None) for _ in range(processes)] - for test in tests: - idx = hash(test.id) % processes - group = queues[idx] - metadata = metadatas[idx] - group.append(test) - test.update_metadata(metadata) + for test_type, tests in tests_by_type.items(): + processes = kwargs["processes"] + queues = [deque([]) for _ in range(processes)] + metadatas = [cls.group_metadata(None) for _ in range(processes)] + for test in tests: + idx = hash(test.id) % processes + group = queues[idx] + metadata = metadatas[idx] + group.append(test) + test.update_metadata(metadata) - for item in zip(queues, metadatas): - test_queue.put(item) + for item in zip(queues, itertools.repeat(test_type), metadatas): + if len(item[0]) > 0: + test_queue.put(TestGroup(*item)) cls.add_sentinal(test_queue, kwargs["processes"]) return test_queue @classmethod - def tests_by_group(cls, tests, **kwargs): - return {cls.group_metadata(None)['scope']: [t.id for t in tests]} + def tests_by_group(cls, tests_by_type, **kwargs): + return {cls.group_metadata(None)['scope']: + [t.id for t in itertools.chain.from_iterable(tests_by_type.values())]} class PathGroupedSource(GroupedSource): @classmethod - def new_group(cls, state, test, **kwargs): + def new_group(cls, state, test_type, test, **kwargs): depth = kwargs.get("depth") if depth is True or depth == 0: depth = None path = urlsplit(test.url).path.split("/")[1:-1][:depth] - rv = path != state.get("prev_path") + rv = (test_type != state.get("prev_test_type") or + path != state.get("prev_path")) + state["prev_test_type"] = test_type state["prev_path"] = path return rv @@ -482,36 +492,38 @@ class GroupFileTestSource(TestSource): @classmethod - def make_queue(cls, tests, **kwargs): - tests_by_group = cls.tests_by_group(tests, **kwargs) - - ids_to_tests = {test.id: test for test in tests} - + def make_queue(cls, tests_by_type, **kwargs): mp = mpcontext.get_context() test_queue = mp.Queue() - for group_name, test_ids in tests_by_group.items(): - group_metadata = {"scope": group_name} - group = deque() + for test_type, tests in tests_by_type.items(): + tests_by_group = cls.tests_by_group({test_type: tests}, + **kwargs) - for test_id in test_ids: - test = ids_to_tests[test_id] - group.append(test) - test.update_metadata(group_metadata) + ids_to_tests = {test.id: test for test in tests} - test_queue.put((group, group_metadata)) + for group_name, test_ids in tests_by_group.items(): + group_metadata = {"scope": group_name} + group = deque() + + for test_id in test_ids: + test = ids_to_tests[test_id] + group.append(test) + test.update_metadata(group_metadata) + + test_queue.put(TestGroup(group, test_type, group_metadata)) cls.add_sentinal(test_queue, kwargs["processes"]) return test_queue @classmethod - def tests_by_group(cls, tests, **kwargs): + def tests_by_group(cls, tests_by_type, **kwargs): logger = kwargs["logger"] test_groups = kwargs["test_groups"] tests_by_group = defaultdict(list) - for test in tests: + for test in itertools.chain.from_iterable(tests_by_type.values()): try: group = test_groups.group_by_test[test.id] except KeyError:
diff --git a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testrunner.py b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testrunner.py index b3cae56..61af18c 100644 --- a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testrunner.py +++ b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/testrunner.py
@@ -24,6 +24,11 @@ pass +TestImplementation = namedtuple('TestImplementation', + ['executor_cls', 'executor_kwargs', + 'browser_cls', 'browser_kwargs']) + + class LogMessageHandler: def __init__(self, send_message): self.send_message = send_message @@ -247,9 +252,11 @@ class _RunnerManagerState: before_init = namedtuple("before_init", []) initializing = namedtuple("initializing", - ["test", "test_group", "group_metadata", "failure_count"]) - running = namedtuple("running", ["test", "test_group", "group_metadata"]) - restarting = namedtuple("restarting", ["test", "test_group", "group_metadata", "force_stop"]) + ["test_type", "test", "test_group", + "group_metadata", "failure_count"]) + running = namedtuple("running", ["test_type", "test", "test_group", "group_metadata"]) + restarting = namedtuple("restarting", ["test_type", "test", "test_group", + "group_metadata", "force_stop"]) error = namedtuple("error", []) stop = namedtuple("stop", ["force_stop"]) @@ -258,10 +265,11 @@ class TestRunnerManager(threading.Thread): - def __init__(self, suite_name, index, test_type, test_queue, test_source_cls, browser_cls, - browser_kwargs, executor_cls, executor_kwargs, stop_flag, rerun=1, - pause_after_test=False, pause_on_unexpected=False, restart_on_unexpected=True, - debug_info=None, capture_stdio=True, restart_on_new_group=True, recording=None): + def __init__(self, suite_name, index, test_queue, test_source_cls, + test_implementation_by_type, stop_flag, rerun=1, + pause_after_test=False, pause_on_unexpected=False, + restart_on_unexpected=True, debug_info=None, + capture_stdio=True, restart_on_new_group=True, recording=None): """Thread that owns a single TestRunner process and any processes required by the TestRunner (e.g. the Firefox binary). @@ -282,16 +290,22 @@ self.test_source = test_source_cls(test_queue) self.manager_number = index - self.test_type = test_type - self.browser_cls = browser_cls - self.browser_kwargs = browser_kwargs.copy() - if self.browser_kwargs.get("device_serial"): - # Assign Android device to runner according to current manager index - self.browser_kwargs["device_serial"] = ( - self.browser_kwargs["device_serial"][index]) + self.test_type = None - self.executor_cls = executor_cls - self.executor_kwargs = executor_kwargs + self.test_implementation_by_type = {} + for test_type, test_implementation in test_implementation_by_type.items(): + kwargs = test_implementation.browser_kwargs + if kwargs.get("device_serial"): + kwargs = kwargs.copy() + # Assign Android device to runner according to current manager index + kwargs["device_serial"] = kwargs["device_serial"][index] + self.test_implementation_by_type[test_type] = TestImplementation( + test_implementation.executor_cls, + test_implementation.executor_kwargs, + test_implementation.browser_cls, + kwargs) + else: + self.test_implementation_by_type[test_type] = test_implementation mp = mpcontext.get_context() @@ -345,54 +359,52 @@ spins.""" self.recording.set(["testrunner", "startup"]) self.logger = structuredlog.StructuredLogger(self.suite_name) - with self.browser_cls(self.logger, remote_queue=self.command_queue, - **self.browser_kwargs) as browser: - self.browser = BrowserManager(self.logger, - browser, - self.command_queue, - no_timeout=self.debug_info is not None) - dispatch = { - RunnerManagerState.before_init: self.start_init, - RunnerManagerState.initializing: self.init, - RunnerManagerState.running: self.run_test, - RunnerManagerState.restarting: self.restart_runner, - } + dispatch = { + RunnerManagerState.before_init: self.start_init, + RunnerManagerState.initializing: self.init, + RunnerManagerState.running: self.run_test, + RunnerManagerState.restarting: self.restart_runner, + } - self.state = RunnerManagerState.before_init() - end_states = (RunnerManagerState.stop, - RunnerManagerState.error) + self.state = RunnerManagerState.before_init() + end_states = (RunnerManagerState.stop, + RunnerManagerState.error) - try: - while not isinstance(self.state, end_states): - f = dispatch.get(self.state.__class__) - while f: - self.logger.debug("Dispatch %s" % f.__name__) - if self.should_stop(): - return - new_state = f() - if new_state is None: - break - self.state = new_state - self.logger.debug("new state: %s" % self.state.__class__.__name__) - if isinstance(self.state, end_states): - return - f = dispatch.get(self.state.__class__) - - new_state = None - while new_state is None: - new_state = self.wait_event() - if self.should_stop(): - return + try: + while not isinstance(self.state, end_states): + f = dispatch.get(self.state.__class__) + while f: + self.logger.debug(f"Dispatch {f.__name__}") + if self.should_stop(): + return + new_state = f() + if new_state is None: + break self.state = new_state - self.logger.debug("new state: %s" % self.state.__class__.__name__) - except Exception: - self.logger.error(traceback.format_exc()) - raise - finally: - self.logger.debug("TestRunnerManager main loop terminating, starting cleanup") - force_stop = not isinstance(self.state, RunnerManagerState.stop) or self.state.force_stop - self.stop_runner(force=force_stop) - self.teardown() + self.logger.debug(f"new state: {self.state.__class__.__name__}") + if isinstance(self.state, end_states): + return + f = dispatch.get(self.state.__class__) + + new_state = None + while new_state is None: + new_state = self.wait_event() + if self.should_stop(): + return + self.state = new_state + self.logger.debug(f"new state: {self.state.__class__.__name__}") + except Exception: + self.logger.error(traceback.format_exc()) + raise + finally: + self.logger.debug("TestRunnerManager main loop terminating, starting cleanup") + force_stop = (not isinstance(self.state, RunnerManagerState.stop) or + self.state.force_stop) + self.stop_runner(force=force_stop) + self.teardown() + if self.browser is not None: + assert self.browser.browser is not None + self.browser.browser.cleanup() self.logger.debug("TestRunnerManager main loop terminated") def wait_event(self): @@ -422,7 +434,8 @@ self.logger.debug("Got command: %r" % command) except OSError: self.logger.error("Got IOError from poll") - return RunnerManagerState.restarting(self.state.test, + return RunnerManagerState.restarting(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata, False) @@ -450,7 +463,8 @@ self.logger.critical("Last test did not complete") return RunnerManagerState.error() self.logger.warning("More tests found, but runner process died, restarting") - return RunnerManagerState.restarting(self.state.test, + return RunnerManagerState.restarting(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata, False) @@ -467,12 +481,12 @@ return self.child_stop_flag.is_set() or self.parent_stop_flag.is_set() def start_init(self): - test, test_group, group_metadata = self.get_next_test() + test_type, test, test_group, group_metadata = self.get_next_test() self.recording.set(["testrunner", "init"]) if test is None: return RunnerManagerState.stop(True) else: - return RunnerManagerState.initializing(test, test_group, group_metadata, 0) + return RunnerManagerState.initializing(test_type, test, test_group, group_metadata, 0) def init(self): assert isinstance(self.state, RunnerManagerState.initializing) @@ -480,19 +494,33 @@ self.logger.critical("Max restarts exceeded") return RunnerManagerState.error() + if self.state.test_type != self.test_type: + if self.browser is not None: + assert self.browser.browser is not None + self.browser.browser.cleanup() + impl = self.test_implementation_by_type[self.state.test_type] + browser = impl.browser_cls(self.logger, remote_queue=self.command_queue, + **impl.browser_kwargs) + browser.setup() + self.browser = BrowserManager(self.logger, + browser, + self.command_queue, + no_timeout=self.debug_info is not None) + self.test_type = self.state.test_type + + assert self.browser is not None self.browser.update_settings(self.state.test) result = self.browser.init(self.state.group_metadata) if result is Stop: return RunnerManagerState.error() elif not result: - return RunnerManagerState.initializing(self.state.test, + return RunnerManagerState.initializing(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata, self.state.failure_count + 1) else: - self.executor_kwargs["group_metadata"] = self.state.group_metadata - self.executor_kwargs["browser_settings"] = self.browser.browser_settings self.start_test_runner() def start_test_runner(self): @@ -503,6 +531,11 @@ assert self.command_queue is not None assert self.remote_queue is not None self.logger.info("Starting runner") + impl = self.test_implementation_by_type[self.state.test_type] + self.executor_cls = impl.executor_cls + self.executor_kwargs = impl.executor_kwargs + self.executor_kwargs["group_metadata"] = self.state.group_metadata + self.executor_kwargs["browser_settings"] = self.browser.browser_settings executor_browser_cls, executor_browser_kwargs = self.browser.browser.executor_browser() args = (self.remote_queue, @@ -527,7 +560,8 @@ def init_succeeded(self): assert isinstance(self.state, RunnerManagerState.initializing) self.browser.after_init() - return RunnerManagerState.running(self.state.test, + return RunnerManagerState.running(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata) @@ -536,22 +570,25 @@ self.browser.check_crash(None) self.browser.after_init() self.stop_runner(force=True) - return RunnerManagerState.initializing(self.state.test, + return RunnerManagerState.initializing(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata, self.state.failure_count + 1) - def get_next_test(self, test_group=None): + def get_next_test(self): + # returns test_type, test, test_group, group_metadata test = None + test_group = None while test is None: while test_group is None or len(test_group) == 0: - test_group, group_metadata = self.test_source.group() + test_group, test_type, group_metadata = self.test_source.group() if test_group is None: self.logger.info("No more tests") - return None, None, None + return None, None, None, None test = test_group.popleft() self.run_count = 0 - return test, test_group, group_metadata + return test_type, test, test_group, group_metadata def run_test(self): assert isinstance(self.state, RunnerManagerState.running) @@ -559,7 +596,8 @@ if self.browser.update_settings(self.state.test): self.logger.info("Restarting browser for new test environment") - return RunnerManagerState.restarting(self.state.test, + return RunnerManagerState.restarting(self.state.test_type, + self.state.test, self.state.test_group, self.state.group_metadata, False) @@ -718,26 +756,34 @@ # that as long as we've done at least the automatic run count in total we can # continue with the next test. if not force_rerun and self.run_count >= self.rerun: - test, test_group, group_metadata = self.get_next_test() + test_type, test, test_group, group_metadata = self.get_next_test() if test is None: return RunnerManagerState.stop(force_stop) - if self.restart_on_new_group and test_group is not self.state.test_group: + if test_type != self.state.test_type: + self.logger.info(f"Restarting browser for new test type:{test_type}") + restart = True + elif self.restart_on_new_group and test_group is not self.state.test_group: self.logger.info("Restarting browser for new test group") restart = True else: + test_type = self.state.test_type test_group = self.state.test_group group_metadata = self.state.group_metadata if restart: - return RunnerManagerState.restarting(test, test_group, group_metadata, force_stop) + return RunnerManagerState.restarting( + test_type, test, test_group, group_metadata, force_stop) else: - return RunnerManagerState.running(test, test_group, group_metadata) + return RunnerManagerState.running( + test_type, test, test_group, group_metadata) def restart_runner(self): """Stop and restart the TestRunner""" assert isinstance(self.state, RunnerManagerState.restarting) self.stop_runner(force=self.state.force_stop) - return RunnerManagerState.initializing(self.state.test, self.state.test_group, self.state.group_metadata, 0) + return RunnerManagerState.initializing( + self.state.test_type, self.state.test, + self.state.test_group, self.state.group_metadata, 0) def log(self, data): self.logger.log_raw(data) @@ -854,8 +900,7 @@ class ManagerGroup: """Main thread object that owns all the TestRunnerManager threads.""" def __init__(self, suite_name, size, test_source_cls, test_source_kwargs, - browser_cls, browser_kwargs, - executor_cls, executor_kwargs, + test_implementation_by_type, rerun=1, pause_after_test=False, pause_on_unexpected=False, @@ -868,10 +913,7 @@ self.size = size self.test_source_cls = test_source_cls self.test_source_kwargs = test_source_kwargs - self.browser_cls = browser_cls - self.browser_kwargs = browser_kwargs - self.executor_cls = executor_cls - self.executor_kwargs = executor_kwargs + self.test_implementation_by_type = test_implementation_by_type self.pause_after_test = pause_after_test self.pause_on_unexpected = pause_on_unexpected self.restart_on_unexpected = restart_on_unexpected @@ -894,25 +936,18 @@ def __exit__(self, exc_type, exc_val, exc_tb): self.stop() - def run(self, test_type, tests): + def run(self, tests): """Start all managers in the group""" self.logger.debug("Using %i processes" % self.size) - if not tests: - self.logger.info("No %s tests to run" % test_type) - return test_queue = make_test_queue(tests, self.test_source_cls, **self.test_source_kwargs) for idx in range(self.size): manager = TestRunnerManager(self.suite_name, idx, - test_type, test_queue, self.test_source_cls, - self.browser_cls, - self.browser_kwargs, - self.executor_cls, - self.executor_kwargs, + self.test_implementation_by_type, self.stop_flag, self.rerun, self.pause_after_test,
diff --git a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/wptrunner.py b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/wptrunner.py index 207d732..e879925 100644 --- a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/wptrunner.py +++ b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/wptrunner.py
@@ -3,6 +3,7 @@ import json import os import sys +from collections import defaultdict from datetime import datetime, timedelta import wptserve @@ -18,7 +19,7 @@ from . import wpttest from mozlog import capture, handlers from .font import FontInstaller -from .testrunner import ManagerGroup +from .testrunner import ManagerGroup, TestImplementation here = os.path.dirname(__file__) @@ -158,13 +159,13 @@ recording, test_environment, product, run_test_kwargs): """Runs the entire test suite. This is called for each repeat or retry run requested.""" - tests = [] + tests_by_type = defaultdict(list) for test_type in test_loader.test_types: - tests.extend(test_loader.tests[test_type]) + tests_by_type[test_type].extend(test_loader.tests[test_type]) try: test_groups = test_source_cls.tests_by_group( - tests, **test_source_kwargs) + tests_by_type, **test_source_kwargs) except Exception: logger.critical("Loading tests failed") return False @@ -174,14 +175,23 @@ test_groups[test_type] = [test for test in tests if test in test_status.unexpected_tests] - unexpected_tests = set() logger.suite_start(test_groups, name='web-platform-test', run_info=run_info, extra={"run_by_dir": run_test_kwargs["run_by_dir"]}) - for test_type in sorted(run_test_kwargs["test_types"]): - logger.info(f"Running {test_type} tests") + test_implementation_by_type = {} + + for test_type in run_test_kwargs["test_types"]: + executor_cls = product.executor_classes.get(test_type) + if executor_cls is None: + logger.warning(f"Unsupported test type {test_type} for product {product.name}") + continue + executor_kwargs = product.get_executor_kwargs(logger, + test_type, + test_environment, + run_info, + **run_test_kwargs) browser_cls = product.get_browser_cls(test_type) browser_kwargs = product.get_browser_kwargs(logger, test_type, @@ -189,17 +199,14 @@ config=test_environment.config, num_test_groups=len(test_groups), **run_test_kwargs) + test_implementation_by_type[test_type] = TestImplementation(executor_cls, + executor_kwargs, + browser_cls, + browser_kwargs) - executor_cls = product.executor_classes.get(test_type) - executor_kwargs = product.get_executor_kwargs(logger, - test_type, - test_environment, - run_info, - **run_test_kwargs) - - if executor_cls is None: - logger.error(f"Unsupported test type {test_type} for product {product.name}") - continue + tests_to_run = {} + for test_type, test_implementation in test_implementation_by_type.items(): + executor_cls = test_implementation.executor_cls for test in test_loader.disabled_tests[test_type]: logger.test_start(test.id) @@ -207,53 +214,50 @@ test_status.skipped += 1 if test_type == "testharness": - tests_to_run = [] - for test in test_loader.tests["testharness"]: + tests_to_run[test_type] = [] + for test in test_loader.tests[test_type]: if ((test.testdriver and not executor_cls.supports_testdriver) or (test.jsshell and not executor_cls.supports_jsshell)): logger.test_start(test.id) logger.test_end(test.id, status="SKIP") test_status.skipped += 1 else: - tests_to_run.append(test) + tests_to_run[test_type].append(test) else: - tests_to_run = test_loader.tests[test_type] - if test_status.retries_remaining: - tests_to_run = [test for test in tests_to_run - if test.id in test_status.unexpected_tests] + tests_to_run[test_type] = test_loader.tests[test_type] - recording.pause() - with ManagerGroup("web-platform-tests", - run_test_kwargs["processes"], - test_source_cls, - test_source_kwargs, - browser_cls, - browser_kwargs, - executor_cls, - executor_kwargs, - run_test_kwargs["rerun"], - run_test_kwargs["pause_after_test"], - run_test_kwargs["pause_on_unexpected"], - run_test_kwargs["restart_on_unexpected"], - run_test_kwargs["debug_info"], - not run_test_kwargs["no_capture_stdio"], - run_test_kwargs["restart_on_new_group"], - recording=recording) as manager_group: - try: - manager_group.run(test_type, tests_to_run) - except KeyboardInterrupt: - logger.critical("Main thread got signal") - manager_group.stop() - raise - test_status.total_tests += manager_group.test_count() - test_status.unexpected += manager_group.unexpected_count() - test_status.unexpected_pass += manager_group.unexpected_pass_count() - unexpected_tests.update(manager_group.unexpected_tests()) + if test_status.retries_remaining: + tests_to_run[test_type] = [test for test in tests_to_run[test_type] + if test.id in test_status.unexpected_tests] + + recording.pause() + with ManagerGroup("web-platform-tests", + run_test_kwargs["processes"], + test_source_cls, + test_source_kwargs, + test_implementation_by_type, + run_test_kwargs["rerun"], + run_test_kwargs["pause_after_test"], + run_test_kwargs["pause_on_unexpected"], + run_test_kwargs["restart_on_unexpected"], + run_test_kwargs["debug_info"], + not run_test_kwargs["no_capture_stdio"], + run_test_kwargs["restart_on_new_group"], + recording=recording) as manager_group: + try: + manager_group.run(tests_to_run) + except KeyboardInterrupt: + logger.critical("Main thread got signal") + manager_group.stop() + raise + test_status.total_tests += manager_group.test_count() + test_status.unexpected += manager_group.unexpected_count() + test_status.unexpected_pass += manager_group.unexpected_pass_count() if test_status.repeated_runs == 1: - test_status.unexpected_tests = unexpected_tests + test_status.unexpected_tests = manager_group.unexpected_tests() else: - test_status.unexpected_tests &= unexpected_tests + test_status.unexpected_tests &= manager_group.unexpected_tests() return True
diff --git a/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.cpp b/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.cpp index 87db6b18..ef7d9166 100644 --- a/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.cpp +++ b/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.cpp
@@ -40,7 +40,7 @@ } // namespace CheckFinalizerVisitor::CheckFinalizerVisitor(RecordCache* cache) - : blacklist_context_(false), + : blocklist_context_(false), cache_(cache) { } @@ -50,7 +50,7 @@ bool CheckFinalizerVisitor::WalkUpFromCXXOperatorCallExpr( CXXOperatorCallExpr* expr) { - // Only continue the walk-up if the operator is a blacklisted one. + // Only continue the walk-up if the operator is a blocklisted one. switch (expr->getOperator()) { case OO_Arrow: case OO_Subscript: @@ -62,12 +62,12 @@ } bool CheckFinalizerVisitor::WalkUpFromCallExpr(CallExpr* expr) { - // We consider all non-operator calls to be blacklisted contexts. - bool prev_blacklist_context = blacklist_context_; - blacklist_context_ = true; + // We consider all non-operator calls to be blocklisted contexts. + bool prev_blocklist_context = blocklist_context_; + blocklist_context_ = true; for (size_t i = 0; i < expr->getNumArgs(); ++i) this->TraverseStmt(expr->getArg(i)); - blacklist_context_ = prev_blacklist_context; + blocklist_context_ = prev_blocklist_context; return true; } @@ -87,7 +87,7 @@ if (seen_members_.find(member) != seen_members_.end()) return true; - if (blacklist_context_ && + if (blocklist_context_ && MightBeCollected(&it->second)) { finalized_fields_.push_back( Error(member, &it->second));
diff --git a/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.h b/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.h index 1672be4..5f65901f 100644 --- a/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.h +++ b/tools/clang/blink_gc_plugin/CheckFinalizerVisitor.h
@@ -44,7 +44,7 @@ private: bool MightBeCollected(FieldPoint* point); - bool blacklist_context_; + bool blocklist_context_; Errors finalized_fields_; std::set<clang::MemberExpr*> seen_members_; RecordCache* cache_;
diff --git a/tools/clang/plugins/CheckIPCVisitor.cpp b/tools/clang/plugins/CheckIPCVisitor.cpp index 463c97c..8ce74ffe 100644 --- a/tools/clang/plugins/CheckIPCVisitor.cpp +++ b/tools/clang/plugins/CheckIPCVisitor.cpp
@@ -11,7 +11,7 @@ namespace { const char kWriteParamBadType[] = - "[chromium-ipc] IPC::WriteParam() is called on blacklisted type '%0'%1."; + "[chromium-ipc] IPC::WriteParam() is called on blocklisted type '%0'%1."; const char kTupleBadType[] = "[chromium-ipc] IPC tuple references banned type '%0'%1."; @@ -36,7 +36,7 @@ note_see_here_ = diagnostics.getCustomDiagID( DiagnosticsEngine::Note, kNoteSeeHere); - blacklisted_typedefs_ = llvm::StringSet<>({ + blocklisted_typedefs_ = llvm::StringSet<>({ "intmax_t", "uintmax_t", "intptr_t", @@ -172,11 +172,11 @@ } bool CheckIPCVisitor::IsBlacklistedTypedef(const TypedefNameDecl* tdef) const { - return blacklisted_typedefs_.find(tdef->getName()) != - blacklisted_typedefs_.end(); + return blocklisted_typedefs_.find(tdef->getName()) != + blocklisted_typedefs_.end(); } -// Checks that integer type is allowed (not blacklisted). +// Checks that integer type is allowed (not blocklisted). bool CheckIPCVisitor::CheckIntegerType(QualType type, CheckDetails* details) const { bool seen_typedef = false; @@ -203,7 +203,7 @@ return seen_typedef || !IsBlacklistedType(type); } -// Checks that |type| is allowed (not blacklisted), recursively visiting +// Checks that |type| is allowed (not blocklisted), recursively visiting // template specializations. bool CheckIPCVisitor::CheckType(QualType type, CheckDetails* details) const { if (type->isReferenceType()) {
diff --git a/tools/clang/plugins/CheckIPCVisitor.h b/tools/clang/plugins/CheckIPCVisitor.h index 04072e6..7a69ccc 100644 --- a/tools/clang/plugins/CheckIPCVisitor.h +++ b/tools/clang/plugins/CheckIPCVisitor.h
@@ -9,15 +9,15 @@ // typedefs, because their definitions rely on the preprocessor. For // example uintptr_t is either unsigned int or unsigned long. // -// So we're not trying to be accurate, and just blacklisting some types +// So we're not trying to be accurate, and just blocklisting some types // that are known to be unstable: // 1. Types: long / unsigned long (but not typedefs to) // 2. Typedefs: intmax_t, uintmax_t, intptr_t, uintptr_t, wint_t, // size_t, rsize_t, ssize_t, ptrdiff_t, dev_t, off_t, clock_t, // time_t, suseconds_t (including typedefs to) // -// Additionally, templates referencing blacklisted types (e.g. vector<long>) -// are also blacklisted. +// Additionally, templates referencing blocklisted types (e.g. vector<long>) +// are also blocklisted. // // Blacklisted types are checked in: // 1. IPC::WriteParam() calls @@ -91,7 +91,7 @@ std::vector<const clang::Decl*> decl_stack_; - llvm::StringSet<> blacklisted_typedefs_; + llvm::StringSet<> blocklisted_typedefs_; }; } // namespace chrome_checker
diff --git a/tools/clang/plugins/ChromeClassTester.cpp b/tools/clang/plugins/ChromeClassTester.cpp index 603e2c8b..d165d3a 100644 --- a/tools/clang/plugins/ChromeClassTester.cpp +++ b/tools/clang/plugins/ChromeClassTester.cpp
@@ -55,7 +55,7 @@ return; if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) { - // We sadly need to maintain a blacklist of types that violate these + // We sadly need to maintain a blocklist of types that violate these // rules, but do so for good reason or due to limitations of this // checker (i.e., we don't handle extern templates very well). std::string base_name = record->getNameAsString();
diff --git a/tools/clang/plugins/FindBadConstructsConsumer.cpp b/tools/clang/plugins/FindBadConstructsConsumer.cpp index 3386c131..5a5cf5d 100644 --- a/tools/clang/plugins/FindBadConstructsConsumer.cpp +++ b/tools/clang/plugins/FindBadConstructsConsumer.cpp
@@ -671,7 +671,7 @@ SourceLocation loc = cs->getLBracLoc(); // CR_BEGIN_MSG_MAP_EX and BEGIN_SAFE_MSG_MAP_EX try to be compatible // to BEGIN_MSG_MAP(_EX). So even though they are in chrome code, - // we can't easily fix them, so explicitly whitelist them here. + // we can't easily fix them, so explicitly allowlist them here. bool emit = true; if (loc.isMacroID()) { SourceManager& manager = instance().getSourceManager();
diff --git a/tools/clang/plugins/tests/ipc.txt b/tools/clang/plugins/tests/ipc.txt index bf845ea..67748dbe 100644 --- a/tools/clang/plugins/tests/ipc.txt +++ b/tools/clang/plugins/tests/ipc.txt
@@ -1,19 +1,19 @@ -ipc.cpp:83:26: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t'. +ipc.cpp:83:26: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t'. WriteParam(pickle, p.size); // ERROR ^ -ipc.cpp:107:24: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:107:24: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. WriteParam(pickle, static_cast<long>(container.value)); // ERROR ^ -ipc.cpp:135:29: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t'. +ipc.cpp:135:29: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t'. IPC::WriteParam(pickle, size_t(0)); // ERROR ^ -ipc.cpp:145:29: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'time_t'. +ipc.cpp:145:29: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'time_t'. IPC::WriteParam(pickle, time_t(0)); // ERROR ^ -ipc.cpp:156:27: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:156:27: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. IPC::WriteParam(pickle, long(0)); // ERROR ^ -ipc.cpp:162:29: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'clock_t'. +ipc.cpp:162:29: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'clock_t'. IPC::WriteParam(pickle, clock_t(0)); // ERROR ^ ipc.cpp:194:1: error: [chromium-ipc] IPC tuple references banned type 'size_t'. @@ -65,103 +65,103 @@ ipc.cpp:186:5: note: expanded from macro 'IPC_MESSAGE_DECL' using InTuple = in_tuple; \ ^ -ipc.cpp:216:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:216:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. CALL_WRITEPARAM(long) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:217:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'unsigned long'. +ipc.cpp:217:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'unsigned long'. CALL_WRITEPARAM(unsigned long) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:218:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'intmax_t'. +ipc.cpp:218:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'intmax_t'. CALL_WRITEPARAM(intmax_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:219:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'uintmax_t'. +ipc.cpp:219:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'uintmax_t'. CALL_WRITEPARAM(uintmax_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:220:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'intptr_t'. +ipc.cpp:220:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'intptr_t'. CALL_WRITEPARAM(intptr_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:221:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'uintptr_t'. +ipc.cpp:221:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'uintptr_t'. CALL_WRITEPARAM(uintptr_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:222:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'wint_t'. +ipc.cpp:222:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'wint_t'. CALL_WRITEPARAM(wint_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:223:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t'. +ipc.cpp:223:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t'. CALL_WRITEPARAM(size_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:224:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'rsize_t'. +ipc.cpp:224:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'rsize_t'. CALL_WRITEPARAM(rsize_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:225:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'ssize_t'. +ipc.cpp:225:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'ssize_t'. CALL_WRITEPARAM(ssize_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:226:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'ptrdiff_t'. +ipc.cpp:226:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'ptrdiff_t'. CALL_WRITEPARAM(ptrdiff_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:227:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'dev_t'. +ipc.cpp:227:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'dev_t'. CALL_WRITEPARAM(dev_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:228:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'off_t'. +ipc.cpp:228:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'off_t'. CALL_WRITEPARAM(off_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:229:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'clock_t'. +ipc.cpp:229:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'clock_t'. CALL_WRITEPARAM(clock_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:230:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'time_t'. +ipc.cpp:230:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'time_t'. CALL_WRITEPARAM(time_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:231:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'suseconds_t'. +ipc.cpp:231:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'suseconds_t'. CALL_WRITEPARAM(suseconds_t) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:235:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t' via 'my_size'. +ipc.cpp:235:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t' via 'my_size'. CALL_WRITEPARAM(my_size) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' @@ -170,7 +170,7 @@ ipc.cpp:234:18: note: see here typedef size_t my_size; ^ -ipc.cpp:249:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t' via 'my_size'. +ipc.cpp:249:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t' via 'my_size'. IPC::WriteParam(nullptr, p); // ERROR ^ ipc.cpp:246:32: note: see here @@ -179,43 +179,43 @@ ipc.cpp:245:20: note: see here typedef size_t my_size_base; ^ -ipc.cpp:253:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long' via 'std::vector<long>'. +ipc.cpp:253:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long' via 'std::vector<long>'. CALL_WRITEPARAM(std::vector<long>) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:254:3: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t' via 'std::vector<size_t>'. +ipc.cpp:254:3: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t' via 'std::vector<size_t>'. CALL_WRITEPARAM(std::vector<size_t>) // ERROR ^ ipc.cpp:212:32: note: expanded from macro 'CALL_WRITEPARAM' IPC::WriteParam(nullptr, p); \ ^ -ipc.cpp:324:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:324:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. IPC::WriteParam(nullptr, p.get<long>()); // ERROR ^ -ipc.cpp:325:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:325:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. IPC::WriteParam(nullptr, p.get_long()); // ERROR ^ -ipc.cpp:326:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'long'. +ipc.cpp:326:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'long'. IPC::WriteParam(nullptr, p.long_data); // ERROR ^ -ipc.cpp:331:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t'. +ipc.cpp:331:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t'. IPC::WriteParam(nullptr, p.get_size()); // ERROR ^ -ipc.cpp:332:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t'. +ipc.cpp:332:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t'. IPC::WriteParam(nullptr, p.size_data); // ERROR ^ -ipc.cpp:336:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'unsigned long'. +ipc.cpp:336:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'unsigned long'. IPC::WriteParam(nullptr, p.get<uint64_t>()); // ERROR ^ -ipc.cpp:341:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'unsigned long' via 'struct std::vector<unsigned long>'. +ipc.cpp:341:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'unsigned long' via 'struct std::vector<unsigned long>'. IPC::WriteParam(nullptr, p.get<std::vector<uint64_t>>()); // ERROR ^ -ipc.cpp:348:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t' via 'std::vector<size_t>'. +ipc.cpp:348:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t' via 'std::vector<size_t>'. IPC::WriteParam(nullptr, p.get_sizes()); // ERROR ^ -ipc.cpp:349:30: error: [chromium-ipc] IPC::WriteParam() is called on blacklisted type 'size_t' via 'std::vector<size_t>'. +ipc.cpp:349:30: error: [chromium-ipc] IPC::WriteParam() is called on blocklisted type 'size_t' via 'std::vector<size_t>'. IPC::WriteParam(nullptr, p.sizes_data); // ERROR ^ 40 errors generated.
diff --git a/tools/clang/rewrite_to_chrome_style/RewriteToChromeStyle.cpp b/tools/clang/rewrite_to_chrome_style/RewriteToChromeStyle.cpp index 4cec6e4..1a0f710f 100644 --- a/tools/clang/rewrite_to_chrome_style/RewriteToChromeStyle.cpp +++ b/tools/clang/rewrite_to_chrome_style/RewriteToChromeStyle.cpp
@@ -215,7 +215,7 @@ } } - // Stores methods to blacklist in a map: + // Stores methods to blocklist in a map: // method name -> class name -> set of all allowed numbers of arguments. llvm::StringMap<llvm::StringSet<>> method_to_classes_; }; @@ -299,7 +299,7 @@ // other it will break what this class overrides, disconnecting it from the // one we did not rename which creates a behaviour change. So assert and // demand the user to fix the code first (or add the method to our - // blacklist T_T). + // blocklist T_T). if (override_matches && override_not_matches) { // blink::InternalSettings::trace method overrides // 1) blink::InternalSettingsGenerated::trace
diff --git a/tools/clang/rewrite_to_chrome_style/tests/methods-expected.cc b/tools/clang/rewrite_to_chrome_style/tests/methods-expected.cc index e6bb412..29adecb 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/methods-expected.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/methods-expected.cc
@@ -235,10 +235,10 @@ } // namespace get_prefix_vs_inheritance -namespace blacklisting_of_method_and_function_names { +namespace blocklisting_of_method_and_function_names { class Foo { - // Expecting |swap| method to be renamed to |Swap| - we blacklist renaming of + // Expecting |swap| method to be renamed to |Swap| - we blocklist renaming of // |swap| *function*, because it needs to have the same casing as std::swap, // so that ADL can kick-in and pull it from another namespace depending on the // bargument. We have a choice to rename or not rename |swap| *methods* - we @@ -266,7 +266,7 @@ void Begin(int x) {} void swap(Foo& x, Foo& y) {} -} // blacklisting_of_method_and_function_names +} // blocklisting_of_method_and_function_names } // namespace blink
diff --git a/tools/clang/rewrite_to_chrome_style/tests/methods-original.cc b/tools/clang/rewrite_to_chrome_style/tests/methods-original.cc index d8798480..a8e41f1b 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/methods-original.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/methods-original.cc
@@ -239,10 +239,10 @@ } // namespace get_prefix_vs_inheritance -namespace blacklisting_of_method_and_function_names { +namespace blocklisting_of_method_and_function_names { class Foo { - // Expecting |swap| method to be renamed to |Swap| - we blacklist renaming of + // Expecting |swap| method to be renamed to |Swap| - we blocklist renaming of // |swap| *function*, because it needs to have the same casing as std::swap, // so that ADL can kick-in and pull it from another namespace depending on the // bargument. We have a choice to rename or not rename |swap| *methods* - we @@ -270,7 +270,7 @@ void begin(int x) {} void swap(Foo& x, Foo& y) {} -} // blacklisting_of_method_and_function_names +} // blocklisting_of_method_and_function_names } // namespace blink
diff --git a/tools/clang/rewrite_to_chrome_style/tests/namespaces-expected.cc b/tools/clang/rewrite_to_chrome_style/tests/namespaces-expected.cc index 1452872..e26b98d 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/namespaces-expected.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/namespaces-expected.cc
@@ -12,7 +12,7 @@ void Foo(); } // namespace nested -// blink::protocol namespace is blacklisted. +// blink::protocol namespace is blocklisted. namespace protocol { void foo(); } // namespace protocol
diff --git a/tools/clang/rewrite_to_chrome_style/tests/namespaces-original.cc b/tools/clang/rewrite_to_chrome_style/tests/namespaces-original.cc index b89c971..f26e0c3 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/namespaces-original.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/namespaces-original.cc
@@ -12,7 +12,7 @@ void foo(); } // namespace nested -// blink::protocol namespace is blacklisted. +// blink::protocol namespace is blocklisted. namespace protocol { void foo(); } // namespace protocol
diff --git a/tools/clang/rewrite_to_chrome_style/tests/template-expected.cc b/tools/clang/rewrite_to_chrome_style/tests/template-expected.cc index db98ea0..21890ba 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/template-expected.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/template-expected.cc
@@ -327,7 +327,7 @@ } // namespace cxx_dependent_scope_member_expr_testing -namespace blacklisting_of_renaming_of_begin_method { +namespace blocklisting_of_renaming_of_begin_method { template <typename T> class IntrusiveHeap { @@ -336,7 +336,7 @@ const T* begin() const { return nullptr; } }; -} // namespace blacklisting_of_renaming_of_begin_method +} // namespace blocklisting_of_renaming_of_begin_method namespace specializations {
diff --git a/tools/clang/rewrite_to_chrome_style/tests/template-original.cc b/tools/clang/rewrite_to_chrome_style/tests/template-original.cc index 0fbec663..fd85ba5d 100644 --- a/tools/clang/rewrite_to_chrome_style/tests/template-original.cc +++ b/tools/clang/rewrite_to_chrome_style/tests/template-original.cc
@@ -326,7 +326,7 @@ } // namespace cxx_dependent_scope_member_expr_testing -namespace blacklisting_of_renaming_of_begin_method { +namespace blocklisting_of_renaming_of_begin_method { template <typename T> class IntrusiveHeap { @@ -335,7 +335,7 @@ const T* begin() const { return nullptr; } }; -} // namespace blacklisting_of_renaming_of_begin_method +} // namespace blocklisting_of_renaming_of_begin_method namespace specializations {
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 87d914b..d682c0c 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -363,7 +363,6 @@ 'Linux Builder (reclient compare)': 'gpu_tests_release_bot_reclient', 'Linux CFI (reclient shadow)': 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_reclient', 'Linux ChromiumOS MSan Focal': 'chromeos_msan_focal_release_bot_reclient', - 'Linux MSan Focal': 'msan_focal_release_bot_reclient', 'Linux Viz': 'release_trybot_minimal_symbols_reclient', # TODO(crbug.com/1260232): remove this after the migration. 'Mac Builder (reclient compare)': 'gpu_tests_release_bot_minimal_symbols_reclient', @@ -442,6 +441,7 @@ 'linux-wpt-fyi-rel': 'release_trybot_minimal_symbols_reclient', 'linux-wpt-identity-fyi-rel': 'release_bot_minimal_symbols_reclient', 'linux-wpt-input-fyi-rel': 'release_bot_minimal_symbols_reclient', + 'mac-12-wpt-fyi-rel': 'release_bot_reclient', # TODO(crbug.com/1252626): remove this after the migration. 'mac-arm64-on-arm64-rel-reclient': 'mac_arm64_release_bot_reclient', 'mac-backuprefptr-x64-fyi-rel': 'release_trybot_backuprefptr_x64_reclient', @@ -620,7 +620,7 @@ 'Linux CFI': 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_reclient', 'Linux Chromium OS ASan LSan Builder': 'asan_lsan_chromeos_release_bot_dcheck_always_on_reclient', 'Linux ChromiumOS MSan Builder': 'chromeos_msan_release_bot_reclient', - 'Linux MSan Builder': 'msan_release_bot_reclient', + 'Linux MSan Builder': 'msan_focal_release_bot_reclient', 'Linux TSan Builder': 'tsan_disable_nacl_release_bot_reclient', 'Mac ASan 64 Builder': 'asan_minimal_symbols_disable_nacl_release_bot_dcheck_always_on_reclient', 'WebKit Linux ASAN': 'asan_lsan_release_bot_blink_reclient', @@ -1182,8 +1182,7 @@ # This is intentionally a release_bot and not a release_trybot; # enabling DCHECKs seems to cause flaky failures that don't show up # on the continuous builder. - 'linux_chromium_msan_focal': 'msan_focal_release_bot_reclient', - 'linux_chromium_msan_rel_ng': 'msan_release_bot_reclient', + 'linux_chromium_msan_rel_ng': 'msan_focal_release_bot_reclient', 'linux_chromium_tsan_rel_ng': 'tsan_disable_nacl_release_trybot_reclient',
diff --git a/tools/mb/mb_config_expectations/chromium.fyi.json b/tools/mb/mb_config_expectations/chromium.fyi.json index 7ec8fcf..cae130381 100644 --- a/tools/mb/mb_config_expectations/chromium.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.fyi.json
@@ -438,17 +438,6 @@ "use_remoteexec": true } }, - "Linux MSan Focal": { - "gn_args": { - "dcheck_always_on": false, - "instrumented_libraries_release": "focal", - "is_component_build": false, - "is_debug": false, - "is_msan": true, - "msan_track_origins": 2, - "use_remoteexec": true - } - }, "Linux Viz": { "gn_args": { "dcheck_always_on": true, @@ -1353,6 +1342,14 @@ "use_remoteexec": true } }, + "mac-12-wpt-fyi-rel": { + "gn_args": { + "dcheck_always_on": false, + "is_component_build": false, + "is_debug": false, + "use_remoteexec": true + } + }, "mac-arm64-on-arm64-rel-reclient": { "gn_args": { "dcheck_always_on": false,
diff --git a/tools/mb/mb_config_expectations/chromium.memory.json b/tools/mb/mb_config_expectations/chromium.memory.json index b8ad634..f026f05 100644 --- a/tools/mb/mb_config_expectations/chromium.memory.json +++ b/tools/mb/mb_config_expectations/chromium.memory.json
@@ -50,7 +50,7 @@ "Linux MSan Builder": { "gn_args": { "dcheck_always_on": false, - "instrumented_libraries_release": "xenial", + "instrumented_libraries_release": "focal", "is_component_build": false, "is_debug": false, "is_msan": true,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json index 62af472..9fbf21b0 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json
@@ -682,21 +682,10 @@ "use_remoteexec": true } }, - "linux_chromium_msan_focal": { - "gn_args": { - "dcheck_always_on": false, - "instrumented_libraries_release": "focal", - "is_component_build": false, - "is_debug": false, - "is_msan": true, - "msan_track_origins": 2, - "use_remoteexec": true - } - }, "linux_chromium_msan_rel_ng": { "gn_args": { "dcheck_always_on": false, - "instrumented_libraries_release": "xenial", + "instrumented_libraries_release": "focal", "is_component_build": false, "is_debug": false, "is_msan": true,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 4fd2587..95568f6 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -5448,6 +5448,12 @@ <int value="6" label="Write File Close Failed"/> </enum> +<enum name="AttributionNavigationType"> + <int value="0" label="Anchor"/> + <int value="1" label="window.open"/> + <int value="2" label="Context menu"/> +</enum> + <enum name="AuctionResult"> <int value="0" label="Success"/> <int value="1" label="Aborted"/> @@ -28498,6 +28504,15 @@ <int value="0" label="UNDETERMINED"/> </enum> +<enum name="DownloadAddWarningActionEventOutcome"> + <int value="0" label="NOT_ADDED_MISSING_DOWNLOAD"/> + <int value="1" label="NOT_ADDED_WARNING_SHOWN_ALREADY_LOGGED"/> + <int value="2" label="NOT_ADDED_MISSING_FIRST_WARNING"/> + <int value="3" label="NOT_ADDED_EXCEED_MAX_LENGTH"/> + <int value="4" label="ADDED_WARNING_FIRST_SHOWN"/> + <int value="5" label="ADDED_WARNING_ACTION"/> +</enum> + <enum name="DownloadARModelState"> <int value="0" label="Created"> AR model download was created but not yet started. @@ -43687,7 +43702,11 @@ <int value="1" label="Deepsleep"/> <int value="2" label="FingerDown"/> <int value="3" label="FingerUp"/> - <int value="4" label="Capture"/> + <int value="4" label="CaptureVendorFormat"> + This is the same as the default Capture mode with no capture type. + + ec::FpMode::Mode::kCapture == ec::FpMode::Mode::kCaptureVendorFormat + </int> <int value="5" label="EnrollSession"/> <int value="6" label="EnrollSessionFingerUp"/> <int value="7" label="EnrollSessionEnrollImage"/> @@ -43701,6 +43720,11 @@ ec::FpMode::Mode::kModeInvalid </int> + <int value="14" label="CaptureSimpleImage"/> + <int value="15" label="CapturePattern0"/> + <int value="16" label="CapturePattern1"/> + <int value="17" label="CaptureQualityTest"/> + <int value="18" label="CaptureResetTest"/> </enum> <enum name="FingerprintSetupScreenUserAction"> @@ -60624,6 +60648,7 @@ <int value="43995010" label="FedCmMultipleIdentityProviders:enabled"/> <int value="44088203" label="ExpensiveBackgroundTimerThrottling:enabled"/> <int value="44240181" label="SharingQRCodeGenerator:disabled"/> + <int value="45681371" label="CCTResizableSideSheet:enabled"/> <int value="46334141" label="FeatureNotificationGuideSkipCheckForLowEngagedUsers:enabled"/> <int value="48159177" label="reduced-referrer-granularity"/> @@ -60724,6 +60749,7 @@ <int value="105046382" label="ParallelDownloading:disabled"/> <int value="106744400" label="OmniboxModernizeVisualUpdate:enabled"/> <int value="106840653" label="mus"/> + <int value="107358678" label="GalleryAppPdfEditNotification:enabled"/> <int value="107900612" label="ChromeHomePersistentIph:disabled"/> <int value="108874121" label="InstanceSwitcher:disabled"/> <int value="109577361" label="ForbidSyncXHRInPageDismissal:enabled"/> @@ -63685,6 +63711,7 @@ <int value="1882177465" label="JourneysKeywordFiltering:enabled"/> <int value="1882197308" label="UseChromeOSDirectVideoDecoder:disabled"/> <int value="1883000826" label="IsolatedSandboxedIframesName:disabled"/> + <int value="1883558610" label="GalleryAppPdfEditNotification:disabled"/> <int value="1883998150" label="WebAppsCrosapi:disabled"/> <int value="1887031213" label="AutofillManualFallbackAndroid:disabled"/> <int value="1887882558" label="RTCUnifiedPlanByDefault:enabled"/> @@ -64105,6 +64132,7 @@ <int value="2129639191" label="ArcWindowPredictor:disabled"/> <int value="2129814401" label="SyncTrustedVaultPassphrasePromo:enabled"/> <int value="2129929643" label="enable-use-zoom-for-dsf"/> + <int value="2130479056" label="CCTResizableSideSheet:disabled"/> <int value="2132335798" label="EcheSWA:disabled"/> <int value="2132595171" label="OmniboxSearchEngineLogo:enabled"/> <int value="2133594095" label="CryptAuthV2DeviceActivityStatus:disabled"/> @@ -98435,6 +98463,7 @@ <int value="36" label="Deprecate Assistant Stylus"/> <int value="37" label="Eche Tray Copy Paste Not Implemented"/> <int value="38" label="Eche Tray Tablet Mode Not Supported"/> + <int value="39" label="Notification Center Tray No Notifications"/> </enum> <enum name="TokenBinding.KeyMatch">
diff --git a/tools/metrics/histograms/metadata/download/histograms.xml b/tools/metrics/histograms/metadata/download/histograms.xml index 55aae18..1a3e0f90 100644 --- a/tools/metrics/histograms/metadata/download/histograms.xml +++ b/tools/metrics/histograms/metadata/download/histograms.xml
@@ -1446,6 +1446,16 @@ <summary>Records events for local video thumbnail retrieval.</summary> </histogram> +<histogram name="Download.WarningData.AddWarningActionEventOutcome" + enum="DownloadAddWarningActionEventOutcome" expires_after="2023-05-22"> + <owner>xinghuilu@chromium.org</owner> + <owner>chrome-counter-abuse-alerts@google.com</owner> + <summary> + Records whether a download warning action event was sent, or if not, then + why not. Logged each time an action is taken on the download warning. + </summary> +</histogram> + <histogram name="Download.WinFileMoveError" enum="WinIFileOperationError" expires_after="2023-10-12"> <owner>drubery@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/enterprise/histograms.xml b/tools/metrics/histograms/metadata/enterprise/histograms.xml index 82fc613..da74913 100644 --- a/tools/metrics/histograms/metadata/enterprise/histograms.xml +++ b/tools/metrics/histograms/metadata/enterprise/histograms.xml
@@ -289,25 +289,31 @@ </histogram> <histogram base="true" name="Enterprise.BrowserSigninIOS.SignedOutByPolicy" - enum="BooleanHit" expires_after="2021-06-30"> + enum="BooleanHit" expires_after="2023-06-30"> <owner>gujen@google.com</owner> <owner>goanuj@google.com</owner> <summary> Recorded when a signed-in user is automatically signed out of the browser due to the BrowserSignin policy being set to 0 (sign-in disabled) by their organization. The sample is always recorded as true. + + Warning: This histogram was expired from 2021-06-30 to 2022-11-30; data may + be missing. </summary> </histogram> <histogram base="true" name="Enterprise.BrowserSigninIOS.SignInInterruptedByPolicy" - enum="BooleanHit" expires_after="2021-06-30"> + enum="BooleanHit" expires_after="2023-06-30"> <owner>gujen@google.com</owner> <owner>goanuj@google.com</owner> <summary> Recorded when a user is in the process of signing in to the browser, but is interrupted due to the BrowserSignin policy being set to 0 (sign-in disabled) by their organization. The sample is always recorded as true. + + Warning: This histogram was expired from 2021-06-30 to 2022-11-30; data may + be missing. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/extensions/histograms.xml b/tools/metrics/histograms/metadata/extensions/histograms.xml index 9fa5042b..a65cc07 100644 --- a/tools/metrics/histograms/metadata/extensions/histograms.xml +++ b/tools/metrics/histograms/metadata/extensions/histograms.xml
@@ -358,6 +358,16 @@ </summary> </histogram> +<histogram name="Extensions.ContentScripts.ContentScriptLength" units="KB" + expires_after="2023-11-22"> + <owner>kelvinjiang@chromium.org</owner> + <owner>extensions-core@chromium.org</owner> + <summary> + The size, in kb, of a content script that is loaded successfully from a + file. Recorded when the content of a user script object is set. + </summary> +</histogram> + <histogram name="Extensions.ContentVerification.ComputedHashesInitTime" units="ms" expires_after="2020-11-30"> <owner>lazyboy@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/media/histograms.xml b/tools/metrics/histograms/metadata/media/histograms.xml index d60a4785..82086ec 100644 --- a/tools/metrics/histograms/metadata/media/histograms.xml +++ b/tools/metrics/histograms/metadata/media/histograms.xml
@@ -6056,7 +6056,7 @@ </histogram> <histogram name="MediaRouter.CastStreaming.Start.Failure.AccessCodeManualEntry" - enum="MirroringServiceErrorType" expires_after="2023-01-01"> + enum="MirroringServiceErrorType" expires_after="2023-07-01"> <owner>bzielinski@google.com</owner> <owner>cros-edu-eng@google.com</owner> <summary> @@ -6067,7 +6067,7 @@ <histogram name="MediaRouter.CastStreaming.Start.Failure.AccessCodeRememberedDevice" - enum="MirroringServiceErrorType" expires_after="2023-01-01"> + enum="MirroringServiceErrorType" expires_after="2023-07-01"> <owner>bzielinski@google.com</owner> <owner>cros-edu-eng@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index 4a800933..e7d09326 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -220,6 +220,17 @@ </summary> </histogram> +<histogram name="AccessCodeCast.Discovery.DeviceDurationOnRoute" + units="seconds" expires_after="2023-03-12"> + <owner>bzielinski@google.com</owner> + <owner>cros-edu-eng@google.com</owner> + <summary> + The duration in seconds an access code device will stay in the list of cast + devices. Recorded on successful creation of a cast session to an access code + device. Logged only on desktop platforms. + </summary> +</histogram> + <histogram name="AccessCodeCast.Discovery.RememberedDevicesCount" units="cast devices" expires_after="2023-05-07"> <owner>bzielinski@google.com</owner> @@ -3326,6 +3337,21 @@ </summary> </histogram> +<histogram name="Conversion.SourceRegistration.NavigationType.{RequestType}" + enum="AttributionNavigationType" expires_after="M117"> + <owner>csharrison@chromium.org</owner> + <owner>apaseltiner@chromium.org</owner> + <owner>measurement-api-dev+metrics@google.com</owner> + <summary> + For any successfully registered {RequestType} navigation sources, records + the API surface that initiated the navigation. + </summary> + <token key="RequestType"> + <variant name="Background" summary="background"/> + <variant name="Foreground" summary="foreground"/> + </token> +</histogram> + <histogram name="Conversions.AggregatableKeysPerSource" units="keys" expires_after="M117"> <owner>linnan@chromium.org</owner> @@ -7874,15 +7900,6 @@ </summary> </histogram> -<histogram name="Launch.IntentFlags" enum="LaunchIntentFlags" - expires_after="2020-10-04"> - <owner>dfalcantara@chromium.org</owner> - <summary> - Records flags (and combinations of flags) that were attached to the Intent - that started ChromeLauncherActivity. - </summary> -</histogram> - <histogram name="Launch.Mode2" enum="LaunchMode" expires_after="never"> <!-- expires-never: used from time to time on Windows to measure the value of the various Chrome shortcuts (davidbienvenu@) -->
diff --git a/tools/metrics/histograms/metadata/safe_browsing/histograms.xml b/tools/metrics/histograms/metadata/safe_browsing/histograms.xml index 4b0105a9..39eab10 100644 --- a/tools/metrics/histograms/metadata/safe_browsing/histograms.xml +++ b/tools/metrics/histograms/metadata/safe_browsing/histograms.xml
@@ -344,6 +344,18 @@ </summary> </histogram> +<histogram + name="SafeBrowsing.ClientSafeBrowsingReport.DownloadWarningActionSize" + units="units" expires_after="2023-05-22"> + <owner>xinghuilu@chromium.org</owner> + <owner>chrome-counter-abuse-alerts@google.com</owner> + <summary> + Counts the length of the download_warning_actions field in a client Safe + Browsing report. Logged each time the field is populated before a report is + sent. + </summary> +</histogram> + <histogram name="SafeBrowsing.ClientSafeBrowsingReport.HasThreatDetailsForTab" enum="BooleanAvailable" expires_after="2023-04-23"> <owner>xinghuilu@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/startup/histograms.xml b/tools/metrics/histograms/metadata/startup/histograms.xml index 405e149..654cde0 100644 --- a/tools/metrics/histograms/metadata/startup/histograms.xml +++ b/tools/metrics/histograms/metadata/startup/histograms.xml
@@ -55,16 +55,6 @@ </summary> </histogram> -<histogram name="Startup.Android.ChromeTabbedTaskExistsTime" units="ms" - expires_after="2021-09-19"> - <owner>mthiesse@chromium.org</owner> - <owner>yfriedman@chromium.org</owner> - <summary> - Measures the amount of time it takes to check if a ChromeTabbedActivity task - already exists during startup. - </summary> -</histogram> - <histogram name="Startup.Android.Cold.FirstNavigationCommitOccurredPreForeground" enum="Boolean" expires_after="2023-05-14">
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index 40718c7b..d16db9d 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -2554,6 +2554,28 @@ </token> </histogram> +<histogram name="Tabs.Tasks.OrderValidOnStartup" units="boolean" + expires_after="M114"> + <owner>ckitagawa@chromium.org</owner> + <owner>fredmello@chromium.org</owner> + <summary> + [Android] boolean value indicating whether the invariant that tab groups are + contiguous holds. Recorded on cold start after all tabs are restored. + </summary> +</histogram> + +<histogram name="Tabs.Tasks.TabAddedWithValidProposedPosition" units="boolean" + expires_after="M114"> + <owner>ckitagawa@chromium.org</owner> + <owner>fredmello@chromium.org</owner> + <summary> + [Android] boolean value indicating whether a tab that was added to the + TabModel would have been added at the correct position if + TabGroupModelFilter had not interved to move it so it respected group + position. Recorded each time a tab is added to the TabModel. + </summary> +</histogram> + <histogram name="Tabs.Tasks.TabCreated.Count{TabCreatedReason}" units="tabs" expires_after="2020-06-30"> <owner>yusufo@chromium.org</owner>
diff --git a/tools/perf/core/bot_platforms.py b/tools/perf/core/bot_platforms.py index 1b12ce15..94a7c1c 100644 --- a/tools/perf/core/bot_platforms.py +++ b/tools/perf/core/bot_platforms.py
@@ -315,9 +315,14 @@ FUCHSIA_EXEC_CONFIGS = {'astro': None, 'sherlock': None, 'atlas': None} _IMAGE_PATHS = { 'astro': ('astro-release', 'smart_display_eng_arrested'), - 'atlas': ('chromebook-x64-release', 'sucrose_eng'), 'sherlock': ('sherlock-release', 'smart_display_max_eng_arrested'), } + +# Some image paths are just a product-bundle, which is not a relative path. +_PB_IMAGE_PATHS = { + 'atlas': 'workstation_eng.chromebook-x64', +} + _FUCHSIA_IMAGE_DIR = '../../third_party/fuchsia-sdk/images-internal/%s/%s' _COMMON_FUCHSIA_ARGS = ['-d', '--os-check=check'] for board, path_parts in _IMAGE_PATHS.items(): @@ -331,6 +336,16 @@ additional_flags=FUCHSIA_EXEC_ARGS[board]) ]) +for board, pb_name in _PB_IMAGE_PATHS.items(): + FUCHSIA_EXEC_ARGS[board] = _COMMON_FUCHSIA_ARGS + [ + f'--system-image-dir={pb_name}' + ] + FUCHSIA_EXEC_CONFIGS[board] = frozenset([ + _base_perftests(900, + path='bin/run_base_perftests', + additional_flags=FUCHSIA_EXEC_ARGS[board]) + ]) + _LINUX_BENCHMARK_CONFIGS = PerfSuite(OFFICIAL_BENCHMARK_CONFIGS).Remove([ 'blink_perf.display_locking', 'v8.runtime_stats.top_25',
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 5301822d..5b77e16 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,8 +5,8 @@ "full_remote_path": "perfetto-luci-artifacts/v31.0/linux-arm64/trace_processor_shell" }, "win": { - "hash": "eec291620013625a856fa2b4d0c3e359e8bacbef", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/51908f273fa158b58c6336afa93b65838c6ff3cf/trace_processor_shell.exe" + "hash": "de67970077e8d87821a5c50cc08c333075cbc1d8", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/4f6803dfe01e8e9f05957329f0475044dc658990/trace_processor_shell.exe" }, "linux_arm": { "hash": "6373f26144aad58f230d11d6a91efda5a09c9873", @@ -14,7 +14,7 @@ }, "mac": { "hash": "ad435e8dc0ca52d5f8a53d4c22e3152c9f92cea3", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/a7d3afea3356f2bce05beb6d9eca9be4402a0e8a/trace_processor_shell" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/4f6803dfe01e8e9f05957329f0475044dc658990/trace_processor_shell" }, "mac_arm64": { "hash": "5f47ee79e59d00bf3889d30ca52315522c158040", @@ -22,7 +22,7 @@ }, "linux": { "hash": "780b06e0c37caf80f458aa8b84af2eb27fd3f720", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/a7d3afea3356f2bce05beb6d9eca9be4402a0e8a/trace_processor_shell" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/4f6803dfe01e8e9f05957329f0475044dc658990/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/core/shard_maps/fuchsia-perf-atlas-fyi_map.json b/tools/perf/core/shard_maps/fuchsia-perf-atlas-fyi_map.json index e8550a3..8ff96bc2 100644 --- a/tools/perf/core/shard_maps/fuchsia-perf-atlas-fyi_map.json +++ b/tools/perf/core/shard_maps/fuchsia-perf-atlas-fyi_map.json
@@ -7,7 +7,7 @@ "--test-launcher-retry-limit=0", "-d", "--os-check=check", - "--system-image-dir=../../third_party/fuchsia-sdk/images-internal/chromebook-x64-release/sucrose_eng" + "--system-image-dir=workstation_eng.chromebook-x64" ], "path": "bin/run_base_perftests" }
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn index 54b47dd..416b489c 100644 --- a/ui/accessibility/BUILD.gn +++ b/ui/accessibility/BUILD.gn
@@ -284,6 +284,7 @@ "mojom/ax_action_data_mojom_traits_unittest.cc", "mojom/ax_event_intent_mojom_traits_unittest.cc", "mojom/ax_event_mojom_traits_unittest.cc", + "mojom/ax_mode_mojom_traits_unittest.cc", "mojom/ax_node_data_mojom_traits_unittest.cc", "mojom/ax_relative_bounds_mojom_traits_unittest.cc", "mojom/ax_tree_data_mojom_traits_unittest.cc",
diff --git a/ui/accessibility/ax_mode.h b/ui/accessibility/ax_mode.h index 0af4b7c8..83e50a7d 100644 --- a/ui/accessibility/ax_mode.h +++ b/ui/accessibility/ax_mode.h
@@ -87,7 +87,7 @@ flags_ = value ? (flags_ | flag) : (flags_ & ~flag); } - uint32_t mode() const { return flags_; } + uint32_t flags() const { return flags_; } bool operator==(AXMode rhs) const { return flags_ == rhs.flags_; } @@ -102,6 +102,8 @@ std::string ToString() const; + uint32_t flags_ = 0U; + // IMPORTANT! // These values are written to logs. Do not renumber or delete // existing items; add new entries to the end of the list. @@ -119,9 +121,6 @@ // increase, but none of the other enum values may change. UMA_AX_MODE_MAX }; - - private: - uint32_t flags_; }; // Used when an AT that only require basic accessibility information, such as
diff --git a/ui/accessibility/mojom/BUILD.gn b/ui/accessibility/mojom/BUILD.gn index 75192d4..7e932995 100644 --- a/ui/accessibility/mojom/BUILD.gn +++ b/ui/accessibility/mojom/BUILD.gn
@@ -10,6 +10,7 @@ "ax_action_data.mojom", "ax_event.mojom", "ax_event_intent.mojom", + "ax_mode.mojom", "ax_node_data.mojom", "ax_relative_bounds.mojom", "ax_tree_data.mojom", @@ -84,6 +85,17 @@ { types = [ { + mojom = "ax.mojom.AXMode" + cpp = "::ui::AXMode" + }, + ] + traits_sources = [ "ax_mode_mojom_traits.cc" ] + traits_headers = [ "ax_mode_mojom_traits.h" ] + traits_public_deps = [ "//ui/accessibility:ax_base" ] + }, + { + types = [ + { mojom = "ax.mojom.AXNodeData" cpp = "::ui::AXNodeData" },
diff --git a/ui/accessibility/mojom/ax_mode.mojom b/ui/accessibility/mojom/ax_mode.mojom new file mode 100644 index 0000000..691fdc9 --- /dev/null +++ b/ui/accessibility/mojom/ax_mode.mojom
@@ -0,0 +1,15 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module ax.mojom; + +// The AXMode determines the amount of information the Chrome accessibility +// engine will serialize in the accessibility tree. +// The mode is currently implemented as a bit field with individual flags +// that may be set in conjunction with each other. +// The implementation may change in the future to a less opaque form. +// See ui::AXMode for additional documentation about individual flags and modes. +struct AXMode { + uint32 flags; +};
diff --git a/ui/accessibility/mojom/ax_mode_mojom_traits.cc b/ui/accessibility/mojom/ax_mode_mojom_traits.cc new file mode 100644 index 0000000..51f0aa5a --- /dev/null +++ b/ui/accessibility/mojom/ax_mode_mojom_traits.cc
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/accessibility/mojom/ax_mode_mojom_traits.h" + +namespace mojo { + +// static +bool StructTraits<ax::mojom::AXModeDataView, ui::AXMode>::Read( + ax::mojom::AXModeDataView data, + ui::AXMode* out) { + // This is a bit field. Check that flags fall within accepted bounds. + if (data.flags() >= ui::AXMode::kLastModeFlag * 2) { + return false; + } + + out->flags_ = data.flags(); + return true; +} + +} // namespace mojo
diff --git a/ui/accessibility/mojom/ax_mode_mojom_traits.h b/ui/accessibility/mojom/ax_mode_mojom_traits.h new file mode 100644 index 0000000..ad36fc28 --- /dev/null +++ b/ui/accessibility/mojom/ax_mode_mojom_traits.h
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_ACCESSIBILITY_MOJOM_AX_MODE_MOJOM_TRAITS_H_ +#define UI_ACCESSIBILITY_MOJOM_AX_MODE_MOJOM_TRAITS_H_ + +#include "ui/accessibility/ax_mode.h" +#include "ui/accessibility/mojom/ax_mode.mojom-shared.h" + +namespace mojo { + +template <> +struct StructTraits<ax::mojom::AXModeDataView, ui::AXMode> { + static uint32_t flags(const ui::AXMode& p) { return p.flags(); } + + static bool Read(ax::mojom::AXModeDataView data, ui::AXMode* out); +}; + +} // namespace mojo + +#endif // UI_ACCESSIBILITY_MOJOM_AX_MODE_MOJOM_TRAITS_H_
diff --git a/ui/accessibility/mojom/ax_mode_mojom_traits_unittest.cc b/ui/accessibility/mojom/ax_mode_mojom_traits_unittest.cc new file mode 100644 index 0000000..f09b070f --- /dev/null +++ b/ui/accessibility/mojom/ax_mode_mojom_traits_unittest.cc
@@ -0,0 +1,18 @@ +// Copyright 2022 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/accessibility/mojom/ax_mode_mojom_traits.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/accessibility/ax_mode.h" +#include "ui/accessibility/mojom/ax_mode.mojom.h" + +using mojo::test::SerializeAndDeserialize; + +TEST(AXModeMojomTraitsTest, TestSerializeAndDeserializeAXModeData) { + ui::AXMode input(ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); + ui::AXMode output; + EXPECT_TRUE(SerializeAndDeserialize<ax::mojom::AXMode>(input, output)); + EXPECT_EQ(ui::kAXModeBasic, output); +}
diff --git a/ui/android/java/src/org/chromium/ui/KeyboardVisibilityDelegate.java b/ui/android/java/src/org/chromium/ui/KeyboardVisibilityDelegate.java index fbcaa1f..670c733 100644 --- a/ui/android/java/src/org/chromium/ui/KeyboardVisibilityDelegate.java +++ b/ui/android/java/src/org/chromium/ui/KeyboardVisibilityDelegate.java
@@ -189,16 +189,6 @@ } /** - * Returns the total keyboard widget height. - * - * In addition to the keyboard itself, this may include accessory bars and related widgets that - * behave as-if they're part of the keyboard if the embedder supports them. - */ - public int calculateTotalKeyboardHeight(View rootView) { - return calculateKeyboardHeight(rootView); - } - - /** * Returns whether the keyboard is showing. * @param context A {@link Context} instance. * @param view A {@link View}.
diff --git a/ui/base/models/dialog_model.cc b/ui/base/models/dialog_model.cc index 984aceb..58573df 100644 --- a/ui/base/models/dialog_model.cc +++ b/ui/base/models/dialog_model.cc
@@ -33,7 +33,6 @@ DialogModel::Builder& DialogModel::Builder::AddOkButton( base::OnceClosure callback, - std::u16string label, const DialogModelButton::Params& params) { DCHECK(!model_->accept_action_callback_); model_->accept_action_callback_ = std::move(callback); @@ -41,15 +40,13 @@ // DialogModelHost should be using OnDialogAccepted() instead. model_->ok_button_.emplace( model_->GetPassKey(), model_.get(), - base::BindRepeating([](const Event&) { NOTREACHED(); }), std::move(label), - params); + base::BindRepeating([](const Event&) { NOTREACHED(); }), params); return *this; } DialogModel::Builder& DialogModel::Builder::AddCancelButton( base::OnceClosure callback, - std::u16string label, const DialogModelButton::Params& params) { DCHECK(!model_->cancel_action_callback_); model_->cancel_action_callback_ = std::move(callback); @@ -57,20 +54,20 @@ // DialogModelHost should be using OnDialogCanceled() instead. model_->cancel_button_.emplace( model_->GetPassKey(), model_.get(), - base::BindRepeating([](const Event&) { NOTREACHED(); }), std::move(label), - params); + base::BindRepeating([](const Event&) { NOTREACHED(); }), params); return *this; } DialogModel::Builder& DialogModel::Builder::AddExtraButton( base::RepeatingCallback<void(const Event&)> callback, - std::u16string label, const DialogModelButton::Params& params) { DCHECK(!model_->extra_button_); DCHECK(!model_->extra_link_); + // Extra buttons are required to have labels. + DCHECK(!params.label_.empty()); model_->extra_button_.emplace(model_->GetPassKey(), model_.get(), - std::move(callback), std::move(label), params); + std::move(callback), params); return *this; }
diff --git a/ui/base/models/dialog_model.h b/ui/base/models/dialog_model.h index c8f0375..ccf8cb3d 100644 --- a/ui/base/models/dialog_model.h +++ b/ui/base/models/dialog_model.h
@@ -202,20 +202,17 @@ // sync with other APIs? Builder& AddOkButton( base::OnceClosure callback, - std::u16string label = std::u16string(), const DialogModelButton::Params& params = DialogModelButton::Params()); Builder& AddCancelButton( base::OnceClosure callback, - std::u16string label = std::u16string(), const DialogModelButton::Params& params = DialogModelButton::Params()); // Use of the extra button in new dialogs are discouraged. If this is deemed // necessary please double-check with UX before adding any new dialogs with - // them. + // them. A button label is required to be set in `params`. Builder& AddExtraButton( base::RepeatingCallback<void(const Event&)> callback, - std::u16string label, - const DialogModelButton::Params& params = DialogModelButton::Params()); + const DialogModelButton::Params& params); // Adds an extra link to the dialog. Builder& AddExtraLink(DialogModelLabel::TextReplacement link);
diff --git a/ui/base/models/dialog_model_field.cc b/ui/base/models/dialog_model_field.cc index 20494f9..4aef0eb 100644 --- a/ui/base/models/dialog_model_field.cc +++ b/ui/base/models/dialog_model_field.cc
@@ -191,6 +191,14 @@ return *this; } +DialogModelButton::Params& DialogModelButton::Params::SetLabel( + std::u16string label) { + DCHECK(label_.empty()); + DCHECK(!label.empty()); + label_ = label; + return *this; +} + DialogModelButton::Params& DialogModelButton::Params::AddAccelerator( Accelerator accelerator) { accelerators_.insert(std::move(accelerator)); @@ -201,14 +209,13 @@ base::PassKey<DialogModel> pass_key, DialogModel* model, base::RepeatingCallback<void(const Event&)> callback, - std::u16string label, const DialogModelButton::Params& params) : DialogModelField(pass_key, model, kButton, params.id_, params.accelerators_), - label_(std::move(label)), + label_(std::move(params.label_)), callback_(std::move(callback)) { DCHECK(callback_); }
diff --git a/ui/base/models/dialog_model_field.h b/ui/base/models/dialog_model_field.h index 5d8fb77..e62a3ef2 100644 --- a/ui/base/models/dialog_model_field.h +++ b/ui/base/models/dialog_model_field.h
@@ -220,13 +220,16 @@ ~Params(); Params& SetId(ElementIdentifier id); + Params& SetLabel(std::u16string label); Params& AddAccelerator(Accelerator accelerator); private: + friend class DialogModel; friend class DialogModelButton; ElementIdentifier id_; + std::u16string label_; base::flat_set<Accelerator> accelerators_; }; @@ -235,7 +238,6 @@ DialogModelButton(base::PassKey<DialogModel> pass_key, DialogModel* model, base::RepeatingCallback<void(const Event&)> callback, - std::u16string label, const Params& params); DialogModelButton(const DialogModelButton&) = delete; DialogModelButton& operator=(const DialogModelButton&) = delete;
diff --git a/ui/base/models/dialog_model_unittest.cc b/ui/base/models/dialog_model_unittest.cc index f17ac79..6729a27 100644 --- a/ui/base/models/dialog_model_unittest.cc +++ b/ui/base/models/dialog_model_unittest.cc
@@ -26,7 +26,7 @@ // are supported. auto host = std::make_unique<TestDialogModelHost>( DialogModel::Builder() - .AddOkButton(base::OnceClosure(), std::u16string(), + .AddOkButton(base::OnceClosure(), DialogModelButton::Params().SetId(kUniqueId)) .Build()); EXPECT_EQ(kUniqueId, host->GetId(TestDialogModelHost::ButtonId::kOk)); @@ -40,10 +40,9 @@ // are supported. auto host = std::make_unique<TestDialogModelHost>( DialogModel::Builder() - .AddOkButton(base::OnceClosure(), std::u16string(), - DialogModelButton::Params() - .AddAccelerator(accelerator_1) - .AddAccelerator(accelerator_2)) + .AddOkButton(base::OnceClosure(), DialogModelButton::Params() + .AddAccelerator(accelerator_1) + .AddAccelerator(accelerator_2)) .Build()); EXPECT_THAT(host->GetAccelerators(TestDialogModelHost::ButtonId::kOk), testing::UnorderedElementsAre(accelerator_1, accelerator_2)); @@ -61,7 +60,7 @@ last_event = std::make_unique<KeyEvent>(*event.AsKeyEvent()); }), - std::u16string()) + DialogModelButton::Params().SetLabel(u"button")) .Build()); KeyEvent first_event(ET_KEY_PRESSED, VKEY_RETURN, EF_NONE); @@ -86,18 +85,17 @@ [](bool* callback_called) { *callback_called = true; }, &callback_called); - // Label to verify the second parameter. - std::u16string label = u"my cool button"; - // The presence of an accelerator in |params| will be used to verify that // |params| are forwarded correctly to the DialogModelButton constructor. DialogModelButton::Params params; - Accelerator accelerator(VKEY_Z, EF_SHIFT_DOWN | EF_CONTROL_DOWN); + const Accelerator accelerator(VKEY_Z, EF_SHIFT_DOWN | EF_CONTROL_DOWN); + const std::u16string label = u"my cool button"; params.AddAccelerator(accelerator); + params.SetLabel(label); switch (button_id) { case TestDialogModelHost::ButtonId::kCancel: - builder.AddCancelButton(std::move(callback), label, params); + builder.AddCancelButton(std::move(callback), params); break; case TestDialogModelHost::ButtonId::kExtra: // Wrap the callback into a repeating callback that'll only be called @@ -108,10 +106,10 @@ std::move(*callback).Run(); }, &callback), - label, params); + params); break; case TestDialogModelHost::ButtonId::kOk: - builder.AddOkButton(std::move(callback), label, params); + builder.AddOkButton(std::move(callback), params); break; } auto host = std::make_unique<TestDialogModelHost>(builder.Build());
diff --git a/ui/chromeos/styles/cros_sys_colors.json5 b/ui/chromeos/styles/cros_sys_colors.json5 index 87f9c8f..2ffa4c4 100644 --- a/ui/chromeos/styles/cros_sys_colors.json5 +++ b/ui/chromeos/styles/cros_sys_colors.json5
@@ -224,25 +224,17 @@ light: 'rgba($cros.ref.neutral10.rgb, 0.10)', dark: 'rgba($cros.ref.neutral10.rgb, 0.06)', }, - 'hover-on-quiet': { - light: 'rgba($cros.ref.neutral10.rgb, 0.06)', - dark: 'rgba($cros.ref.neutral10.rgb, 0.16)', - }, - 'hover-on-base': { + 'hover-on-subtle': { light: 'rgba($cros.ref.neutral10.rgb, 0.06)', dark: 'rgba($cros.ref.neutral99.rgb, 0.1)', }, - 'hover-alt': { - light: 'rgba($cros.ref.neutral99.rgb, 0.1)', - dark: 'rgba($cros.ref.neutral10.rgb, 0.06)', - }, 'ripple-primary': { light: 'rgba($cros.ref.primary70.rgb, 0.32)', dark: 'rgba($cros.ref.primary60.rgb, 0.32)', }, 'ripple-neutral-on-prominent': { light: 'rgba($cros.ref.neutral99.rgb, 0.16)', - dark: 'rgba($cros.ref.neutral10.rgb, 0.12)', + dark: 'rgba($cros.ref.neutral10.rgb, 0.08)', }, 'ripple-neutral-on-subtle': { light: 'rgba($cros.ref.neutral10.rgb, 0.12)', @@ -255,6 +247,10 @@ 'highlight-text': { light: 'rgba($cros.ref.primary70.rgb, 0.6)', dark: 'rgba($cros.ref.primary70.rgb, 0.6)', + }, + 'focus-ring': { + light: '$cros.ref.primary40', + dark: '$cros.ref.primary80', } }, }
diff --git a/ui/file_manager/file_manager/common/js/api.js b/ui/file_manager/file_manager/common/js/api.js index 368311a0..50fc114 100644 --- a/ui/file_manager/file_manager/common/js/api.js +++ b/ui/file_manager/file_manager/common/js/api.js
@@ -286,3 +286,13 @@ export async function getFileTasks(entries) { return promisify(chrome.fileManagerPrivate.getFileTasks, entries); } + +/** + * @param {!chrome.fileManagerPrivate.FileTaskDescriptor} taskDescriptor + * @param {!Array<!Entry|!FilesAppEntry>} entries + * @return {!Promise<chrome.fileManagerPrivate.TaskResult>} + */ +export async function executeTask(taskDescriptor, entries) { + return promisify( + chrome.fileManagerPrivate.executeTask, taskDescriptor, entries); +}
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js index 4139285..64044b7 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
@@ -1842,19 +1842,9 @@ */ CommandHandler.COMMANDS_['open-with'] = new (class extends FilesCommand { execute(event, fileManager) { - fileManager.taskController.getFileTasks() - .then(tasks => { - tasks.showTaskPicker( - fileManager.ui.defaultTaskPicker, str('OPEN_WITH_BUTTON_LABEL'), - '', task => { - tasks.execute(task); - }, TaskPickerType.OpenWith); - }) - .catch(error => { - if (error) { - console.warn(error.stack || error); - } - }); + console.assert( + `open-with command doesn't execute, ` + + `instead it only opens the sub-menu`); } /** @override */
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks.ts b/ui/file_manager/file_manager/foreground/js/file_tasks.ts index e25e74e..78b7ea8 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks.ts +++ b/ui/file_manager/file_manager/foreground/js/file_tasks.ts
@@ -8,9 +8,8 @@ * @suppress {checkTypes} */ import {assert} from 'chrome://resources/js/assert.js'; -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {getDirectory, getFileTasks} from '../../common/js/api.js'; +import {executeTask, getDirectory, getFileTasks} from '../../common/js/api.js'; import {AsyncQueue} from '../../common/js/async_util.js'; import {FileType} from '../../common/js/file_type.js'; import {metrics} from '../../common/js/metrics.js'; @@ -46,7 +45,6 @@ QUICK_OFFICE: 2, }; -type TaskResultType = chrome.fileManagerPrivate.TaskResult; /** * Represents a collection of available tasks to execute for a specific list * of entries. @@ -323,51 +321,51 @@ if (isFilesAppId(appId) && (taskType === 'app' || taskType === 'web')) { if (parsedActionId === 'mount-archive') { task.iconType = 'archive'; - task.title = loadTimeData.getString('MOUNT_ARCHIVE'); + task.title = str('MOUNT_ARCHIVE'); } else if (parsedActionId === 'open-hosted-generic') { if (entries.length > 1) { task.iconType = 'generic'; } else { // Use specific icon. task.iconType = FileType.getIcon(entries[0]!); } - task.title = loadTimeData.getString('TASK_OPEN'); + task.title = str('TASK_OPEN'); } else if (parsedActionId === 'open-hosted-gdoc') { task.iconType = 'gdoc'; - task.title = loadTimeData.getString('TASK_OPEN_GDOC'); + task.title = str('TASK_OPEN_GDOC'); } else if (parsedActionId === 'open-hosted-gsheet') { task.iconType = 'gsheet'; - task.title = loadTimeData.getString('TASK_OPEN_GSHEET'); + task.title = str('TASK_OPEN_GSHEET'); } else if (parsedActionId === 'open-hosted-gslides') { task.iconType = 'gslides'; - task.title = loadTimeData.getString('TASK_OPEN_GSLIDES'); + task.title = str('TASK_OPEN_GSLIDES'); } else if (parsedActionId === 'open-web-drive-office-word') { task.iconType = 'gdoc'; - task.title = loadTimeData.getString('TASK_OPEN_GDOC'); + task.title = str('TASK_OPEN_GDOC'); } else if (parsedActionId === 'open-web-drive-office-excel') { task.iconType = 'gsheet'; - task.title = loadTimeData.getString('TASK_OPEN_GSHEET'); + task.title = str('TASK_OPEN_GSHEET'); } else if (parsedActionId === 'upload-office-to-drive') { task.iconType = 'generic'; task.title = 'Upload to Drive'; } else if (parsedActionId === 'open-web-drive-office-powerpoint') { task.iconType = 'gslides'; - task.title = loadTimeData.getString('TASK_OPEN_GSLIDES'); + task.title = str('TASK_OPEN_GSLIDES'); } else if (parsedActionId === 'open-in-office') { task.iconUrl = toFilesAppURL('foreground/images/files/ui/ms365.svg').toString(); - task.title = loadTimeData.getString('TASK_OPEN_OFFICE'); + task.title = str('TASK_OPEN_OFFICE'); } else if (parsedActionId === 'install-linux-package') { task.iconType = 'crostini'; - task.title = loadTimeData.getString('TASK_INSTALL_LINUX_PACKAGE'); + task.title = str('TASK_INSTALL_LINUX_PACKAGE'); } else if (parsedActionId === 'import-crostini-image') { task.iconType = 'tini'; - task.title = loadTimeData.getString('TASK_IMPORT_CROSTINI_IMAGE'); + task.title = str('TASK_IMPORT_CROSTINI_IMAGE'); } else if (parsedActionId === 'view-pdf') { task.iconType = 'pdf'; - task.title = loadTimeData.getString('TASK_VIEW'); + task.title = str('TASK_VIEW'); } else if (parsedActionId === 'view-in-browser') { task.iconType = 'generic'; - task.title = loadTimeData.getString('TASK_VIEW'); + task.title = str('TASK_VIEW'); } } if (!task.iconType && taskType === 'web-intent') { @@ -418,43 +416,31 @@ }); } - /** - * Executes default task. - * @param {function()=} callback Called when the default task is executed, or - * the error is occurred. - */ - executeDefault(callback?: (isDefault: boolean, entries: Entry[]) => void) { + /** Executes default task. */ + async executeDefault(): Promise<void> { FileTasks.recordViewingFileTypeUMA_(this.volumeManager_, this.entries_); FileTasks.recordViewingRootTypeUMA_( this.volumeManager_, this.directoryModel_.getCurrentRootType()); FileTasks.recordOfficeFileHandlerUMA_( this.volumeManager_, this.entries_, this.directoryModel_.getCurrentRootType(), this.defaultTask_); - this.executeDefaultInternal_(callback); + return this.executeDefaultInternal_(); } - /** - * Executes default task. - * @param callback Called when the default task is executed, or the error is - * occurred. - */ - private executeDefaultInternal_( - callback?: (isDefault: boolean, entries: Entry[]) => void) { - callback = callback || ((_0: boolean, _1: Entry[]) => {}); - + private async executeDefaultInternal_(): Promise<void> { if (this.defaultTask_) { this.executeInternal_(this.defaultTask_); - callback(true, this.entries_); return; } // If there's policy involved and |defaultTask_| is null, means that policy // assignment was incorrect. We should not execute anything in this case. if (this.getPolicyDefaultHandlerStatus()) { - assert( + console.assert( this.getPolicyDefaultHandlerStatus() === - chrome.fileManagerPrivate.PolicyDefaultHandlerStatus - .INCORRECT_ASSIGNMENT); + chrome.fileManagerPrivate.PolicyDefaultHandlerStatus + .INCORRECT_ASSIGNMENT, + 'policyDefaultHandlerStatus expected to be INCORRECT, thus not executing the task'); return; } @@ -482,7 +468,31 @@ const filename = this.entries_[0]!.name; const extension = util.splitExtension(filename)[1] || null; - const showAlert = () => { + await this.checkAvailability_(); + + try { + const descriptor = { + appId: LEGACY_FILES_EXTENSION_ID, + taskType: 'file', + actionId: 'view-in-browser', + }; + const result = await executeTask(descriptor, this.entries_); + switch (result) { + case 'opened': + break; + case 'message_sent': + util.isTeleported(window).then(teleported => { + if (teleported) { + this.ui_.showOpenInOtherDesktopAlert(this.entries_); + } + }); + break; + case 'empty': + break; + case 'failed': + throw new Error(); + } + } catch { let textMessageId; let titleMessageId; switch (extension) { @@ -503,51 +513,8 @@ const text = strf(textMessageId, str('NO_TASK_FOR_FILE_URL')); const title = titleMessageId ? str(titleMessageId) : filename; - this.ui_.alertDialog.showHtml(title, text, null, null, null); - callback!(false, this.entries_); - }; - - const onViewFilesFailure = () => { - showAlert(); - }; - - const onViewFiles = (result: TaskResultType) => { - if (chrome.runtime.lastError) { - // Suppress the Unchecked runtime.lastError console message - console.debug(chrome.runtime.lastError.message); - onViewFilesFailure(); - return; - } - switch (result) { - case 'opened': - callback!(true, this.entries_); - break; - case 'message_sent': - util.isTeleported(window).then(teleported => { - if (teleported) { - this.ui_.showOpenInOtherDesktopAlert(this.entries_); - } - }); - callback!(true, this.entries_); - break; - case 'empty': - callback!(true, this.entries_); - break; - case 'failed': - onViewFilesFailure(); - break; - } - }; - - this.checkAvailability_(() => { - const descriptor = { - appId: LEGACY_FILES_EXTENSION_ID, - taskType: 'file', - actionId: 'view-in-browser', - }; - chrome.fileManagerPrivate.executeTask( - descriptor, this.entries_, onViewFiles); - }); + this.ui_.alertDialog.showHtml(title, text); + } } /** Executes a single task. */ @@ -562,19 +529,28 @@ } /** The core implementation to execute a single task. */ - private executeInternal_(task: chrome.fileManagerPrivate.FileTask) { - const onFileManagerPrivateExecuteTask = (result: TaskResultType) => { - if (chrome.runtime.lastError) { - console.warn( - 'Unable to execute task: ' + chrome.runtime.lastError.message); - return; - } + private async executeInternal_(task: chrome.fileManagerPrivate.FileTask): + Promise<void> { + const entries = this.entries_; + await this.checkAvailability_(); + this.taskHistory_.recordTaskExecuted(task.descriptor); + const msg = (entries.length === 1) ? + strf('OPEN_A11Y', entries[0]!.name) : + strf('OPEN_A11Y_PLURAL', entries.length); + this.ui_.speakA11yMessage(msg); + if (FileTasks.isInternalTask_(task.descriptor)) { + this.executeInternalTask_(task.descriptor); + return; + } + + try { + const result = await executeTask(task.descriptor, entries); const TaskResult = chrome.fileManagerPrivate.TaskResult; switch (result) { case TaskResult.MESSAGE_SENT: util.isTeleported(window).then((teleported) => { if (teleported) { - this.ui_.showOpenInOtherDesktopAlert(this.entries_); + this.ui_.showOpenInOtherDesktopAlert(entries); } }); break; @@ -586,38 +562,24 @@ 'UNABLE_TO_OPEN_WITH_PLUGIN_VM_EXTERNAL_DRIVE_MESSAGE', task.title); FileTasks.showPluginVmNotSharedDialog( - this.entries_, this.volumeManager_, this.metadataModel_, this.ui_, + entries, this.volumeManager_, this.metadataModel_, this.ui_, moveMessage, copyMessage, this.fileTransferController_, this.directoryModel_); break; } - }; - - this.checkAvailability_(() => { - this.taskHistory_.recordTaskExecuted(task.descriptor); - let msg; - if (this.entries_.length === 1) { - msg = strf('OPEN_A11Y', this.entries_[0]!.name); - } else { - msg = strf('OPEN_A11Y_PLURAL', this.entries_.length); - } - this.ui_.speakA11yMessage(msg); - if (FileTasks.isInternalTask_(task.descriptor)) { - this.executeInternalTask_(task.descriptor); - } else { - chrome.fileManagerPrivate.executeTask( - task.descriptor, this.entries_, onFileManagerPrivateExecuteTask); - } - }); + } catch (error) { + console.warn(`Failed to execute task ${task.descriptor}: ${error}`); + } } /** * Ensures that the all files are available right now. * Must not call before initialization. - * @param callback Called when checking is completed and all files are - * available. Otherwise not called. + * Resolved when checking is completed and all files are available + * Rejected/throws if the user cancels the confirmation dialog for downloading + * in cellular/metered network dialog. */ - private checkAvailability_(callback: () => void) { + private async checkAvailability_(): Promise<void> { const areAll = (entries: Entry[], props: MetadataItem[], name: keyof MetadataItem) => { let okEntriesNum = 0; @@ -640,7 +602,6 @@ // availableWhenMetered are not exposed for other types of volumes at this // moment. if (!containsDriveEntries) { - callback(); return; } @@ -649,58 +610,48 @@ chrome.fileManagerPrivate.DriveConnectionStateType.OFFLINE; if (isDriveOffline) { - this.metadataModel_.get(this.entries_, ['availableOffline', 'hosted']) - .then((props: MetadataItem[]) => { - if (areAll(this.entries_, props, 'availableOffline')) { - callback(); - return; - } + const props = await this.metadataModel_.get( + this.entries_, ['availableOffline', 'hosted']); + if (areAll(this.entries_, props, 'availableOffline')) { + return; + } + const msg = props[0]!.hosted ? + str(this.entries_.length === 1 ? 'HOSTED_OFFLINE_MESSAGE' : + 'HOSTED_OFFLINE_MESSAGE_PLURAL') : + strf( + this.entries_.length === 1 ? 'OFFLINE_MESSAGE' : + 'OFFLINE_MESSAGE_PLURAL', + str('OFFLINE_COLUMN_LABEL')); - this.ui_.alertDialog.showHtml( - loadTimeData.getString('OFFLINE_HEADER'), - props[0]!.hosted ? - loadTimeData.getStringF( - this.entries_.length === 1 ? - 'HOSTED_OFFLINE_MESSAGE' : - 'HOSTED_OFFLINE_MESSAGE_PLURAL') : - loadTimeData.getStringF( - this.entries_.length === 1 ? 'OFFLINE_MESSAGE' : - 'OFFLINE_MESSAGE_PLURAL', - loadTimeData.getString('OFFLINE_COLUMN_LABEL')), - null, null, null); - }); + this.ui_.alertDialog.showHtml(str('OFFLINE_HEADER'), msg); return; } const isOnMetered = this.volumeManager_.getDriveConnectionState().type === chrome.fileManagerPrivate.DriveConnectionStateType.METERED; - if (isOnMetered) { - this.metadataModel_.get(this.entries_, ['availableWhenMetered', 'size']) - .then((props: MetadataItem[]) => { - if (areAll(this.entries_, props, 'availableWhenMetered')) { - callback(); - return; - } + if (!isOnMetered) { + return; + } + const props = await this.metadataModel_.get( + this.entries_, ['availableWhenMetered', 'size']); - let sizeToDownload = 0; - for (let i = 0; i !== this.entries_.length; i++) { - if (!props[i]!.availableWhenMetered) { - sizeToDownload += (props[i]!.size || 0); - } - } - this.ui_.confirmDialog.show( - loadTimeData.getStringF( - this.entries_.length === 1 ? - 'CONFIRM_MOBILE_DATA_USE' : - 'CONFIRM_MOBILE_DATA_USE_PLURAL', - util.bytesToString(sizeToDownload)), - callback); - }); + if (areAll(this.entries_, props, 'availableWhenMetered')) { return; } - callback(); + let sizeToDownload = 0; + for (let i = 0; i !== this.entries_.length; i++) { + if (!props[i]!.availableWhenMetered) { + sizeToDownload += (props[i]!.size || 0); + } + } + const msg = strf( + this.entries_.length === 1 ? 'CONFIRM_MOBILE_DATA_USE' : + 'CONFIRM_MOBILE_DATA_USE_PLURAL', + util.bytesToString(sizeToDownload)); + return new Promise( + (resolve, reject) => this.ui_.confirmDialog.show(msg, resolve, reject)); } /**
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.ts b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.ts index fe60fc3..3f20d44 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.ts +++ b/ui/file_manager/file_manager/foreground/js/file_tasks_unittest.ts
@@ -11,7 +11,6 @@ import {installMockChrome} from '../../common/js/mock_chrome.js'; import {MockFileEntry, MockFileSystem} from '../../common/js/mock_entry.js'; import {ProgressItemState} from '../../common/js/progress_center_common.js'; -import {reportPromise} from '../../common/js/test_error_reporting.js'; import {LEGACY_FILES_EXTENSION_ID} from '../../common/js/url_constants.js'; import {util} from '../../common/js/util.js'; import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; @@ -282,7 +281,7 @@ /** * Returns a promise that resolves when showImportCrostiniImageDialog is called. */ -function showImportCrostiniImageDialogIsCalled(entries: Entry[]): +async function showImportCrostiniImageDialogIsCalled(entries: Entry[]): Promise<void> { return new Promise((resolve) => { const fileManager = getMockFileManager(); @@ -306,55 +305,52 @@ } /** Tests opening a .exe file. */ -export function testToOpenExeFile(callback: () => void) { +export async function testToOpenExeFile(done: () => void) { const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.exe'); - reportPromise( - showHtmlOfAlertDialogIsCalled( - [mockEntry], 'test.exe', 'NO_TASK_FOR_EXECUTABLE'), - callback); + await showHtmlOfAlertDialogIsCalled( + [mockEntry], 'test.exe', 'NO_TASK_FOR_EXECUTABLE'); + done(); } /** Tests opening a .dmg file. */ -export function testToOpenDmgFile(callback: () => void) { +export async function testToOpenDmgFile(done: () => void) { const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.dmg'); - reportPromise( - showHtmlOfAlertDialogIsCalled([mockEntry], 'test.dmg', 'NO_TASK_FOR_DMG'), - callback); + await showHtmlOfAlertDialogIsCalled( + [mockEntry], 'test.dmg', 'NO_TASK_FOR_DMG'); + done(); } /** * Tests opening a .crx file. */ -export function testToOpenCrxFile(callback: () => void) { +export async function testToOpenCrxFile(done: () => void) { const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.crx'); - reportPromise( - showHtmlOfAlertDialogIsCalled( - [mockEntry], 'NO_TASK_FOR_CRX_TITLE', 'NO_TASK_FOR_CRX'), - callback); + await showHtmlOfAlertDialogIsCalled( + [mockEntry], 'NO_TASK_FOR_CRX_TITLE', 'NO_TASK_FOR_CRX'); + done(); } /** Tests opening a .rtf file. */ -export function testToOpenRtfFile(callback: () => void) { +export async function testToOpenRtfFile(done: () => void) { const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.rtf'); - reportPromise( - showHtmlOfAlertDialogIsCalled( - [mockEntry], 'test.rtf', 'NO_TASK_FOR_FILE'), - callback); + await showHtmlOfAlertDialogIsCalled( + [mockEntry], 'test.rtf', 'NO_TASK_FOR_FILE'); + done(); } /** * Tests opening the task picker with an entry that does not have a default app * but there are multiple apps that could open it. */ -export function testOpenTaskPicker(callback: () => void) { +export async function testOpenTaskPicker(done: () => void) { chrome.fileManagerPrivate.getFileTasks = (_entries: Entry[], callback: (tasks: any) => void) => { setTimeout( @@ -388,7 +384,8 @@ const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.tiff'); - reportPromise(showDefaultTaskDialogCalled([mockEntry]), callback); + await showDefaultTaskDialogCalled([mockEntry]); + done(); } /** @@ -396,7 +393,7 @@ * but there are multiple apps that could open it. The app with the most recent * task execution order should execute. */ -export function testOpenWithMostRecentlyExecuted(callback: () => void) { +export async function testOpenWithMostRecentlyExecuted(done: () => void) { const latestTaskDescriptor = { appId: 'handler-extension-most-recently-executed', taskType: 'app', @@ -472,30 +469,23 @@ const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.tiff'); - const promise = new Promise<void>((resolve) => { - const fileManager = getMockFileManager(); - fileManager.ui.defaultTaskPicker = { - showDefaultTaskDialog: function( - _title, _message, _items, _defaultIdx, _onSuccess) { - failWithMessage('should not show task picker'); - }, - } as DefaultTaskDialog; + const fileManager = getMockFileManager(); + fileManager.ui.defaultTaskPicker = { + showDefaultTaskDialog: function( + _title, _message, _items, _defaultIdx, _onSuccess) { + failWithMessage('should not show task picker'); + }, + } as DefaultTaskDialog; - FileTasks - .create( - fileManager.volumeManager, fileManager.metadataModel, - fileManager.directoryModel, fileManager.ui, - mockFileTransferController, [mockEntry], taskHistory as TaskHistory, - fileManager.crostini, fileManager.progressCenter, - fileManager.taskController) - .then(tasks => { - tasks.executeDefault(); - assertTrue(util.descriptorEqual(latestTaskDescriptor, executedTask!)); - resolve(); - }); - }); + const tasks = await FileTasks.create( + fileManager.volumeManager, fileManager.metadataModel, + fileManager.directoryModel, fileManager.ui, mockFileTransferController, + [mockEntry], taskHistory as TaskHistory, fileManager.crostini, + fileManager.progressCenter, fileManager.taskController); + await tasks.executeDefault(); + assertTrue(util.descriptorEqual(latestTaskDescriptor, executedTask!)); - reportPromise(promise, callback); + done(); } function setUpInstallLinuxPackage() { @@ -526,39 +516,35 @@ * Tests opening a .deb file. The crostini linux package install dialog should * be called. */ -export function testOpenInstallLinuxPackageDialog(callback: () => void) { +export async function testOpenInstallLinuxPackageDialog(done: () => void) { const fileManager = setUpInstallLinuxPackage(); const mockFileSystem = new MockFileSystem('volumeId'); const mockEntry = MockFileEntry.create(mockFileSystem, '/test.deb'); - const promise = new Promise<void>((resolve) => { + await new Promise<void>(async (resolve) => { fileManager.ui.installLinuxPackageDialog = { showInstallLinuxPackageDialog: function(_entry: Entry) { resolve(); }, } as unknown as InstallLinuxPackageDialog; - FileTasks - .create( - fileManager.volumeManager, fileManager.metadataModel, - fileManager.directoryModel, fileManager.ui, - mockFileTransferController, [mockEntry], mockTaskHistory, - fileManager.crostini, fileManager.progressCenter, - fileManager.taskController) - .then(tasks => { - tasks.executeDefault(); - }); + const tasks = await FileTasks.create( + fileManager.volumeManager, fileManager.metadataModel, + fileManager.directoryModel, fileManager.ui, mockFileTransferController, + [mockEntry], mockTaskHistory, fileManager.crostini, + fileManager.progressCenter, fileManager.taskController); + await tasks.executeDefault(); }); - reportPromise(promise, callback); + done(); } /** * Tests opening a .tini file. The import crostini image dialog should be * called. */ -export function testToOpenTiniFileOpensImportCrostiniImageDialog( - callback: () => void) { +export async function testToOpenTiniFileOpensImportCrostiniImageDialog( + done: () => void) { chrome.fileManagerPrivate.getFileTasks = (_entries: Entry[], callback: (tasks: any) => void) => { setTimeout( @@ -581,7 +567,8 @@ const mockEntry = MockFileEntry.create(new MockFileSystem('testfilesystem'), '/test.tini'); - reportPromise(showImportCrostiniImageDialogIsCalled([mockEntry]), callback); + await showImportCrostiniImageDialogIsCalled([mockEntry]); + done(); } /**
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller.ts b/ui/file_manager/file_manager/foreground/js/task_controller.ts index 32232cd..230aff059 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller.ts +++ b/ui/file_manager/file_manager/foreground/js/task_controller.ts
@@ -300,8 +300,7 @@ return items; } - - /** Executes default task. */ + /** Executes default task from the dropdown menu. */ async executeDefaultTask() { try { const tasks = await this.getFileTasks();
diff --git a/ui/shell_dialogs/select_file_dialog_linux_portal.cc b/ui/shell_dialogs/select_file_dialog_linux_portal.cc index 6d55452c..f843bf5 100644 --- a/ui/shell_dialogs/select_file_dialog_linux_portal.cc +++ b/ui/shell_dialogs/select_file_dialog_linux_portal.cc
@@ -170,7 +170,7 @@ // static bool SelectFileDialogLinuxPortal::IsPortalAvailable() { if (!GetAvailabilityTestCompletionFlag()->IsSet()) - LOG(WARNING) << "Portal availiability checked before test was complete"; + LOG(WARNING) << "Portal availability checked before test was complete"; return is_portal_available_; }
diff --git a/ui/views/bubble/bubble_dialog_model_host_unittest.cc b/ui/views/bubble/bubble_dialog_model_host_unittest.cc index 4b526b9..95e0b9b 100644 --- a/ui/views/bubble/bubble_dialog_model_host_unittest.cc +++ b/ui/views/bubble/bubble_dialog_model_host_unittest.cc
@@ -91,15 +91,16 @@ menu_item_params.SetIsEnabled(false); ui::DialogModelButton::Params ok_button_params; ok_button_params.SetId(kOkButtonId); + ok_button_params.SetLabel(kOkButtonText); ui::DialogModelButton::Params extra_button_params; extra_button_params.SetId(kExtraButtonId); + extra_button_params.SetLabel(kExtraButtonText); auto host = std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder() .AddMenuItem(ui::ImageModel(), kMenuItemText, base::DoNothing(), menu_item_params) - .AddOkButton(base::DoNothing(), kOkButtonText, ok_button_params) - .AddExtraButton(base::DoNothing(), kExtraButtonText, - extra_button_params) + .AddOkButton(base::DoNothing(), ok_button_params) + .AddExtraButton(base::DoNothing(), extra_button_params) .Build(), anchor_widget->GetContentsView(), BubbleBorder::Arrow::TOP_RIGHT);
diff --git a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html index e7d47e70..513a6b1 100644 --- a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html +++ b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html
@@ -143,6 +143,9 @@ .title-container { display: flex; flex: 1; + font-size: inherit; + font-weight: inherit; + margin: 0; outline: none; } @@ -159,9 +162,9 @@ erroneously played when the user clicks on the outer-most scrollbar. --> <div id="content-wrapper" part="wrapper"> <div class="top-container"> - <div id="title" class="title-container" tabindex="-1"> + <h2 id="title" class="title-container" tabindex="-1"> <slot name="title"></slot> - </div> + </h2> <cr-icon-button id="close" class="icon-clear" hidden$="[[!showCloseButton]]" aria-label$="[[closeText]]" on-click="cancel" on-keypress="onCloseKeypress_">
diff --git a/weblayer/weblayer_resource_exclusions.gni b/weblayer/weblayer_resource_exclusions.gni index 46e87b4..dfebc5e6 100644 --- a/weblayer/weblayer_resource_exclusions.gni +++ b/weblayer/weblayer_resource_exclusions.gni
@@ -16,6 +16,10 @@ # https://crbug.com/1298549 "${_material_package}/layout/m3_auto_complete_simple_item.xml", "${_material_package}/layout/mtrl_auto_complete_simple_item.xml", + + # Referenced by Base.ThemeOverlay.Material3.Dialog. For context: + # https://crbug.com/1392477 + "${_material_package}/layout/m*_alert_*dialog*", ] # Copied from chrome_public_apk_tmpl.gni. @@ -29,8 +33,6 @@ "${_material_package}:[Cc]alendar", "${_material_package}:design_snackbar", "${_material_package}:[Ff]loatingActionButton", - "${_material_package}:[Mm]aterialAlertDialog", - "${_material_package}:mtrl_alert", "${_material_package}:mtrl_slider", "${_material_package}:[Nn]avigationView", "${_material_package}:[Pp]icker",