diff --git a/DEPS b/DEPS index 008d130..c6f547c 100644 --- a/DEPS +++ b/DEPS
@@ -297,7 +297,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': 'f39d68a2adcc5c78642a31db8eabb8bddcbe2e9b', + 'skia_revision': '67b05344b27e685deec98d2b9e658063a1e74585', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -305,11 +305,11 @@ # 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': '3b020cc17e58a6f7b03fa40e2f29c39b30a7b2ee', + 'angle_revision': 'be7084466521cb1b09e4d3bf39f5014e9e73d176', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '16e026a959f1bc80ff237aa81b4a63b52517dec1', + 'swiftshader_revision': '161e7cb70dba2814b01eeff01b178b7cf7510c36', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -368,7 +368,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': '1157c80fa75f5b847d51b20e4c48fd4faadd30fb', + 'catapult_revision': '03071f17662458dfab63504e0b43184aa9e7eaa3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -376,7 +376,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '9a5da0c76dc395d50e903a489c8e08ff28c3f57b', + 'devtools_frontend_revision': '355c426bc8d5f88eabb8e3ad5186a5346efa1b06', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -412,7 +412,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': '0cbf5a922fe7b0b759db48ab07a329645b53e6bd', + 'dawn_revision': '4d1d143977dd4272dc61eb7c3f6fc96f539f77f8', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -1156,7 +1156,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'cdd3bdd509da1f6be93c6f09cf36a282e1062f67', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '4581eca756fd9970fa733e38e54b1097719831d6', 'condition': 'checkout_chromeos', }, @@ -1584,7 +1584,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'e4d93e430c4751cda91e9fb5603154a6d44314fd', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'e19e4f253f28cfb21c5a2c2587c98b77b978bb98', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1715,7 +1715,7 @@ 'dep_type': 'cipd', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@50a58c2a73cb6f66480c8c258af941e1672255dd', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@895da470d97436fefdad6b0b33525b2c2a49e5c3', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1754,7 +1754,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'e88fcf99da482fb22a3f90e0f74bed85d84e0f99', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'ed6b586b62ec93ae82a231b6128f2f7360e663af', + Var('webrtc_git') + '/src.git' + '@' + 'd460c3130957ae599d7c3745964dcb18e0e2950f', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1827,7 +1827,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@50a6daf7c5fa7ef269a1c5161558b0db63b9c60e', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@2d7aa5c114baacc93f52fdc6f5ece99153decf13', 'condition': 'checkout_src_internal', }, @@ -2671,7 +2671,7 @@ 'packages': [ { 'package': 'chromium/third_party/android_deps/libs/com_google_android_material_material', - 'version': 'version:2@1.6.0-alpha01.cr1', + 'version': 'version:2@1.7.0-alpha02.cr1', }, ], 'condition': 'checkout_android',
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContentsStatics.java b/android_webview/java/src/org/chromium/android_webview/AwContentsStatics.java index f973e50b..991c407e 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContentsStatics.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContentsStatics.java
@@ -16,6 +16,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; +import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; import org.chromium.content_public.browser.UiThreadTaskTraits; @@ -183,7 +184,10 @@ * Returns the variations header used with the X-Client-Data header. */ public static String getVariationsHeader() { - return AwContentsStaticsJni.get().getVariationsHeader(); + String header = AwContentsStaticsJni.get().getVariationsHeader(); + RecordHistogram.recordCount100Histogram( + "Android.WebView.VariationsHeaderLength", header.length()); + return header; } @NativeMethods
diff --git a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java index 1477493..46b7026 100644 --- a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java +++ b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java
@@ -337,6 +337,7 @@ + "Android T device with stylus handwriting enabled."), Flag.baseFeature(BlinkFeatures.SCROLL_UPDATE_OPTIMIZATIONS, "Enable scroll update optimizations. See https://crbug.com/1346789."), + Flag.baseFeature(BaseFeatures.ALIGN_WAKE_UPS, "Align delayed wake ups at 125 Hz"), // Add new commandline switches and features above. The final entry should have a // trailing comma for cleaner diffs. };
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/VariationsHeadersTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/VariationsHeadersTest.java index d622ea7..ff20c22 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/VariationsHeadersTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/VariationsHeadersTest.java
@@ -12,6 +12,7 @@ import org.junit.runner.RunWith; import org.chromium.android_webview.AwContentsStatics; +import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.util.CommandLineFlags; /** @@ -27,6 +28,10 @@ @Test public void testGetVariationsHeader() throws Throwable { // Check the value is equal to the base64 encoded proto with the forced variations IDs. - Assert.assertEquals("CAQICggi", AwContentsStatics.getVariationsHeader()); + String expectedHeader = "CAQICggi"; + Assert.assertEquals(expectedHeader, AwContentsStatics.getVariationsHeader()); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + "Android.WebView.VariationsHeaderLength", expectedHeader.length())); } }
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 21655d2c..45d4e4f 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -861,6 +861,8 @@ "shelf/launcher_nudge_controller.h", "shelf/login_shelf_view.cc", "shelf/login_shelf_view.h", + "shelf/login_shelf_widget.cc", + "shelf/login_shelf_widget.h", "shelf/scroll_arrow_view.cc", "shelf/scroll_arrow_view.h", "shelf/scrollable_shelf_constants.cc", @@ -1543,8 +1545,6 @@ "system/power/video_activity_notifier.h", "system/privacy/privacy_indicators_controller.cc", "system/privacy/privacy_indicators_controller.h", - "system/privacy_hub/microphone_privacy_switch_controller.cc", - "system/privacy_hub/microphone_privacy_switch_controller.h", "system/privacy_screen/privacy_screen_feature_pod_controller.cc", "system/privacy_screen/privacy_screen_feature_pod_controller.h", "system/privacy_screen/privacy_screen_toast_controller.cc", @@ -1699,6 +1699,8 @@ "system/unified/custom_shape_button.h", "system/unified/date_tray.cc", "system/unified/date_tray.h", + "system/unified/deferred_update_dialog.cc", + "system/unified/deferred_update_dialog.h", "system/unified/detailed_view_controller.h", "system/unified/feature_pod_button.cc", "system/unified/feature_pod_button.h", @@ -2244,6 +2246,7 @@ "//ash/webui/eche_app_ui/mojom:mojom", "//ash/webui/personalization_app/mojom", "//ash/webui/personalization_app/proto", + "//ash/webui/projector_app/public/cpp", "//base", "//base:i18n", "//base/third_party/dynamic_annotations", @@ -2262,6 +2265,7 @@ "//chromeos/ash/components/dbus/rmad:rmad_proto", "//chromeos/ash/components/dbus/services", "//chromeos/ash/components/dbus/system_clock", + "//chromeos/ash/components/dbus/update_engine", "//chromeos/ash/components/dbus/usb", "//chromeos/ash/components/feature_usage", "//chromeos/ash/components/human_presence", @@ -2853,7 +2857,6 @@ "system/power/power_prefs_unittest.cc", "system/power/power_status_unittest.cc", "system/power/video_activity_notifier_unittest.cc", - "system/privacy_hub/microphone_privacy_switch_controller_unittest.cc", "system/progress_indicator/progress_indicator_animation_registry_unittest.cc", "system/progress_indicator/progress_indicator_unittest.cc", "system/rotation/rotation_lock_feature_pod_controller_unittest.cc",
diff --git a/ash/app_list/app_list_color_provider_impl.cc b/ash/app_list/app_list_color_provider_impl.cc index fe45de8..c85b1ff 100644 --- a/ash/app_list/app_list_color_provider_impl.cc +++ b/ash/app_list/app_list_color_provider_impl.cc
@@ -252,18 +252,6 @@ return ash_color_provider_->GetInkDropBaseColorAndOpacity(bg_color).second; } -SkColor AppListColorProviderImpl::GetInvertedInkDropBaseColor( - SkColor bg_color) const { - return ash_color_provider_->GetInvertedInkDropBaseColorAndOpacity(bg_color) - .first; -} - -float AppListColorProviderImpl::GetInvertedInkDropOpacity( - SkColor bg_color) const { - return ash_color_provider_->GetInvertedInkDropBaseColorAndOpacity(bg_color) - .second; -} - SkColor AppListColorProviderImpl::GetSearchResultViewHighlightColor() const { // Use highlight colors when Dark Light mode is enabled. if (ShouldUseDarkLightColors()) {
diff --git a/ash/app_list/app_list_color_provider_impl.h b/ash/app_list/app_list_color_provider_impl.h index 40419b6..4518d370 100644 --- a/ash/app_list/app_list_color_provider_impl.h +++ b/ash/app_list/app_list_color_provider_impl.h
@@ -46,10 +46,6 @@ SkColor bg_color = gfx::kPlaceholderColor) const override; float GetInkDropOpacity( SkColor bg_color = gfx::kPlaceholderColor) const override; - SkColor GetInvertedInkDropBaseColor( - SkColor bg_color = gfx::kPlaceholderColor) const override; - float GetInvertedInkDropOpacity( - SkColor bg_color = gfx::kPlaceholderColor) const override; SkColor GetSearchResultViewHighlightColor() const override; SkColor GetTextColorURL() const override;
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index 7cbafd3..5d57b95 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -134,10 +134,9 @@ AppsGridView::VisibleItemIndexRange::VisibleItemIndexRange() = default; -AppsGridView::VisibleItemIndexRange::VisibleItemIndexRange( - int input_first_index, - int input_last_index) - : first_index(input_first_index), last_index(input_last_index) {} +AppsGridView::VisibleItemIndexRange::VisibleItemIndexRange(size_t first_index, + size_t last_index) + : first_index(first_index), last_index(last_index) {} AppsGridView::VisibleItemIndexRange::~VisibleItemIndexRange() = default; @@ -766,10 +765,9 @@ return GetItemViewAt(GetModelIndexOfItem(item)); } -AppListItemView* AppsGridView::GetItemViewAt(int index) const { - if (index < 0 || static_cast<size_t>(index) >= view_model_.view_size()) - return nullptr; - return view_model_.view_at(index); +AppListItemView* AppsGridView::GetItemViewAt(size_t index) const { + return (index < view_model_.view_size()) ? view_model_.view_at(index) + : nullptr; } void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView( @@ -1257,7 +1255,7 @@ if (!IsValidIndex(index)) return nullptr; - const int model_index = view_structure_.GetModelIndexFromIndex(index); + const size_t model_index = view_structure_.GetModelIndexFromIndex(index); return GetItemViewAt(model_index); } @@ -2131,7 +2129,7 @@ // Only show the visible items during animation to reduce the cost of painting // that is triggered by view bounds changes due to reorder. - for (int visible_view_index = range->first_index; + for (size_t visible_view_index = range->first_index; visible_view_index <= range->last_index; ++visible_view_index) { view_model_.view_at(visible_view_index)->SetVisible(true); } @@ -2158,7 +2156,7 @@ // The row of the first visible item. const int base_row = range->first_index / cols_; - for (int visible_view_index = range->first_index; + for (size_t visible_view_index = range->first_index; visible_view_index <= range->last_index; ++visible_view_index) { // Calculate translate offset for each view. NOTE: The items on the // different rows have different fade in offsets. The ratio between the @@ -2215,7 +2213,7 @@ .SetDuration(base::Milliseconds(300)); // Animate each row of app icons with a different offset. - for (int item_index = range->first_index; item_index <= range->last_index; + for (size_t item_index = range->first_index; item_index <= range->last_index; ++item_index) { const int row_index = item_index / cols_; @@ -2514,7 +2512,7 @@ GetItemViewAt(i)->CancelContextMenu(); } -void AppsGridView::DeleteItemViewAtIndex(int index) { +void AppsGridView::DeleteItemViewAtIndex(size_t index) { AppListItemView* item_view = GetItemViewAt(index); view_model_.Remove(index); view_structure_.Remove(item_view); @@ -2623,8 +2621,8 @@ // The item is updated in the item list but the view_model is not updated, // so get current model index by looking up view_model and predict the // target model index based on its current item index. - int from_model_index = GetModelIndexOfItem(item); - int to_model_index = GetTargetModelIndexFromItemIndex(to_index); + size_t from_model_index = GetModelIndexOfItem(item); + size_t to_model_index = GetTargetModelIndexFromItemIndex(to_index); view_model_.Move(from_model_index, to_model_index); items_container_->ReorderChildView(view_model_.view_at(to_model_index), to_model_index); @@ -3005,21 +3003,21 @@ return view_structure_.IsValidReorderTargetIndex(index); } -int AppsGridView::GetModelIndexOfItem(const AppListItem* item) const { +size_t AppsGridView::GetModelIndexOfItem(const AppListItem* item) const { const auto& entries = view_model_.entries(); const auto iter = std::find_if(entries.begin(), entries.end(), [item](const auto& entry) { return static_cast<AppListItemView*>(entry.view)->item() == item; }); - return std::distance(entries.begin(), iter); + return static_cast<size_t>(std::distance(entries.begin(), iter)); } -int AppsGridView::GetTargetModelIndexFromItemIndex(size_t item_index) { +size_t AppsGridView::GetTargetModelIndexFromItemIndex(size_t item_index) { if (folder_delegate_) return item_index; CHECK(item_index <= item_list_->item_count()); - int target_model_index = 0; + size_t target_model_index = 0; for (size_t i = 0; i < item_index; ++i) { if (!item_list_->item_at(i)->is_page_break()) ++target_model_index;
diff --git a/ash/app_list/views/apps_grid_view.h b/ash/app_list/views/apps_grid_view.h index c5b6550..6533a6b 100644 --- a/ash/app_list/views/apps_grid_view.h +++ b/ash/app_list/views/apps_grid_view.h
@@ -200,7 +200,7 @@ // Returns the item view of the item at |index|, or nullptr if there is no // view at |index|. - AppListItemView* GetItemViewAt(int index) const; + AppListItemView* GetItemViewAt(size_t index) const; // Called to initiate drag for reparenting a folder item in root level grid // view. @@ -382,14 +382,14 @@ struct VisibleItemIndexRange { VisibleItemIndexRange(); - VisibleItemIndexRange(int first_index, int last_index); + VisibleItemIndexRange(size_t first_index, size_t last_index); ~VisibleItemIndexRange(); // The view index of the first visible item on the apps grid. - int first_index = 0; + size_t first_index = 0; // The view index of the last visible item on the apps grid. - int last_index = 0; + size_t last_index = 0; }; // The duration in ms for most of the apps grid view animations. @@ -730,7 +730,7 @@ // Removes the AppListItemView at |index| in |view_model_|, removes it from // view structure as well and deletes it. - void DeleteItemViewAtIndex(int index); + void DeleteItemViewAtIndex(size_t index); // Returns true if |point| lies within the bounds of this grid view plus a // buffer area surrounding it that can trigger drop target change. @@ -835,12 +835,12 @@ bool IsValidReorderTargetIndex(const GridIndex& index) const; // Returns model index of the item view of the specified item. - int GetModelIndexOfItem(const AppListItem* item) const; + size_t GetModelIndexOfItem(const AppListItem* item) const; // Returns the target model index based on item index. (Item index is the // index of an item in item list.) This should be used when the item is // updated in item list but its item view has not been updated in view model. - int GetTargetModelIndexFromItemIndex(size_t item_index); + size_t GetTargetModelIndexFromItemIndex(size_t item_index); // Returns the target GridIndex for a keyboard move. GridIndex GetTargetGridIndexForKeyboardMove(ui::KeyboardCode key_code) const;
diff --git a/ash/app_list/views/scrollable_apps_grid_view_unittest.cc b/ash/app_list/views/scrollable_apps_grid_view_unittest.cc index 622dd5e..ecbf36a2 100644 --- a/ash/app_list/views/scrollable_apps_grid_view_unittest.cc +++ b/ash/app_list/views/scrollable_apps_grid_view_unittest.cc
@@ -150,7 +150,7 @@ } // Verifies the visible item index range. - bool IsIndexRangeExpected(int first_index, int last_index) { + bool IsIndexRangeExpected(size_t first_index, size_t last_index) { const absl::optional<AppsGridView::VisibleItemIndexRange> index_range = apps_grid_view_->GetVisibleItemIndexRange();
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 1e22bb1..bcdccdd 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -773,9 +773,18 @@ <message name="IDS_UPDATE_NOTIFICATION_RESTART_BUTTON" meaning="button label" desc="The label used as the button to restart system and update. Displayed as the action button of the notification for system update."> Restart to update </message> + <message name="IDS_UPDATE_NOTIFICATION_APPLY_UPDATE_BUTTON" meaning="button label" desc="The label used as the button to apply deferred update. Displayed as the action button of the notification for deferred system update."> + Update + </message> + <message name="IDS_UPDATE_NOTIFICATION_AUTOMATIC_UPDATE_BUTTON" meaning="button label" desc="The label used as the button to take users to the settings page with the automatic update toggle. Displayed as the action button of the notification for deferred system update."> + Automatic updates + </message> <message name="IDS_ROLLBACK_NOTIFICATION_RESTART_BUTTON" meaning="button label" desc="The label used as the button to restart system to rollback. Displayed as the action button of the notification for system rollback."> Reset </message> + <message name="IDS_UPDATE_NOTIFICATION_MESSAGE_DEFERRED_UPDATE" desc="The notification message used in the system notification update when update is downloaded but deferred."> + Get the latest features and security improvements. Updates happen in the background. + </message> <message name="IDS_UPDATE_NOTIFICATION_MESSAGE_POWERWASH" desc="The notification message used in the system notification update when user need to powerwash the device in order to update the system."> This update requires powerwashing your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph>. All data will be deleted. Learn more about the latest <ph name="SYSTEM_APP_NAME">$2<ex>ChromiumOS</ex></ph> update. </message> @@ -5097,6 +5106,28 @@ Can't stream apps in tablet mode. Try again in laptop mode. </message> + <!-- Deferred update dialog --> + <message name="IDS_DEFERRED_UPDATE_DIALOG_TITLE" desc="Title of the dialog for notifying deferred update available to be applied."> + Update available + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_TEXT" desc="Content of the dialog for notifying deferred update available."> + Get the latest features and security improvements. If you decline this update, your device may no longer work properly and you may experience security and performance issues. + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_CHECKBOX" desc="Checkbox to enable automatic updates."> + Get automatic updates + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_SIGN_OUT" desc="Sign out button."> + Sign out + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SIGN_OUT" desc="Update and sign out button."> + Update and sign out + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_SHUT_DOWN" desc="Shut down button."> + Shut down + </message> + <message name="IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SHUT_DOWN" desc="Update and shut down button."> + Update and shut down + </message> </messages> </release> </grit>
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_CHECKBOX.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_CHECKBOX.png.sha1 new file mode 100644 index 0000000..2a29a35 --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_CHECKBOX.png.sha1
@@ -0,0 +1 @@ +053af48070064f9322cbbb6b665973678fa70529 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SHUT_DOWN.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SHUT_DOWN.png.sha1 new file mode 100644 index 0000000..2a29a35 --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SHUT_DOWN.png.sha1
@@ -0,0 +1 @@ +053af48070064f9322cbbb6b665973678fa70529 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SIGN_OUT.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SIGN_OUT.png.sha1 new file mode 100644 index 0000000..132c4bd --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_SIGN_OUT.png.sha1
@@ -0,0 +1 @@ +7297dcb774c6c59965b66c1f34b8d43db255c5cc \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TEXT.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TEXT.png.sha1 new file mode 100644 index 0000000..2a29a35 --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TEXT.png.sha1
@@ -0,0 +1 @@ +053af48070064f9322cbbb6b665973678fa70529 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TITLE.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TITLE.png.sha1 new file mode 100644 index 0000000..2a29a35 --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_TITLE.png.sha1
@@ -0,0 +1 @@ +053af48070064f9322cbbb6b665973678fa70529 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SHUT_DOWN.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SHUT_DOWN.png.sha1 new file mode 100644 index 0000000..2a29a35 --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SHUT_DOWN.png.sha1
@@ -0,0 +1 @@ +053af48070064f9322cbbb6b665973678fa70529 \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SIGN_OUT.png.sha1 b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SIGN_OUT.png.sha1 new file mode 100644 index 0000000..132c4bd --- /dev/null +++ b/ash/ash_strings_grd/IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SIGN_OUT.png.sha1
@@ -0,0 +1 @@ +7297dcb774c6c59965b66c1f34b8d43db255c5cc \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_APPLY_UPDATE_BUTTON.png.sha1 b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_APPLY_UPDATE_BUTTON.png.sha1 new file mode 100644 index 0000000..54f31da2 --- /dev/null +++ b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_APPLY_UPDATE_BUTTON.png.sha1
@@ -0,0 +1 @@ +066986453af2cd1dee319ee0128a03aa1faec13c \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_AUTOMATIC_UPDATE_BUTTON.png.sha1 b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_AUTOMATIC_UPDATE_BUTTON.png.sha1 new file mode 100644 index 0000000..54f31da2 --- /dev/null +++ b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_AUTOMATIC_UPDATE_BUTTON.png.sha1
@@ -0,0 +1 @@ +066986453af2cd1dee319ee0128a03aa1faec13c \ No newline at end of file
diff --git a/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_MESSAGE_DEFERRED_UPDATE.png.sha1 b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_MESSAGE_DEFERRED_UPDATE.png.sha1 new file mode 100644 index 0000000..54f31da2 --- /dev/null +++ b/ash/ash_strings_grd/IDS_UPDATE_NOTIFICATION_MESSAGE_DEFERRED_UPDATE.png.sha1
@@ -0,0 +1 @@ +066986453af2cd1dee319ee0128a03aa1faec13c \ No newline at end of file
diff --git a/ash/assistant/ui/base/assistant_button.cc b/ash/assistant/ui/base/assistant_button.cc index fa2c64442..f52fdfe 100644 --- a/ash/assistant/ui/base/assistant_button.cc +++ b/ash/assistant/ui/base/assistant_button.cc
@@ -7,12 +7,15 @@ #include "ash/assistant/model/assistant_ui_model.h" #include "ash/assistant/ui/base/assistant_button_listener.h" #include "ash/assistant/util/histogram_util.h" +#include "ash/constants/ash_features.h" #include "ash/public/cpp/assistant/controller/assistant_ui_controller.h" -#include "ash/public/cpp/style/color_provider.h" #include "ash/public/cpp/style/scoped_light_mode_as_default.h" +#include "ash/style/ash_color_id.h" +#include "ash/style/style_util.h" #include "base/bind.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" @@ -54,7 +57,6 @@ SetHasInkDropActionOnClick(true); views::InkDrop::UseInkDropForFloodFillRipple(views::InkDrop::Get(this), /*highlight_on_hover=*/false); - UpdateInkDropColors(); views::InstallCircleHighlightPathGenerator(this, gfx::Insets(kInkDropInset)); // Image. @@ -145,7 +147,17 @@ void AssistantButton::OnThemeChanged() { views::View::OnThemeChanged(); - UpdateInkDropColors(); + // Updates inkdrop color and opacity. + const bool is_enabled = features::IsProductivityLauncherEnabled(); + const bool base_color = + is_enabled ? GetColorProvider()->GetColor(kColorAshInkDropOpaqueColor) + : SK_ColorBLACK; + const float opacity = is_enabled ? StyleUtil::GetInkDropOpacity() + : StyleUtil::kDarkInkDropOpacity; + + auto* ink_drop = views::InkDrop::Get(this); + ink_drop->SetBaseColor(base_color); + ink_drop->SetVisibleOpacity(opacity); if (!icon_color_type_.has_value() || !icon_description_.has_value()) return; @@ -162,15 +174,6 @@ listener_->OnButtonPressed(id_); } -void AssistantButton::UpdateInkDropColors() { - ScopedAssistantLightModeAsDefault scoped_assistant_light_mode_as_default; - - std::pair<SkColor, float> base_color_and_opacity = - ColorProvider::Get()->GetInkDropBaseColorAndOpacity(); - views::InkDrop::Get(this)->SetBaseColor(base_color_and_opacity.first); - views::InkDrop::Get(this)->SetVisibleOpacity(base_color_and_opacity.second); -} - BEGIN_METADATA(AssistantButton, views::ImageButton) END_METADATA
diff --git a/ash/assistant/ui/base/assistant_button.h b/ash/assistant/ui/base/assistant_button.h index c3d127e3c..a2043501 100644 --- a/ash/assistant/ui/base/assistant_button.h +++ b/ash/assistant/ui/base/assistant_button.h
@@ -87,7 +87,6 @@ private: void OnButtonPressed(); - void UpdateInkDropColors(); AssistantButtonListener* listener_; const AssistantButtonId id_;
diff --git a/ash/assistant/ui/base/assistant_button_unittest.cc b/ash/assistant/ui/base/assistant_button_unittest.cc index a4b9d83b..eb5a9d9 100644 --- a/ash/assistant/ui/base/assistant_button_unittest.cc +++ b/ash/assistant/ui/base/assistant_button_unittest.cc
@@ -132,9 +132,11 @@ params.accessible_name_id = IDS_ASH_ASSISTANT_DIALOG_PLATE_KEYBOARD_ACCNAME; params.icon_color_type = ColorProvider::ContentLayerType::kIconColorPrimary; - std::unique_ptr<AssistantButton> button = AssistantButton::Create( - nullptr, vector_icons::kKeyboardIcon, - AssistantButtonId::kKeyboardInputToggle, std::move(params)); + std::unique_ptr<views::Widget> widget = CreateTestWidget(); + AssistantButton* button = + widget->GetContentsView()->AddChildView(AssistantButton::Create( + nullptr, vector_icons::kKeyboardIcon, + AssistantButtonId::kKeyboardInputToggle, std::move(params))); const SkBitmap light_mode_expected_image = *gfx::CreateVectorIcon(vector_icons::kKeyboardIcon, kIconSizeInDip, @@ -156,10 +158,6 @@ dark_light_mode_controller->ToggleColorMode(); const bool dark_mode_status = dark_light_mode_controller->IsDarkModeEnabled(); ASSERT_NE(initial_dark_mode_status, dark_mode_status); - - // Manually triggers OnThemeChanged as the button is not attached to an UI - // tree. - button->OnThemeChanged(); EXPECT_TRUE(gfx::test::AreBitmapsEqual( dark_mode_status ? dark_mode_expected_image : light_mode_expected_image, *button->GetImage(views::Button::STATE_NORMAL).bitmap()));
diff --git a/ash/clipboard/views/clipboard_history_main_button.cc b/ash/clipboard/views/clipboard_history_main_button.cc index 266fb3ea..df05c4b1 100644 --- a/ash/clipboard/views/clipboard_history_main_button.cc +++ b/ash/clipboard/views/clipboard_history_main_button.cc
@@ -5,23 +5,18 @@ #include "ash/clipboard/views/clipboard_history_main_button.h" #include "ash/clipboard/views/clipboard_history_item_view.h" +#include "ash/constants/ash_features.h" #include "ash/public/cpp/style/scoped_light_mode_as_default.h" -#include "ash/style/ash_color_provider.h" +#include "ash/style/ash_color_id.h" #include "ash/style/style_util.h" #include "base/bind.h" +#include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/controls/focus_ring.h" namespace ash { -namespace { - -// The menu background's color type. -constexpr ash::AshColorProvider::BaseLayerType kMenuBackgroundColorType = - ash::AshColorProvider::BaseLayerType::kOpaque; - -} // namespace ClipboardHistoryMainButton::ClipboardHistoryMainButton( ClipboardHistoryItemView* container) @@ -110,22 +105,21 @@ if (!should_highlight_) return; - // Use the light mode as default because the light mode is the default mode - // of the native theme which decides the context menu's background color. - // TODO(andrewxu): remove this line after https://crbug.com/1143009 is - // fixed. - ScopedLightModeAsDefault scoped_light_mode_as_default; - // Highlight the background when the menu item is selected or pressed. cc::PaintFlags flags; flags.setAntiAlias(true); - auto* color_provider = AshColorProvider::Get(); - const std::pair<SkColor, float> base_color_and_opacity = - color_provider->GetInkDropBaseColorAndOpacity( - color_provider->GetBaseLayerColor(kMenuBackgroundColorType)); - flags.setColor(SkColorSetA(base_color_and_opacity.first, - base_color_and_opacity.second * 0xFF)); + // Use the color in light mode when dark/light mode is not enabled. As the + // background color of the context menu is from NativeTheme when the feature + // is not enabled, and light mode is the default color of NativeTheme. If + // dark/light mode is enabled, the background color of the context menus + // inside SystemUI will be overridden to align with current system color mode. + const SkColor color = + features::IsDarkLightModeEnabled() + ? GetColorProvider()->GetColor(kColorAshInkDrop) + : SkColorSetA(SK_ColorBLACK, + StyleUtil::kLightInkDropOpacity * SK_AlphaOPAQUE); + flags.setColor(color); flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawRect(GetLocalBounds(), flags); }
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 426c4ae..c0e4d599 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -1370,6 +1370,11 @@ const base::Feature kSettingsAppThemeChangeAnimation{ "SettingsAppThemeChangeAnimation", base::FEATURE_DISABLED_BY_DEFAULT}; +// Whether we should track auto-hide preferences separately between clamshell +// and tablet. +const base::Feature kShelfAutoHideSeparation{"ShelfAutoHideSeparation", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables shelf gestures (swipe to show hotseat, swipe to go home or overview) // in tablet mode when virtual keyboard is shown. const base::Feature kShelfGesturesWithVirtualKeyboard{
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index 3291eec62..203c130 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -554,6 +554,8 @@ COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSettingsAppThemeChangeAnimation; COMPONENT_EXPORT(ASH_CONSTANTS) +extern const base::Feature kShelfAutoHideSeparation; +COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShelfGesturesWithVirtualKeyboard; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShelfLauncherNudge; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShelfParty;
diff --git a/ash/frame/caption_buttons/frame_size_button_unittest.cc b/ash/frame/caption_buttons/frame_size_button_unittest.cc index 404e433..e718602 100644 --- a/ash/frame/caption_buttons/frame_size_button_unittest.cc +++ b/ash/frame/caption_buttons/frame_size_button_unittest.cc
@@ -587,45 +587,14 @@ EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); } -// FrameSizeButtonPortraitDisplayTest is parameterized to run with and without -// the feature |features::kVerticalSnap|, which allows users to snap top and -// bottom in portrait layout, affecting snap icons. -class FrameSizeButtonPortraitDisplayTest - : public FrameSizeButtonTest, - public ::testing::WithParamInterface<bool> { - public: - FrameSizeButtonPortraitDisplayTest() = default; - - FrameSizeButtonPortraitDisplayTest( - const FrameSizeButtonPortraitDisplayTest&) = delete; - FrameSizeButtonPortraitDisplayTest& operator=( - const FrameSizeButtonPortraitDisplayTest&) = delete; - - ~FrameSizeButtonPortraitDisplayTest() override = default; - - // FrameSizeButtonTest: - void SetUp() override { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); - } else { - scoped_feature_list_.InitAndDisableFeature( - chromeos::wm::features::kVerticalSnap); - } - FrameSizeButtonTest::SetUp(); - UpdateDisplay("600x800"); - } - - protected: - bool IsVerticalSnapEnabled() const { return GetParam(); } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; +// FrameSizeButtonPortraitDisplayTest is used to test functionalities to snap +// top and bottom in portrait layout, affecting snap icons. +using FrameSizeButtonPortraitDisplayTest = FrameSizeButtonTest; // Test that upon pressed the size button should show left and right arrows for // horizontal snap and upward and downward arrow for vertical snap. -TEST_P(FrameSizeButtonPortraitDisplayTest, SnapButtons) { +TEST_F(FrameSizeButtonPortraitDisplayTest, SnapButtons) { + UpdateDisplay("600x800"); FrameCaptionButtonContainerView* container = widget_delegate()->caption_button_container(); views::Widget* widget = widget_delegate()->GetWidget(); @@ -650,12 +619,9 @@ EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED, close_button()->GetIcon()); - const gfx::VectorIcon* left_icon = - IsVerticalSnapEnabled() ? &chromeos::kWindowControlTopSnappedIcon - : &chromeos::kWindowControlLeftSnappedIcon; + const gfx::VectorIcon* left_icon = &chromeos::kWindowControlTopSnappedIcon; const gfx::VectorIcon* right_icon = - IsVerticalSnapEnabled() ? &chromeos::kWindowControlBottomSnappedIcon - : &chromeos::kWindowControlRightSnappedIcon; + &chromeos::kWindowControlBottomSnappedIcon; EXPECT_TRUE(left_icon->name == minimize_button()->icon_definition_for_test()->name); @@ -780,8 +746,4 @@ EXPECT_TRUE(window_state()->IsFullscreen()); } -INSTANTIATE_TEST_SUITE_P(All, - FrameSizeButtonPortraitDisplayTest, - ::testing::Bool()); - } // namespace ash
diff --git a/ash/login/ui/lock_contents_view.cc b/ash/login/ui/lock_contents_view.cc index 4c305c9..28412187 100644 --- a/ash/login/ui/lock_contents_view.cc +++ b/ash/login/ui/lock_contents_view.cc
@@ -42,6 +42,7 @@ #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/login_shelf_view.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" @@ -1670,7 +1671,10 @@ ->status_area_widget_delegate() ->set_default_last_focusable_child(reverse); Shell::Get()->focus_cycler()->FocusWidget(shelf->GetStatusAreaWidget()); - } else if (!features::IsUseLoginShelfWidgetEnabled()) { + } else if (features::IsUseLoginShelfWidgetEnabled()) { + shelf->login_shelf_widget()->SetDefaultLastFocusableChild(reverse); + Shell::Get()->focus_cycler()->FocusWidget(shelf->login_shelf_widget()); + } else { shelf->shelf_widget()->set_default_last_focusable_child(reverse); Shell::Get()->focus_cycler()->FocusWidget(shelf->shelf_widget()); }
diff --git a/ash/login/ui/lock_screen_sanity_unittest.cc b/ash/login/ui/lock_screen_sanity_unittest.cc index 6a0671c..ca32155 100644 --- a/ash/login/ui/lock_screen_sanity_unittest.cc +++ b/ash/login/ui/lock_screen_sanity_unittest.cc
@@ -14,6 +14,7 @@ #include "ash/login/ui/login_test_utils.h" #include "ash/root_window_controller.h" #include "ash/session/test_session_controller_client.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" @@ -39,8 +40,11 @@ views::View* GetLoginShelfContentsView(gfx::NativeWindow native_window) { // TODO(https://crbug.com/1343114): refactor the code below after the login // shelf widget is ready. + Shelf* shelf = Shelf::ForWindow(native_window); + if (features::IsUseLoginShelfWidgetEnabled()) + return shelf->login_shelf_widget()->GetContentsView(); - return Shelf::ForWindow(native_window)->shelf_widget()->GetContentsView(); + return shelf->shelf_widget()->GetContentsView(); } class LockScreenAppFocuser { @@ -196,7 +200,7 @@ SetUserCount(1); std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(lock); views::View* login_shelf_contents_view = - GetLoginShelfContentsView(lock->GetWidget()->GetNativeView()); + GetLoginShelfContentsView(lock->GetWidget()->GetNativeWindow()); // Lock has focus. EXPECT_TRUE(VerifyFocused(lock)); @@ -260,7 +264,7 @@ std::unique_ptr<views::Widget> widget = CreateWidgetWithContent(lock); views::View* login_shelf_contents_view = - GetLoginShelfContentsView((lock->GetWidget()->GetNativeView())); + GetLoginShelfContentsView((lock->GetWidget()->GetNativeWindow())); views::View* status_area = RootWindowController::ForWindow(lock->GetWidget()->GetNativeWindow())
diff --git a/ash/projector/projector_metadata_controller.cc b/ash/projector/projector_metadata_controller.cc index a27a080..3e51770 100644 --- a/ash/projector/projector_metadata_controller.cc +++ b/ash/projector/projector_metadata_controller.cc
@@ -8,6 +8,7 @@ #include "ash/projector/projector_ui_controller.h" #include "ash/public/cpp/projector/projector_controller.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/webui/projector_app/public/cpp/projector_app_constants.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/logging.h"
diff --git a/ash/public/cpp/app_list/app_list_color_provider.h b/ash/public/cpp/app_list/app_list_color_provider.h index 4efc5a12..2ab1352 100644 --- a/ash/public/cpp/app_list/app_list_color_provider.h +++ b/ash/public/cpp/app_list/app_list_color_provider.h
@@ -55,10 +55,6 @@ SkColor bg_color = gfx::kPlaceholderColor) const = 0; virtual float GetInkDropOpacity( SkColor bg_color = gfx::kPlaceholderColor) const = 0; - virtual SkColor GetInvertedInkDropBaseColor( - SkColor bg_color = gfx::kPlaceholderColor) const = 0; - virtual float GetInvertedInkDropOpacity( - SkColor bg_color = gfx::kPlaceholderColor) const = 0; virtual SkColor GetSearchResultViewHighlightColor() const = 0; virtual SkColor GetTextColorURL() const = 0;
diff --git a/ash/public/cpp/projector/projector_controller.h b/ash/public/cpp/projector/projector_controller.h index d0d164a..19c2f3e 100644 --- a/ash/public/cpp/projector/projector_controller.h +++ b/ash/public/cpp/projector/projector_controller.h
@@ -13,10 +13,6 @@ struct NewScreencastPrecondition; -// File extension of Projector metadata file. It is used to identify Projector -// screencasts at processing pending screencasts and fetching screencast list. -constexpr char kProjectorMetadataFileExtension[] = "projector"; - class ProjectorClient; // Enum class used to notify the ProjectorController on the availability of
diff --git a/ash/public/cpp/style/color_provider.h b/ash/public/cpp/style/color_provider.h index add928a..38e2300 100644 --- a/ash/public/cpp/style/color_provider.h +++ b/ash/public/cpp/style/color_provider.h
@@ -167,14 +167,11 @@ // Gets the ink drop base color and opacity. Since the inkdrop ripple and // highlight have the same opacity, we are keeping only one opacity here. The // base color will be gotten based on current color mode, which will be WHITE - // in dark mode and BLACK in light mode. Some parts of the UI use inverted - // ink drop colors which will be BLACK in dark mode and WHITE in light mode. - // Please provide `background_color` if different base color needed on current - // color mode. See more details of IsDarkModeEnabled for current color mode. + // in dark mode and BLACK in light mode. Please provide `background_color` if + // different base color needed on current color mode. See more details of + // IsDarkModeEnabled for current color mode. virtual std::pair<SkColor, float> GetInkDropBaseColorAndOpacity( SkColor background_color = gfx::kPlaceholderColor) const = 0; - virtual std::pair<SkColor, float> GetInvertedInkDropBaseColorAndOpacity( - SkColor background_color = gfx::kPlaceholderColor) const = 0; protected: ColorProvider();
diff --git a/ash/public/cpp/system_tray.h b/ash/public/cpp/system_tray.h index 28fd43d..5d41542 100644 --- a/ash/public/cpp/system_tray.h +++ b/ash/public/cpp/system_tray.h
@@ -94,6 +94,10 @@ // when a new update starts before the current update is applied. virtual void ResetUpdateState() = 0; + // Shows an icon in the system tray which indicates that a update is + // downloaded but deferred. + virtual void SetUpdateDeferred(bool deferred) = 0; + // If |visible| is true, shows an icon in the system tray which indicates that // a software update is available but user's agreement is required as current // connection is cellular. If |visible| is false, hides the icon because the
diff --git a/ash/public/cpp/system_tray_client.h b/ash/public/cpp/system_tray_client.h index 646b681..b099bbd 100644 --- a/ash/public/cpp/system_tray_client.h +++ b/ash/public/cpp/system_tray_client.h
@@ -80,6 +80,9 @@ // loaded. virtual void ShowAboutChromeOS() = 0; + // Shows the about chrome OS additional details page. + virtual void ShowAboutChromeOSDetails() = 0; + // Shows accessibility help. virtual void ShowAccessibilityHelp() = 0;
diff --git a/ash/public/cpp/test/test_app_list_color_provider.cc b/ash/public/cpp/test/test_app_list_color_provider.cc index 0f18815..becc3bd 100644 --- a/ash/public/cpp/test/test_app_list_color_provider.cc +++ b/ash/public/cpp/test/test_app_list_color_provider.cc
@@ -124,16 +124,6 @@ return 0.08f; } -SkColor TestAppListColorProvider::GetInvertedInkDropBaseColor( - SkColor bg_color) const { - return SK_ColorBLACK; -} - -float TestAppListColorProvider::GetInvertedInkDropOpacity( - SkColor bg_color) const { - return 0.06f; -} - SkColor TestAppListColorProvider::GetSearchResultViewHighlightColor() const { return SkColorSetA(SK_ColorWHITE, 0x0D); }
diff --git a/ash/public/cpp/test/test_app_list_color_provider.h b/ash/public/cpp/test/test_app_list_color_provider.h index 9aa7ed2..dbeceea 100644 --- a/ash/public/cpp/test/test_app_list_color_provider.h +++ b/ash/public/cpp/test/test_app_list_color_provider.h
@@ -46,10 +46,6 @@ SkColor bg_color = gfx::kPlaceholderColor) const override; float GetInkDropOpacity( SkColor bg_color = gfx::kPlaceholderColor) const override; - SkColor GetInvertedInkDropBaseColor( - SkColor bg_color = gfx::kPlaceholderColor) const override; - float GetInvertedInkDropOpacity( - SkColor bg_color = gfx::kPlaceholderColor) const override; SkColor GetSearchResultViewHighlightColor() const override; SkColor GetTextColorURL() const override; };
diff --git a/ash/public/cpp/test/test_system_tray_client.cc b/ash/public/cpp/test/test_system_tray_client.cc index 49284e6..3810f40 100644 --- a/ash/public/cpp/test/test_system_tray_client.cc +++ b/ash/public/cpp/test/test_system_tray_client.cc
@@ -54,6 +54,8 @@ void TestSystemTrayClient::ShowAboutChromeOS() {} +void TestSystemTrayClient::ShowAboutChromeOSDetails() {} + void TestSystemTrayClient::ShowAccessibilityHelp() {} void TestSystemTrayClient::ShowAccessibilitySettings() {}
diff --git a/ash/public/cpp/test/test_system_tray_client.h b/ash/public/cpp/test/test_system_tray_client.h index 4eb3398..38a9796 100644 --- a/ash/public/cpp/test/test_system_tray_client.h +++ b/ash/public/cpp/test/test_system_tray_client.h
@@ -41,6 +41,7 @@ void ShowTetherNetworkSettings() override; void ShowWifiSyncSettings() override; void ShowAboutChromeOS() override; + void ShowAboutChromeOSDetails() override; void ShowAccessibilityHelp() override; void ShowAccessibilitySettings() override; void ShowGestureEducationHelp() override;
diff --git a/ash/shelf/assistant_overlay.cc b/ash/shelf/assistant_overlay.cc index 4194c6d..3fea10d 100644 --- a/ash/shelf/assistant_overlay.cc +++ b/ash/shelf/assistant_overlay.cc
@@ -16,7 +16,7 @@ #include "ash/shelf/shelf_view.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" -#include "ash/style/ash_color_provider.h" +#include "ash/style/ash_color_id.h" #include "ash/system/tray/tray_popup_utils.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/command_line.h" @@ -69,9 +69,8 @@ AssistantOverlay::AssistantOverlay(HomeButton* host_view) : ripple_layer_(std::make_unique<ui::Layer>()), host_view_(host_view), - circle_layer_delegate_( - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity().first, - kRippleCircleInitRadiusDip) { + circle_layer_delegate_(gfx::kPlaceholderColor, + kRippleCircleInitRadiusDip) { SetPaintToLayer(ui::LAYER_NOT_DRAWN); layer()->SetName("AssistantOverlay:ROOT_LAYER"); layer()->SetMasksToBounds(false); @@ -215,7 +214,7 @@ void AssistantOverlay::OnThemeChanged() { views::View::OnThemeChanged(); circle_layer_delegate_.set_color( - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity().first); + GetColorProvider()->GetColor(kColorAshInkDropOpaqueColor)); SchedulePaint(); }
diff --git a/ash/shelf/home_button.cc b/ash/shelf/home_button.cc index 3e9e2c1..fa60b95 100644 --- a/ash/shelf/home_button.cc +++ b/ash/shelf/home_button.cc
@@ -17,6 +17,7 @@ #include "ash/shelf/shelf_view.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/style/ash_color_id.h" #include "ash/style/ash_color_provider.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/check_op.h" @@ -361,7 +362,7 @@ ShelfControlButton::OnThemeChanged(); if (ripple_layer_delegate_) { ripple_layer_delegate_->set_color( - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity().first); + GetColorProvider()->GetColor(kColorAshInkDropOpaqueColor)); } if (label_container_) { label_container_->layer()->SetColor( @@ -422,8 +423,10 @@ ui::Layer* ripple_layer = nudge_ripple_layer_.layer(); float ripple_diameter = ShelfControlButton::CalculatePreferredSize().width(); + auto* color_provider = GetColorProvider(); + DCHECK(color_provider); ripple_layer_delegate_ = std::make_unique<views::CircleLayerDelegate>( - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity().first, + color_provider->GetColor(kColorAshInkDropOpaqueColor), /*radius=*/ripple_diameter / 2); // The bounds are set with respect to |shelf_container_layer| stated below.
diff --git a/ash/shelf/login_shelf_view.cc b/ash/shelf/login_shelf_view.cc index 899ddb2c..7c6da6d 100644 --- a/ash/shelf/login_shelf_view.cc +++ b/ash/shelf/login_shelf_view.cc
@@ -890,6 +890,8 @@ return; } + + const gfx::Size old_preferred_size = GetPreferredSize(); bool show_reboot = Shell::Get()->shutdown_controller()->reboot_on_shutdown(); mojom::TrayActionState tray_action_state = Shell::Get()->tray_action()->GetLockScreenNoteState(); @@ -962,7 +964,16 @@ SetFocusBehavior(is_anything_focusable ? views::View::FocusBehavior::ALWAYS : views::View::FocusBehavior::NEVER); UpdateButtonsColors(); - Layout(); + + // When the login shelf view is moved to its own widget, the login shelf + // widget needs to change the size according to the login shelf view's + // preferred size. + if (old_preferred_size != GetPreferredSize() && + features::IsUseLoginShelfWidgetEnabled()) { + PreferredSizeChanged(); + } else { + Layout(); + } } void LoginShelfView::UpdateButtonsColors() {
diff --git a/ash/shelf/login_shelf_view_unittest.cc b/ash/shelf/login_shelf_view_unittest.cc index 386f033..dd620b55 100644 --- a/ash/shelf/login_shelf_view_unittest.cc +++ b/ash/shelf/login_shelf_view_unittest.cc
@@ -22,6 +22,7 @@ #include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/session/test_session_controller_client.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_navigation_widget.h" #include "ash/shelf/shelf_shutdown_confirmation_bubble.h" @@ -164,21 +165,30 @@ // TODO(https://crbug.com/1343114): refactor the code below after the login // shelf widget is ready. - ShelfWidget* shelf_widget = GetLoginShelfWidget(); - shelf_widget->set_default_last_focusable_child( - /*default_last_focusable_child=*/false); - Shell::Get()->focus_cycler()->FocusWidget(shelf_widget); - ExpectFocused(shelf_widget->GetContentsView()); + views::Widget* login_shelf_widget = GetLoginShelfWidget(); + if (features::IsUseLoginShelfWidgetEnabled()) { + static_cast<LoginShelfWidget*>(login_shelf_widget) + ->SetDefaultLastFocusableChild(/*reverse=*/false); + } else { + static_cast<ShelfWidget*>(login_shelf_widget) + ->set_default_last_focusable_child( + /*default_last_focusable_child=*/false); + } + + Shell::Get()->focus_cycler()->FocusWidget(login_shelf_widget); + ExpectFocused(login_shelf_widget->GetContentsView()); } // Returns the widget where the login shelf view lives. - ShelfWidget* GetLoginShelfWidget() { + views::Widget* GetLoginShelfWidget() { // TODO(https://crbug.com/1343114): refactor the code below after the login // shelf widget is ready. - gfx::NativeWindow window = - login_shelf_view_->GetWidget()->GetNativeWindow(); - return Shelf::ForWindow(window)->shelf_widget(); + Shelf* shelf = + Shelf::ForWindow(login_shelf_view_->GetWidget()->GetNativeWindow()); + return features::IsUseLoginShelfWidgetEnabled() + ? static_cast<views::Widget*>(shelf->login_shelf_widget()) + : shelf->shelf_widget(); } TestTrayActionClient tray_action_client_;
diff --git a/ash/shelf/login_shelf_widget.cc b/ash/shelf/login_shelf_widget.cc new file mode 100644 index 0000000..123ff27 --- /dev/null +++ b/ash/shelf/login_shelf_widget.cc
@@ -0,0 +1,189 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/shelf/login_shelf_widget.h" + +#include "ash/focus_cycler.h" +#include "ash/root_window_controller.h" +#include "ash/shelf/login_shelf_view.h" +#include "ash/shelf/shelf.h" +#include "ash/shelf/shelf_layout_manager.h" +#include "ash/shelf/shelf_widget.h" +#include "ui/views/accessible_pane_view.h" +#include "ui/views/focus/focus_search.h" +#include "ui/views/layout/fill_layout.h" + +namespace ash { + +// LoginShelfWidget::LoginShelfWidgetDelegate ---------------------------------- +// The delegate of the login shelf widget. + +class LoginShelfWidget::LoginShelfWidgetDelegate + : public views::AccessiblePaneView, + public views::WidgetDelegate { + public: + explicit LoginShelfWidgetDelegate(Shelf* shelf) : shelf_(shelf) { + SetOwnedByWidget(true); + set_allow_deactivate_on_esc(true); + SetLayoutManager(std::make_unique<views::FillLayout>()); + } + + LoginShelfWidgetDelegate(const LoginShelfWidgetDelegate&) = delete; + LoginShelfWidgetDelegate& operator=(const LoginShelfWidgetDelegate&) = delete; + + ~LoginShelfWidgetDelegate() override = default; + + // views::View: + views::View* GetDefaultFocusableChild() override { + // `login_shelf_view` is added to the widget delegate as a child when the + // login shelf widget is constructed and is removed when the widget is + // destructed. Therefore, `login_shelf_view` is not null here. + views::View* login_shelf_view = children()[0]; + + views::FocusSearch search(login_shelf_view, default_last_focusable_child_, + /*accessibility_mode=*/false); + views::FocusTraversable* dummy_focus_traversable; + views::View* dummy_focus_traversable_view; + + return search.FindNextFocusableView( + login_shelf_view, + default_last_focusable_child_ + ? views::FocusSearch::SearchDirection::kBackwards + : views::FocusSearch::SearchDirection::kForwards, + views::FocusSearch::TraversalDirection::kDown, + views::FocusSearch::StartingViewPolicy::kSkipStartingView, + views::FocusSearch::AnchoredDialogPolicy::kCanGoIntoAnchoredDialog, + &dummy_focus_traversable, &dummy_focus_traversable_view); + } + + // views::WidgetDelegate: + bool CanActivate() const override { + // We don't want mouse clicks to activate us, but we need to allow + // activation when the user is using the keyboard (FocusCycler). + bool can_active = Shell::Get()->focus_cycler()->widget_activating() == + views::View::GetWidget(); + return can_active; + } + + void ChildPreferredSizeChanged(views::View* child) override { + shelf_->shelf_layout_manager()->LayoutShelf(/*animate=*/false); + } + + void set_default_last_focusable_child(bool reverse) { + default_last_focusable_child_ = reverse; + } + + private: + const base::raw_ptr<Shelf> shelf_ = nullptr; + + // When true, the default focus of the shelf is the last focusable child. + bool default_last_focusable_child_ = false; +}; + +// LoginShelfWidget ------------------------------------------------------------ + +LoginShelfWidget::LoginShelfWidget(Shelf* shelf, aura::Window* container) + : shelf_(shelf), + delegate_(new LoginShelfWidgetDelegate(shelf)), + scoped_session_observer_(this) { + DCHECK(container); + login_shelf_view_ = delegate_->AddChildView(std::make_unique<LoginShelfView>( + RootWindowController::ForWindow(container) + ->lock_screen_action_background_controller())); + + views::Widget::InitParams params( + views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + params.name = "LoginShelfWidget"; + params.delegate = delegate_; + params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; + params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + params.parent = container; + Init(std::move(params)); + SetContentsView(delegate_); + + // Hide the login shelf by default. + Hide(); + + // TODO(https://crbug.com/1343114): currently, some logics in shelf check the + // login shelf view's visibility. Update them to check whether the login shelf + // view is drawn or the widget's visibility. Then remove this line. + login_shelf_view_->SetVisible(false); +} + +LoginShelfWidget::~LoginShelfWidget() = default; + +void LoginShelfWidget::SetDefaultLastFocusableChild(bool reverse) { + delegate_->set_default_last_focusable_child(reverse); +} + +void LoginShelfWidget::SetLoginShelfButtonOpacity(float target_opacity) { + login_shelf_view_->SetButtonOpacity(target_opacity); +} + +void LoginShelfWidget::HandleLocaleChange() { + login_shelf_view_->HandleLocaleChange(); +} + +void LoginShelfWidget::CalculateTargetBounds() { + const gfx::Point shelf_origin = + shelf_->shelf_widget()->GetTargetBounds().origin(); + + gfx::Point origin = gfx::Point(shelf_origin.x(), shelf_origin.y()); + const int target_bounds_width = delegate_->GetPreferredSize().width(); + if (shelf_->IsHorizontalAlignment() && base::i18n::IsRTL()) { + origin.set_x(shelf_->shelf_widget()->GetTargetBounds().size().width() - + target_bounds_width); + } + + target_bounds_ = + gfx::Rect(origin, {target_bounds_width, + shelf_->shelf_widget()->GetTargetBounds().height()}); +} + +gfx::Rect LoginShelfWidget::GetTargetBounds() const { + return target_bounds_; +} + +void LoginShelfWidget::UpdateLayout(bool animate) { + if (GetNativeView()->bounds() == target_bounds_) + return; + + SetBounds(target_bounds_); +} + +bool LoginShelfWidget::OnNativeWidgetActivationChanged(bool active) { + if (!Widget::OnNativeWidgetActivationChanged(active)) + return false; + + if (active) + delegate_->SetPaneFocusAndFocusDefault(); + + return true; +} + +void LoginShelfWidget::OnSessionStateChanged( + session_manager::SessionState state) { + bool is_active = (state == session_manager::SessionState::ACTIVE); + + // The visibility of `login_shelf_view_` is accessed in different places. + // Therefore, ensure the consistency between the widget's visibility and the + // view's visibility. + if (!is_active && !shelf_->ShouldHideOnSecondaryDisplay(state)) { + if (!IsVisible()) { + Show(); + login_shelf_view_->SetVisible(true); + } + } else if (IsVisible()) { + Hide(); + login_shelf_view_->SetVisible(false); + } + + login_shelf_view_->UpdateAfterSessionChange(); +} + +void LoginShelfWidget::OnUserSessionAdded(const AccountId& account_id) { + login_shelf_view_->UpdateAfterSessionChange(); +} + +} // namespace ash
diff --git a/ash/shelf/login_shelf_widget.h b/ash/shelf/login_shelf_widget.h new file mode 100644 index 0000000..d7c14f1f --- /dev/null +++ b/ash/shelf/login_shelf_widget.h
@@ -0,0 +1,69 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_SHELF_LOGIN_SHELF_WIDGET_H_ +#define ASH_SHELF_LOGIN_SHELF_WIDGET_H_ + +#include "ash/ash_export.h" +#include "ash/public/cpp/session/session_observer.h" +#include "ash/shelf/shelf_component.h" +#include "ui/views/widget/widget.h" + +namespace ash { +class Shelf; +class LoginShelfView; + +// The widget showing the login shelf. Exists separately from `ShelfWidget` so +// that the login shelf can be focused without stacking the shelf widget above +// other shelf components. +class ASH_EXPORT LoginShelfWidget : public ShelfComponent, + public views::Widget, + public SessionObserver { + public: + LoginShelfWidget(Shelf* shelf, aura::Window* container); + LoginShelfWidget(const LoginShelfWidget&) = delete; + LoginShelfWidget& operator=(const LoginShelfWidget&) = delete; + ~LoginShelfWidget() override; + + // Specifies whether the default focused view is the login shelf's last + // focusable child. + void SetDefaultLastFocusableChild(bool reverse); + + void SetLoginShelfButtonOpacity(float target_opacity); + + // Called when shelf layout manager detects a locale change. + void HandleLocaleChange(); + + // ShelfComponent: + void CalculateTargetBounds() override; + gfx::Rect GetTargetBounds() const override; + void UpdateLayout(bool animate) override; + void UpdateTargetBoundsForGesture(int shelf_position) override {} + + LoginShelfView* login_shelf_view() { return login_shelf_view_; } + + private: + // views::Widget: + bool OnNativeWidgetActivationChanged(bool active) override; + + // SessionObserver: + void OnSessionStateChanged(session_manager::SessionState state) override; + void OnUserSessionAdded(const AccountId& account_id) override; + + const base::raw_ptr<Shelf> shelf_; + + class LoginShelfWidgetDelegate; + base::raw_ptr<LoginShelfWidgetDelegate> delegate_; + + ScopedSessionObserver scoped_session_observer_; + + base::raw_ptr<LoginShelfView> login_shelf_view_ = nullptr; + + // The target widget bounds in screen coordinates. + gfx::Rect target_bounds_; +}; + +} // namespace ash + +#endif // ASH_SHELF_LOGIN_SHELF_WIDGET_H_
diff --git a/ash/shelf/shelf.cc b/ash/shelf/shelf.cc index 85b2aac..a382323 100644 --- a/ash/shelf/shelf.cc +++ b/ash/shelf/shelf.cc
@@ -17,6 +17,7 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/root_window_controller.h" #include "ash/shelf/hotseat_widget.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/shelf_controller.h" #include "ash/shelf/shelf_focus_cycler.h" #include "ash/shelf/shelf_layout_manager.h" @@ -430,6 +431,10 @@ // Create the various shelf components. CreateHotseatWidget(shelf_container); CreateNavigationWidget(shelf_container); + if (features::IsUseLoginShelfWidgetEnabled()) { + login_shelf_widget_ = + std::make_unique<LoginShelfWidget>(/*shelf=*/this, shelf_container); + } // Must occur after |shelf_widget_| is constructed because the system tray // constructors call back into Shelf::shelf_widget(). @@ -453,6 +458,7 @@ hotseat_widget_.reset(); status_area_widget_.reset(); navigation_widget_.reset(); + login_shelf_widget_.reset(); } void Shelf::DestroyShelfWidget() {
diff --git a/ash/shelf/shelf.h b/ash/shelf/shelf.h index 8ab0a57..5f24c503 100644 --- a/ash/shelf/shelf.h +++ b/ash/shelf/shelf.h
@@ -36,6 +36,7 @@ class HotseatWidgetAnimationMetricsReporter; class NavigationWidgetAnimationMetricsReporter; class ShelfFocusCycler; +class LoginShelfWidget; class ShelfLayoutManager; class ShelfLayoutManagerTest; class ShelfLockingManager; @@ -241,6 +242,7 @@ StatusAreaWidget* status_area_widget() const { return status_area_widget_.get(); } + LoginShelfWidget* login_shelf_widget() { return login_shelf_widget_.get(); } ShelfAlignment alignment() const { return alignment_; } ShelfAutoHideBehavior auto_hide_behavior() const { @@ -308,6 +310,7 @@ // Null during display teardown, see WindowTreeHostManager::DeleteHost() and // RootWindowController::CloseAllChildWindows(). std::unique_ptr<ShelfWidget> shelf_widget_; + std::unique_ptr<LoginShelfWidget> login_shelf_widget_; // These initial values hide the shelf until user preferences are available. ShelfAlignment alignment_ = ShelfAlignment::kBottomLocked;
diff --git a/ash/shelf/shelf_focus_cycler.cc b/ash/shelf/shelf_focus_cycler.cc index 8e4c58b..9013bf77 100644 --- a/ash/shelf/shelf_focus_cycler.cc +++ b/ash/shelf/shelf_focus_cycler.cc
@@ -6,6 +6,7 @@ #include "ash/focus_cycler.h" #include "ash/shelf/login_shelf_view.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/scrollable_shelf_view.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_navigation_widget.h" @@ -75,7 +76,11 @@ // TODO(https://crbug.com/1343114): refactor the code below after the login // shelf widget is ready. - if (!features::IsUseLoginShelfWidgetEnabled()) { + if (features::IsUseLoginShelfWidgetEnabled()) { + LoginShelfWidget* login_shelf_widget = shelf_->login_shelf_widget(); + login_shelf_widget->SetDefaultLastFocusableChild(last_element); + Shell::Get()->focus_cycler()->FocusWidget(login_shelf_widget); + } else { ShelfWidget* shelf_widget = shelf_->shelf_widget(); shelf_widget->set_default_last_focusable_child(last_element); Shell::Get()->focus_cycler()->FocusWidget(shelf_widget);
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 973eb3f..c8a2c75 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -29,6 +29,7 @@ #include "ash/shelf/home_to_overview_nudge_controller.h" #include "ash/shelf/hotseat_widget.h" #include "ash/shelf/in_app_to_home_nudge_controller.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_layout_manager_observer.h" #include "ash/shelf/shelf_metrics.h" @@ -1231,9 +1232,10 @@ } void ShelfLayoutManager::OnLocaleChanged() { - if (!features::IsUseLoginShelfWidgetEnabled()) + if (features::IsUseLoginShelfWidgetEnabled()) + shelf_->login_shelf_widget()->HandleLocaleChange(); + else shelf_->shelf_widget()->HandleLocaleChange(); - shelf_->status_area_widget()->HandleLocaleChange(); shelf_->navigation_widget()->HandleLocaleChange(); @@ -1620,8 +1622,11 @@ AnimateOpacity(GetLayer(shelf_->status_area_widget()), target_opacity_, dim_animation_duration, dim_animation_tween); - if (!features::IsUseLoginShelfWidgetEnabled()) + if (features::IsUseLoginShelfWidgetEnabled()) + shelf_->login_shelf_widget()->SetLoginShelfButtonOpacity(target_opacity_); + else shelf_widget_->SetLoginShelfButtonOpacity(target_opacity_); + return true; } @@ -1656,6 +1661,8 @@ hotseat_widget->UpdateLayout(animate); status_widget->UpdateLayout(animate); nav_widget->UpdateLayout(animate); + if (features::IsUseLoginShelfWidgetEnabled()) + shelf_->login_shelf_widget()->UpdateLayout(animate); // Do not update the work area during overview animation. if (!suspend_work_area_update_) { @@ -1738,6 +1745,8 @@ shelf_->status_area_widget()->CalculateTargetBounds(); shelf_->navigation_widget()->CalculateTargetBounds(); shelf_->hotseat_widget()->CalculateTargetBounds(); + if (features::IsUseLoginShelfWidgetEnabled()) + shelf_->login_shelf_widget()->CalculateTargetBounds(); target_opacity_ = ComputeTargetOpacity(state); @@ -2204,12 +2213,23 @@ shelf_widget_->status_area_widget()->GetNativeWindow(); const aura::Window* drag_handle_nudge_window = GetDragHandleNudgeWindow(shelf_widget_); + + // Calculate whether `window` is contained by the login shelf widget. + bool window_in_login_shelf_widget = false; + if (features::IsUseLoginShelfWidgetEnabled()) { + const aura::Window* login_shelf_window = + shelf_->login_shelf_widget()->GetNativeWindow(); + window_in_login_shelf_widget = + (login_shelf_window && login_shelf_window->Contains(window)); + } + return (shelf_window && shelf_window->Contains(window)) || (navigation_window && navigation_window->Contains(window)) || (hotseat_window && hotseat_window->Contains(window)) || (status_area_window && status_area_window->Contains(window)) || (drag_handle_nudge_window && - drag_handle_nudge_window->Contains(window)); + drag_handle_nudge_window->Contains(window)) || + window_in_login_shelf_widget; } bool ShelfLayoutManager::IsStatusAreaWindow(aura::Window* window) {
diff --git a/ash/shelf/shelf_view.cc b/ash/shelf/shelf_view.cc index 95ee31a..cfe8360 100644 --- a/ash/shelf/shelf_view.cc +++ b/ash/shelf/shelf_view.cc
@@ -1495,7 +1495,7 @@ } // Move the view to the front so that it appears on top of other views. - ReorderChildView(drag_view_, -1); + ReorderChildView(drag_view_, children().size()); bounds_animator_->StopAnimatingView(drag_view_); drag_view_->OnDragStarted(&event);
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index 10995687..1a3dde2 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -24,13 +24,15 @@ #include "ash/shelf/hotseat_transition_animator.h" #include "ash/shelf/hotseat_widget.h" #include "ash/shelf/login_shelf_view.h" +#include "ash/shelf/login_shelf_widget.h" #include "ash/shelf/scrollable_shelf_view.h" #include "ash/shelf/shelf_background_animator_observer.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_navigation_widget.h" #include "ash/shelf/shelf_view.h" #include "ash/shell.h" -#include "ash/style/ash_color_provider.h" +#include "ash/style/ash_color_id.h" +#include "ash/style/style_util.h" #include "ash/system/status_area_widget.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/work_area_insets.h" @@ -180,10 +182,12 @@ canvas->DrawRoundRect(gfx::Rect(layer()->size()), corner_radius_, flags); // Don't draw highlight border in login screen. - if (login_shelf_from_shelf_widget_ && - login_shelf_from_shelf_widget_->GetVisible()) { + LoginShelfView* login_shelf_view = + features::IsUseLoginShelfWidgetEnabled() + ? shelf_->login_shelf_widget()->login_shelf_view() + : login_shelf_from_shelf_widget_; + if (login_shelf_view && login_shelf_view->GetVisible()) return; - } if (corner_radius_ > 0) { views::HighlightBorder::PaintBorderToCanvas( @@ -441,10 +445,6 @@ drag_handle_ = AddChildView( std::make_unique<DragHandle>(kDragHandleCornerRadius, shelf)); - const std::pair<SkColor, float> base_color_and_opacity = - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity(); - animating_drag_handle_.SetColor(base_color_and_opacity.first); - animating_drag_handle_.SetOpacity(base_color_and_opacity.second + 0.075); animating_drag_handle_.SetRoundedCornerRadius( {kDragHandleCornerRadius, kDragHandleCornerRadius, kDragHandleCornerRadius, kDragHandleCornerRadius}); @@ -482,9 +482,15 @@ shelf_widget_->background_animator_.PaintBackground( shelf_widget_->shelf_layout_manager()->GetShelfBackgroundType(), AnimationChangeType::IMMEDIATE); + animating_drag_handle_.SetOpacity(StyleUtil::GetInkDropOpacity() + 0.075); + animating_drag_handle_.SetColor( + GetColorProvider()->GetColor(kColorAshInkDropOpaqueColor)); } bool ShelfWidget::DelegateView::CanActivate() const { + if (features::IsUseLoginShelfWidgetEnabled()) + return false; + // This widget only contains anything interesting to activate in login/lock // screen mode. Only allow activation from the focus cycler, not from mouse // events, etc. @@ -900,12 +906,17 @@ } LoginShelfView* ShelfWidget::GetLoginShelfView() { + if (features::IsUseLoginShelfWidgetEnabled()) + return shelf_->login_shelf_widget()->login_shelf_view(); + return login_shelf_view_; } bool ShelfWidget::OnNativeWidgetActivationChanged(bool active) { // TODO(https://crbug.com/1343114): remove this function after the login shelf // widget is ready. + if (features::IsUseLoginShelfWidgetEnabled()) + return false; if (!Widget::OnNativeWidgetActivationChanged(active)) return false;
diff --git a/ash/shell.cc b/ash/shell.cc index 88e95b78..c789ef3 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -144,7 +144,6 @@ #include "ash/system/power/power_prefs.h" #include "ash/system/power/power_status.h" #include "ash/system/power/video_activity_notifier.h" -#include "ash/system/privacy_hub/microphone_privacy_switch_controller.h" #include "ash/system/screen_layout_observer.h" #include "ash/system/screen_security/screen_switch_check_controller.h" #include "ash/system/session/logout_confirmation_controller.h" @@ -836,9 +835,6 @@ // controller. dark_light_mode_controller_.reset(); - // Observes `SessionController` and must be destroyed before it. - microphone_privacy_switch_controller_.reset(); - // These members access Shell in their destructors. wallpaper_controller_.reset(); accessibility_controller_.reset(); @@ -1041,9 +1037,6 @@ std::make_unique<SnoopingProtectionController>(); } - microphone_privacy_switch_controller_ = - std::make_unique<MicrophonePrivacySwitchController>(); - // Manages lifetime of DiagnosticApp logs. if (features::IsLogControllerForDiagnosticsAppEnabled()) { diagnostics_log_controller_ =
diff --git a/ash/shell.h b/ash/shell.h index 68c6e159..6c7fbdc 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -154,7 +154,6 @@ class MediaControllerImpl; class MessageCenterAshImpl; class MessageCenterController; -class MicrophonePrivacySwitchController; class MouseCursorEventFilter; class MruWindowTracker; class MultiDeviceNotificationPresenter; @@ -508,9 +507,6 @@ MessageCenterController* message_center_controller() { return message_center_controller_.get(); } - MicrophonePrivacySwitchController* microphone_privacy_switch_controller() { - return microphone_privacy_switch_controller_.get(); - } MouseCursorEventFilter* mouse_cursor_filter() { return mouse_cursor_filter_.get(); } @@ -981,12 +977,6 @@ std::unique_ptr<chromeos::SnapController> snap_controller_; - // Privacy hub controllers. - // TODO(b/239400029): Move this to the unified privacy hub controller after it - // is created. - std::unique_ptr<MicrophonePrivacySwitchController> - microphone_privacy_switch_controller_; - // |native_cursor_manager_| is owned by |cursor_manager_|, but we keep a // pointer to vend to test code. NativeCursorManagerAsh* native_cursor_manager_;
diff --git a/ash/style/ash_color_id.h b/ash/style/ash_color_id.h index b8dd6005..b69b8e1 100644 --- a/ash/style/ash_color_id.h +++ b/ash/style/ash_color_id.h
@@ -90,7 +90,8 @@ E_CPONLY(kColorAshBatterySystemInfoIconColor) \ /* Color of the capture region in the capture session. */ \ E_CPONLY(kColorAshCaptureRegionColor) \ - E_CPONLY(kColorAshInkDrop) + E_CPONLY(kColorAshInkDrop) \ + E_CPONLY(kColorAshInkDropOpaqueColor) #include "ui/color/color_id_macros.inc"
diff --git a/ash/style/ash_color_mixer.cc b/ash/style/ash_color_mixer.cc index af710de0..a2f71a6 100644 --- a/ash/style/ash_color_mixer.cc +++ b/ash/style/ash_color_mixer.cc
@@ -8,6 +8,7 @@ #include "ash/public/cpp/style/scoped_light_mode_as_default.h" #include "ash/style/ash_color_id.h" #include "ash/style/ash_color_provider.h" +#include "ash/style/style_util.h" #include "ash/style/temp_palette.h" #include "ash/system/tray/tray_constants.h" #include "third_party/skia/include/core/SkColor.h" @@ -29,9 +30,6 @@ constexpr int kAlpha90 = SK_AlphaOPAQUE * 0.9f; constexpr int kAlpha95 = SK_AlphaOPAQUE * 0.95f; -constexpr int kLightInkDropOpacity = SK_AlphaOPAQUE * 0.08f; -constexpr int kDarkInkDropOpacity = SK_AlphaOPAQUE * 0.06f; - // Color of second tone is always 30% opacity of the color of first tone. constexpr int kSecondToneOpacity = SK_AlphaOPAQUE * 0.3f; @@ -201,14 +199,23 @@ if (key.user_color.has_value()) { mixer[kColorAshInkDrop] = ui::SelectBasedOnDarkInput( {*key.user_color}, /*output_transform_for_dark_input=*/ - ui::SetAlpha(SK_ColorWHITE, kDarkInkDropOpacity), + ui::SetAlpha(SK_ColorWHITE, + StyleUtil::kDarkInkDropOpacity * SK_AlphaOPAQUE), /*output_transform_for_light_input=*/ - ui::SetAlpha(SK_ColorBLACK, kLightInkDropOpacity)); + ui::SetAlpha(SK_ColorBLACK, + StyleUtil::kLightInkDropOpacity * SK_AlphaOPAQUE)); + mixer[kColorAshInkDropOpaqueColor] = ui::SelectBasedOnDarkInput( + {*key.user_color}, SK_ColorWHITE, SK_ColorBLACK); } else { // Default `user_color` is dark if color_mode is dark. mixer[kColorAshInkDrop] = - use_dark_color ? ui::SetAlpha(SK_ColorWHITE, kDarkInkDropOpacity) - : ui::SetAlpha(SK_ColorBLACK, kLightInkDropOpacity); + use_dark_color + ? ui::SetAlpha(SK_ColorWHITE, + StyleUtil::kDarkInkDropOpacity * SK_AlphaOPAQUE) + : ui::SetAlpha(SK_ColorBLACK, + StyleUtil::kLightInkDropOpacity * SK_AlphaOPAQUE); + mixer[kColorAshInkDropOpaqueColor] = + ui::ColorTransform(use_dark_color ? SK_ColorWHITE : SK_ColorBLACK); } }
diff --git a/ash/style/ash_color_provider.cc b/ash/style/ash_color_provider.cc index fc49645..3321e951 100644 --- a/ash/style/ash_color_provider.cc +++ b/ash/style/ash_color_provider.cc
@@ -220,18 +220,6 @@ return std::make_pair(base_color, opacity); } -std::pair<SkColor, float> -AshColorProvider::GetInvertedInkDropBaseColorAndOpacity( - SkColor background_color) const { - if (background_color == gfx::kPlaceholderColor) - background_color = GetBackgroundColor(); - - const bool is_light = !color_utils::IsDark(background_color); - const SkColor base_color = is_light ? SK_ColorWHITE : SK_ColorBLACK; - const float opacity = is_light ? kLightInkDropOpacity : kDarkInkDropOpacity; - return std::make_pair(base_color, opacity); -} - SkColor AshColorProvider::GetBackgroundColor() const { return GetBackgroundThemedColorImpl(GetBackgroundDefaultColor(), IsDarkModeEnabled());
diff --git a/ash/style/ash_color_provider.h b/ash/style/ash_color_provider.h index 86214b0..7f0b953 100644 --- a/ash/style/ash_color_provider.h +++ b/ash/style/ash_color_provider.h
@@ -54,8 +54,6 @@ SkColor GetInactiveDialogTitleBarColor() const override; std::pair<SkColor, float> GetInkDropBaseColorAndOpacity( SkColor background_color = gfx::kPlaceholderColor) const override; - std::pair<SkColor, float> GetInvertedInkDropBaseColorAndOpacity( - SkColor background_color = gfx::kPlaceholderColor) const override; // Gets the background color that can be applied on any layer. The returned // color will be different based on color mode and color theme (see
diff --git a/ash/style/style_util.cc b/ash/style/style_util.cc index 6ee11c2..fa28b2c 100644 --- a/ash/style/style_util.cc +++ b/ash/style/style_util.cc
@@ -5,25 +5,35 @@ #include "ash/style/style_util.h" #include "ash/style/ash_color_provider.h" +#include "ash/style/dark_light_mode_controller_impl.h" #include "ui/color/color_id.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop.h" +#include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_host_view.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/focus_ring.h" namespace ash { -namespace { +// static +float StyleUtil::GetInkDropOpacity() { + return DarkLightModeControllerImpl::Get()->IsDarkModeEnabled() + ? kDarkInkDropOpacity + : kLightInkDropOpacity; +} -std::unique_ptr<views::InkDrop> CreateInkDrop(views::Button* host, - bool highlight_on_hover, - bool highlight_on_focus) { +// static +std::unique_ptr<views::InkDrop> StyleUtil::CreateInkDrop( + views::Button* host, + bool highlight_on_hover, + bool highlight_on_focus) { return views::InkDrop::CreateInkDropForFloodFillRipple( views::InkDrop::Get(host), highlight_on_hover, highlight_on_focus); } -std::unique_ptr<views::InkDropRipple> CreateInkDropRipple( +// static +std::unique_ptr<views::InkDropRipple> StyleUtil::CreateInkDropRipple( const gfx::Insets& insets, const views::View* host, SkColor background_color) { @@ -35,8 +45,9 @@ base_color_and_opacity.first, base_color_and_opacity.second); } -std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight( - views::View* host, +// static +std::unique_ptr<views::InkDropHighlight> StyleUtil::CreateInkDropHighlight( + const views::View* host, SkColor background_color) { const std::pair<SkColor, float> base_color_and_opacity = AshColorProvider::Get()->GetInkDropBaseColorAndOpacity(background_color); @@ -46,8 +57,6 @@ return highlight; } -} // namespace - // static void StyleUtil::SetRippleParams(views::View* host, const gfx::Insets& insets,
diff --git a/ash/style/style_util.h b/ash/style/style_util.h index 424b805..52ec852 100644 --- a/ash/style/style_util.h +++ b/ash/style/style_util.h
@@ -6,12 +6,16 @@ #define ASH_STYLE_STYLE_UTIL_H_ #include "ash/ash_export.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/color_palette.h" -#include "ui/views/animation/ink_drop_highlight.h" +#include "ui/gfx/geometry/insets.h" namespace views { class Button; class FocusRing; +class InkDrop; +class InkDropHighlight; +class InkDropRipple; class View; } // namespace views @@ -28,6 +32,29 @@ kHighlightOpacity = 1 << 2 }; + static constexpr float kLightInkDropOpacity = 0.08f; + static constexpr float kDarkInkDropOpacity = 0.06f; + + static float GetInkDropOpacity(); + + // Creates an InkDrop instance for `host`. All styles are configured to show + // the highlight when the ripple is visible. + static std::unique_ptr<views::InkDrop> CreateInkDrop( + views::Button* host, + bool highlight_on_hover = false, + bool highlight_on_focus = false); + + // Crates an InkDropRipple instance for `host` with `insets`. + static std::unique_ptr<views::InkDropRipple> CreateInkDropRipple( + const gfx::Insets& insets, + const views::View* host, + SkColor background_color = gfx::kPlaceholderColor); + + // Creates an InkDropHighlight instance for `host`. + static std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight( + const views::View* host, + SkColor background_color); + // Sets attributes(e.g, insets) for creating the inkdrop ripple. Note, A // FloodFillInkDropRipple will be created for the given `host`. static void SetRippleParams( @@ -35,17 +62,15 @@ const gfx::Insets& insets, SkColor background_color = gfx::kPlaceholderColor); - // TODO: Remove TrayPopupUtils::ConfigureTrayPopupButton and migrate all its - // clients to this function. // Sets up the inkdrop for the given `button`. Including setting the callback // for InkDrop, Ripple, Highlight. Inside the callback functions, they will // setup whether to show the highlight on hover or focus, inkdrop color, // opacity etc. static void SetUpInkDropForButton( views::Button* button, - const gfx::Insets& ripple_insets, - bool highlight_on_hover, - bool highlight_on_focus, + const gfx::Insets& ripple_insets = gfx::Insets(), + bool highlight_on_hover = false, + bool highlight_on_focus = false, SkColor background_color = gfx::kPlaceholderColor); // Configures the InkDropAttributes for the given `view` based on
diff --git a/ash/system/accessibility/floating_menu_button.cc b/ash/system/accessibility/floating_menu_button.cc index bca621a..b1ed373 100644 --- a/ash/system/accessibility/floating_menu_button.cc +++ b/ash/system/accessibility/floating_menu_button.cc
@@ -5,7 +5,7 @@ #include "ash/system/accessibility/floating_menu_button.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/tray/tray_popup_utils.h" +#include "ash/style/style_util.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" @@ -28,7 +28,7 @@ SetImageHorizontalAlignment(ALIGN_CENTER); SetImageVerticalAlignment(ALIGN_MIDDLE); SetFlipCanvasOnPaintForRTLUI(false); - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::InstallCircleHighlightPathGenerator(this); } @@ -60,7 +60,7 @@ SetImageVerticalAlignment(ALIGN_MIDDLE); SetFlipCanvasOnPaintForRTLUI(flip_for_rtl); SetPreferredSize(gfx::Size(size_, size_)); - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::InstallCircleHighlightPathGenerator(this); SetTooltipText(l10n_util::GetStringUTF16(accessible_name_id)); views::FocusRing::Get(this)->SetColorId(ui::kColorAshFocusRing);
diff --git a/ash/system/audio/unified_volume_view.cc b/ash/system/audio/unified_volume_view.cc index 0db306d..22df65f 100644 --- a/ash/system/audio/unified_volume_view.cc +++ b/ash/system/audio/unified_volume_view.cc
@@ -10,7 +10,8 @@ #include "ash/resources/vector_icons/vector_icons.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/tray/tray_popup_utils.h" +#include "ash/style/style_util.h" +#include "ash/system/tray/tray_constants.h" #include "base/bind.h" #include "base/i18n/rtl.h" #include "components/vector_icons/vector_icons.h" @@ -20,10 +21,6 @@ #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_utils.h" -#include "ui/views/animation/flood_fill_ink_drop_ripple.h" -#include "ui/views/animation/ink_drop_highlight.h" -#include "ui/views/animation/ink_drop_impl.h" -#include "ui/views/animation/ink_drop_mask.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/focus_ring.h" @@ -71,7 +68,7 @@ template <typename... Args> explicit UnifiedVolumeViewButton(Args... args) : T(std::forward<Args>(args)...) { - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(), kTrayItemCornerRadius);
diff --git a/ash/system/bluetooth/bluetooth_detailed_view_legacy.cc b/ash/system/bluetooth/bluetooth_detailed_view_legacy.cc index ec63bd7..d647744 100644 --- a/ash/system/bluetooth/bluetooth_detailed_view_legacy.cc +++ b/ash/system/bluetooth/bluetooth_detailed_view_legacy.cc
@@ -215,7 +215,7 @@ bool has_paired_devices = !connected_devices.empty() || !connecting_devices.empty() || !paired_not_connected_devices.empty(); - int index = 0; + size_t index = 0; if (has_paired_devices) { paired_devices_heading_ = AddSubHeading(IDS_ASH_STATUS_TRAY_BLUETOOTH_PAIRED_DEVICES, @@ -292,7 +292,7 @@ TriView* BluetoothDetailedViewLegacy::AddSubHeading(int text_id, TriView* sub_heading_view, - int child_index) { + size_t child_index) { if (!sub_heading_view) { sub_heading_view = AddScrollListSubHeader(text_id); } @@ -300,11 +300,11 @@ return sub_heading_view; } -int BluetoothDetailedViewLegacy::AddSameTypeDevicesToScrollList( +size_t BluetoothDetailedViewLegacy::AddSameTypeDevicesToScrollList( const BluetoothDeviceList& list, const std::unordered_map<HoverHighlightView*, BluetoothAddress>& old_device_list, - int child_index, + size_t child_index, bool highlight, bool checked) { for (const auto& device : list) {
diff --git a/ash/system/bluetooth/bluetooth_detailed_view_legacy.h b/ash/system/bluetooth/bluetooth_detailed_view_legacy.h index 8a5409fc..a6613aa 100644 --- a/ash/system/bluetooth/bluetooth_detailed_view_legacy.h +++ b/ash/system/bluetooth/bluetooth_detailed_view_legacy.h
@@ -70,16 +70,16 @@ // |sub_heading_view| or the newly created view. TriView* AddSubHeading(int text_id, TriView* sub_heading_view, - int child_index); + size_t child_index); // Adds devices from |list| into the scroll list at given |child_index|. // To avoid disrupting a11y, list items are re-used from |old_device_list| if // it exists. Returns index position for next scroll list item. - int AddSameTypeDevicesToScrollList( + size_t AddSameTypeDevicesToScrollList( const BluetoothDeviceList& list, const std::unordered_map<HoverHighlightView*, BluetoothAddress>& old_device_list, - int child_index, + size_t child_index, bool highlight, bool checked);
diff --git a/ash/system/bluetooth/bluetooth_device_list_controller_impl.cc b/ash/system/bluetooth/bluetooth_device_list_controller_impl.cc index 4d224897..939f8d9 100644 --- a/ash/system/bluetooth/bluetooth_device_list_controller_impl.cc +++ b/ash/system/bluetooth/bluetooth_device_list_controller_impl.cc
@@ -80,7 +80,7 @@ // order of the devices we are provided with. We use |index| to keep track of // the next index within the device list where a view should be placed, i.e. // all views before |index| are in their final position. - int index = 0; + size_t index = 0; // The list of connected devices. if (!connected.empty()) { @@ -150,7 +150,7 @@ TriView* BluetoothDeviceListControllerImpl::CreateSubHeaderIfMissingAndReorder( TriView* sub_header, int text_id, - int index) { + size_t index) { if (!sub_header) { sub_header = bluetooth_detailed_view_->AddDeviceListSubHeader( gfx::kNoneIcon, text_id); @@ -159,10 +159,10 @@ return sub_header; } -int BluetoothDeviceListControllerImpl::CreateViewsIfMissingAndReorder( +size_t BluetoothDeviceListControllerImpl::CreateViewsIfMissingAndReorder( const PairedBluetoothDevicePropertiesPtrs& device_property_list, base::flat_map<std::string, BluetoothDeviceListItemView*>* previous_views, - int index) { + size_t index) { DCHECK(previous_views); BluetoothDeviceListItemView* device_view = nullptr;
diff --git a/ash/system/bluetooth/bluetooth_device_list_controller_impl.h b/ash/system/bluetooth/bluetooth_device_list_controller_impl.h index 77f0d1e..521693c 100644 --- a/ash/system/bluetooth/bluetooth_device_list_controller_impl.h +++ b/ash/system/bluetooth/bluetooth_device_list_controller_impl.h
@@ -51,17 +51,17 @@ // returned. TriView* CreateSubHeaderIfMissingAndReorder(TriView* sub_header, int text_id, - int index); + size_t index); // Creates and initializes a view for each of the device properties within // |device_property_list| if a view does not already exist, otherwise re-using // the existing view to avoid disrupting a11y. Each view will be reordered to // start at |index| and will be removed from |previous_views|. The index of // the position after the final view that was added is returned. - int CreateViewsIfMissingAndReorder( + size_t CreateViewsIfMissingAndReorder( const PairedBluetoothDevicePropertiesPtrs& device_property_list, base::flat_map<std::string, BluetoothDeviceListItemView*>* previous_views, - int index); + size_t index); BluetoothDetailedView* const bluetooth_detailed_view_;
diff --git a/ash/system/human_presence/snooping_protection_notification_blocker_internal.h b/ash/system/human_presence/snooping_protection_notification_blocker_internal.h index 4d8466b..3eb22a7 100644 --- a/ash/system/human_presence/snooping_protection_notification_blocker_internal.h +++ b/ash/system/human_presence/snooping_protection_notification_blocker_internal.h
@@ -79,7 +79,7 @@ } const bool found = - app_cache->ForApp(id.id, [&](const apps::AppUpdate& update) { + app_cache->ForOneApp(id.id, [&](const apps::AppUpdate& update) { const std::string& short_name = update.ShortName(); title = std::u16string(short_name.begin(), short_name.end()); });
diff --git a/ash/system/human_presence/snooping_protection_notification_blocker_unittest.cc b/ash/system/human_presence/snooping_protection_notification_blocker_unittest.cc index 745ff4ad..8bc0ae1 100644 --- a/ash/system/human_presence/snooping_protection_notification_blocker_unittest.cc +++ b/ash/system/human_presence/snooping_protection_notification_blocker_unittest.cc
@@ -155,7 +155,7 @@ FakeAppRegistryCache* GetAppRegistryCache(const AccountId&) { return this; } template <typename FunctionType> - bool ForApp(const std::string& app_id, FunctionType f) { + bool ForOneApp(const std::string& app_id, FunctionType f) { for (const std::unique_ptr<apps::AppUpdate>& app : apps_) { if (app_id == app->AppId()) { f(*app);
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_controller.cc b/ash/system/keyboard_brightness/keyboard_backlight_color_controller.cc index ad8301fc..ed8732a 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_controller.cc +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_controller.cc
@@ -94,6 +94,17 @@ DisplayBacklightColor(backlight_color); } +void KeyboardBacklightColorController::OnUserSessionUpdated( + const AccountId& account_id) { + const auto backlight_color = GetBacklightColor(account_id); + // Wallpaper extracted color may not be available at this state. Instead of + // setting wallpaper color here, let |OnWallpaperColorsChanged| handles it + // when the color is available. + if (backlight_color == personalization_app::mojom::BacklightColor::kWallpaper) + return; + DisplayBacklightColor(backlight_color); +} + void KeyboardBacklightColorController::OnWallpaperColorsChanged() { const auto backlight_color = GetBacklightColor(GetActiveAccountId()); if (backlight_color != personalization_app::mojom::BacklightColor::kWallpaper)
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_controller.h b/ash/system/keyboard_brightness/keyboard_backlight_color_controller.h index 3e42b16..5062fd3 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_controller.h +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_controller.h
@@ -46,6 +46,9 @@ // SessionObserver: void OnActiveUserPrefServiceChanged(PrefService* pref_service) override; + // b/239967737: |OnActiveUserPrefServiceChanged| doesn't get triggered when + // chrome restarts. + void OnUserSessionUpdated(const AccountId& account_id) override; // WallpaperControllerObserver: void OnWallpaperColorsChanged() override;
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_controller_unittest.cc b/ash/system/keyboard_brightness/keyboard_backlight_color_controller_unittest.cc index de9242f69..940a84ea 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_controller_unittest.cc +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_controller_unittest.cc
@@ -5,6 +5,7 @@ #include "ash/system/keyboard_brightness/keyboard_backlight_color_controller.h" #include "ash/constants/ash_features.h" #include "ash/rgb_keyboard/rgb_keyboard_util.h" +#include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/wallpaper/wallpaper_controller_impl.h" @@ -92,6 +93,10 @@ return controller_->displayed_color_for_testing_; } + void clear_displayed_color() { + controller_->displayed_color_for_testing_ = SK_ColorTRANSPARENT; + } + KeyboardBacklightColorController* controller_ = nullptr; WallpaperControllerImpl* wallpaper_controller_ = nullptr; @@ -138,6 +143,39 @@ } TEST_F(KeyboardBacklightColorControllerTest, + SetBacklightColorOnUserSessionUpdated) { + // Verify the user starts with wallpaper-extracted color. + SimulateUserLogin(account_id_1); + EXPECT_EQ(personalization_app::mojom::BacklightColor::kWallpaper, + controller_->GetBacklightColor(account_id_1)); + // Expect the Wallpaper color to be not set. + histogram_tester().ExpectBucketCount( + "Ash.Personalization.KeyboardBacklight.WallpaperColor.Valid", false, 0); + EXPECT_EQ(SK_ColorTRANSPARENT, displayed_color()); + + controller_->SetBacklightColor( + personalization_app::mojom::BacklightColor::kBlue, account_id_1); + ClearLogin(); + clear_displayed_color(); + + // Simulate adding session for user1 and expect blue color to be set. + UserSession session; + session.session_id = 0; + session.user_info.account_id = account_id_1; + Shell::Get()->session_controller()->UpdateUserSession(session); + EXPECT_EQ(ConvertBacklightColorToSkColor( + personalization_app::mojom::BacklightColor::kBlue), + displayed_color()); + + // Simulate updating session for user1 and expect blue color to be set. + clear_displayed_color(); + Shell::Get()->session_controller()->UpdateUserSession(session); + EXPECT_EQ(ConvertBacklightColorToSkColor( + personalization_app::mojom::BacklightColor::kBlue), + displayed_color()); +} + +TEST_F(KeyboardBacklightColorControllerTest, DisplaysDefaultColorForNearlyBlackColor) { TestWallpaperObserver observer; SimulateUserLogin(account_id_1);
diff --git a/ash/system/message_center/ash_notification_view.cc b/ash/system/message_center/ash_notification_view.cc index 65eaec06..ebbfaae3 100644 --- a/ash/system/message_center/ash_notification_view.cc +++ b/ash/system/message_center/ash_notification_view.cc
@@ -38,6 +38,7 @@ #include "ui/color/color_id.h" #include "ui/compositor/animation_throughput_reporter.h" #include "ui/compositor/layer.h" +#include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/color_utils.h" @@ -62,6 +63,7 @@ #include "ui/message_center/views/proportional_image_view.h" #include "ui/message_center/views/relative_time_formatter.h" #include "ui/strings/grit/ui_strings.h" +#include "ui/views/animation/animation_builder.h" #include "ui/views/background.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/image_button_factory.h" @@ -1326,8 +1328,10 @@ if (snooze_button_) { DCHECK(snooze_button_spacer_); // Spacer and snooze button should be at the end of action buttons row. - action_buttons_row()->ReorderChildView(snooze_button_spacer_, -1); - action_buttons_row()->ReorderChildView(snooze_button_, -1); + action_buttons_row()->ReorderChildView( + snooze_button_spacer_, action_buttons_row()->children().size()); + action_buttons_row()->ReorderChildView( + snooze_button_, action_buttons_row()->children().size()); return; }
diff --git a/ash/system/model/system_tray_model.cc b/ash/system/model/system_tray_model.cc index 785b414b..1886d2b 100644 --- a/ash/system/model/system_tray_model.cc +++ b/ash/system/model/system_tray_model.cc
@@ -105,6 +105,10 @@ update_model()->ResetUpdateAvailable(); } +void SystemTrayModel::SetUpdateDeferred(bool deferred) { + update_model()->SetUpdateDeferred(deferred); +} + void SystemTrayModel::SetUpdateOverCellularAvailableIconVisible(bool visible) { update_model()->SetUpdateOverCellularAvailable(visible); }
diff --git a/ash/system/model/system_tray_model.h b/ash/system/model/system_tray_model.h index 3c3deca..26832b1 100644 --- a/ash/system/model/system_tray_model.h +++ b/ash/system/model/system_tray_model.h
@@ -54,6 +54,7 @@ void SetRelaunchNotificationState( const RelaunchNotificationState& relaunch_notification_state) override; void ResetUpdateState() override; + void SetUpdateDeferred(bool deferred) override; void SetUpdateOverCellularAvailableIconVisible(bool visible) override; void ShowVolumeSliderBubble() override; void ShowNetworkDetailedViewBubble() override;
diff --git a/ash/system/model/update_model.cc b/ash/system/model/update_model.cc index a224dc1..602dddce 100644 --- a/ash/system/model/update_model.cc +++ b/ash/system/model/update_model.cc
@@ -22,6 +22,7 @@ bool rollback, UpdateType update_type) { update_required_ = true; + update_deferred_ = false; severity_ = severity; factory_reset_required_ = factory_reset_required; rollback_ = rollback; @@ -41,6 +42,11 @@ NotifyUpdateAvailable(); } +void UpdateModel::SetUpdateDeferred(bool deferred) { + update_deferred_ = deferred; + NotifyUpdateAvailable(); +} + UpdateSeverity UpdateModel::GetSeverity() const { // TODO(https://crbug.com/927010): adjust severity according the amount of // time passing after update is available over cellular connection. Use low @@ -50,6 +56,7 @@ void UpdateModel::ResetUpdateAvailable() { update_required_ = false; + update_deferred_ = false; NotifyUpdateAvailable(); }
diff --git a/ash/system/model/update_model.h b/ash/system/model/update_model.h index 3de541b..00a469f 100644 --- a/ash/system/model/update_model.h +++ b/ash/system/model/update_model.h
@@ -50,6 +50,9 @@ // granted. void SetUpdateOverCellularAvailable(bool available); + // If `deferred` is true, an update is downloaded but deferred. + void SetUpdateDeferred(bool deferred); + UpdateSeverity GetSeverity() const; // Sets |update_required_| back to false. @@ -65,6 +68,7 @@ bool update_over_cellular_available() const { return update_over_cellular_available_; } + bool update_deferred() const { return update_deferred_; } private: void NotifyUpdateAvailable(); @@ -76,6 +80,7 @@ UpdateType update_type_ = UpdateType::kSystem; RelaunchNotificationState relaunch_notification_state_; bool update_over_cellular_available_ = false; + bool update_deferred_ = false; base::ObserverList<UpdateObserver>::Unchecked observers_; };
diff --git a/ash/system/network/network_list_view.cc b/ash/system/network/network_list_view.cc index 8f6a2d26..10b86157 100644 --- a/ash/system/network/network_list_view.cc +++ b/ash/system/network/network_list_view.cc
@@ -379,7 +379,7 @@ std::unique_ptr<std::set<std::string>> NetworkListView::UpdateNetworkListEntries() { // Keep an index where the next child should be inserted. - int index = 0; + size_t index = 0; const NetworkStateProperties* default_network = model()->default_network(); bool using_proxy = @@ -692,7 +692,7 @@ std::unique_ptr<std::set<std::string>> NetworkListView::UpdateNetworkChildren( NetworkType type, - int index) { + size_t index) { std::unique_ptr<std::set<std::string>> new_guids(new std::set<std::string>); for (const auto& info : network_list_) { if (!NetworkTypeMatchesType(info->type, type)) @@ -703,7 +703,8 @@ return new_guids; } -void NetworkListView::UpdateNetworkChild(int index, const NetworkInfo* info) { +void NetworkListView::UpdateNetworkChild(size_t index, + const NetworkInfo* info) { HoverHighlightView* network_view = nullptr; NetworkGuidMap::const_iterator found = network_guid_map_.find(info->guid); @@ -735,12 +736,11 @@ network_guid_map_[info->guid] = network_view; } -void NetworkListView::PlaceViewAtIndex(views::View* view, int index) { +void NetworkListView::PlaceViewAtIndex(views::View* view, size_t index) { if (view->parent() != scroll_content()) { scroll_content()->AddChildViewAt(view, index); - } else if (index > 0 && - static_cast<size_t>(index) < scroll_content()->children().size() && - scroll_content()->children()[static_cast<size_t>(index)] == view) { + } else if (index > 0 && index < scroll_content()->children().size() && + scroll_content()->children()[index] == view) { // ReorderChildView() would no-op in this case, but we still want to avoid // setting |needs_relayout_|. return; @@ -751,7 +751,7 @@ } void NetworkListView::UpdateInfoLabel(int message_id, - int insertion_index, + size_t insertion_index, TrayInfoLabel** info_label_ptr) { TrayInfoLabel* info_label = *info_label_ptr; if (!message_id) { @@ -771,10 +771,10 @@ *info_label_ptr = info_label; } -int NetworkListView::UpdateNetworkSectionHeader( +size_t NetworkListView::UpdateNetworkSectionHeader( chromeos::network_config::mojom::NetworkType type, bool enabled, - int child_index, + size_t child_index, NetworkSectionHeaderView* view, views::Separator** separator_view) { // Show or hide a separator above the header. The separator should only be
diff --git a/ash/system/network/network_list_view.h b/ash/system/network/network_list_view.h index 6eefb7f1..0d84c34c 100644 --- a/ash/system/network/network_list_view.h +++ b/ash/system/network/network_list_view.h
@@ -90,12 +90,12 @@ // connections. std::unique_ptr<std::set<std::string>> UpdateNetworkChildren( chromeos::network_config::mojom::NetworkType type, - int child_index); - void UpdateNetworkChild(int index, const NetworkInfo* info); + size_t child_index); + void UpdateNetworkChild(size_t index, const NetworkInfo* info); // Reorders children of |scroll_content()| as necessary placing |view| at // |index|. - void PlaceViewAtIndex(views::View* view, int index); + void PlaceViewAtIndex(views::View* view, size_t index); // Creates an info label with text specified by |message_id| and adds it to // |scroll_content()| if necessary or updates the text and reorders the @@ -104,17 +104,17 @@ // |scroll_content()| and destroys it. |info_label_ptr| is an in/out parameter // and is only modified if the info label is created or destroyed. void UpdateInfoLabel(int message_id, - int insertion_index, + size_t insertion_index, TrayInfoLabel** info_label_ptr); // Updates a cellular/Wi-Fi header row |view| and reorders the // |scroll_content()| placing the |view| at |child_index|. Returns the index // where the next child should be inserted, i.e., the index directly after the // last inserted child. - int UpdateNetworkSectionHeader( + size_t UpdateNetworkSectionHeader( chromeos::network_config::mojom::NetworkType type, bool enabled, - int child_index, + size_t child_index, NetworkSectionHeaderView* view, views::Separator** separator_view);
diff --git a/ash/system/network/network_list_view_controller_impl.cc b/ash/system/network/network_list_view_controller_impl.cc index 21dd0d0..3ca59700 100644 --- a/ash/system/network/network_list_view_controller_impl.cc +++ b/ash/system/network/network_list_view_controller_impl.cc
@@ -172,7 +172,7 @@ std::vector<NetworkStatePropertiesPtr> networks) { // Indicates the current position a view will be added to in // NetworkDetailedNetworkView scroll list. - int index = 0; + size_t index = 0; // Store current views in |previous_network_views|, views which have // a corresponding network in |networks| will be added back to @@ -288,8 +288,8 @@ model()->GetDeviceState(NetworkType::kWiFi) == DeviceStateType::kEnabled; } -int NetworkListViewControllerImpl::ShowConnectionWarningIfVpnOrProxy( - int index) { +size_t NetworkListViewControllerImpl::ShowConnectionWarningIfVpnOrProxy( + size_t index) { const NetworkStateProperties* default_network = model()->default_network(); bool using_proxy = default_network && default_network->proxy_mode != ProxyMode::kDirect; @@ -333,8 +333,8 @@ return true; } -int NetworkListViewControllerImpl::CreateSeparatorIfMissingAndReorder( - int index, +size_t NetworkListViewControllerImpl::CreateSeparatorIfMissingAndReorder( + size_t index, views::Separator** separator_view) { // Separator view should never be the first view in the list. DCHECK(index); @@ -551,9 +551,9 @@ std::move(info)); } -int NetworkListViewControllerImpl::CreateItemViewsIfMissingAndReorder( +size_t NetworkListViewControllerImpl::CreateItemViewsIfMissingAndReorder( NetworkType type, - int index, + size_t index, std::vector<NetworkStatePropertiesPtr>& networks, NetworkIdToViewMap* previous_views) { NetworkIdToViewMap id_to_view_map;
diff --git a/ash/system/network/network_list_view_controller_impl.h b/ash/system/network/network_list_view_controller_impl.h index f142c98..5ec45ee6 100644 --- a/ash/system/network/network_list_view_controller_impl.h +++ b/ash/system/network/network_list_view_controller_impl.h
@@ -96,7 +96,7 @@ // Adds a warning indicator if connected to a VPN or if the default network // has a proxy installed. - int ShowConnectionWarningIfVpnOrProxy(int index); + size_t ShowConnectionWarningIfVpnOrProxy(size_t index); // Returns true if mobile data section should be added to view. bool ShouldMobileDataSectionBeShown(); @@ -104,8 +104,8 @@ // Creates if missing and adds a Mobile or Wifi separator to the view. // Also reorders separator view in network list. A reference to the // separator is captured in |*separator_view|. - int CreateSeparatorIfMissingAndReorder(int index, - views::Separator** separator_view); + size_t CreateSeparatorIfMissingAndReorder(size_t index, + views::Separator** separator_view); // Updates Mobile data section, updates add eSIM button states and // calls UpdateMobileToggleAndSetStatusMessage(). @@ -126,9 +126,9 @@ // Creates a NetworkListNetworkItem if it does not exist else uses the // existing view, also reorders it in NetworkDetailedNetworkView scroll list. - int CreateItemViewsIfMissingAndReorder( + size_t CreateItemViewsIfMissingAndReorder( chromeos::network_config::mojom::NetworkType type, - int index, + size_t index, std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr>& networks, NetworkIdToViewMap* previous_views);
diff --git a/ash/system/phonehub/phone_hub_recent_app_button.cc b/ash/system/phonehub/phone_hub_recent_app_button.cc index ec0578e..25a4a2e 100644 --- a/ash/system/phonehub/phone_hub_recent_app_button.cc +++ b/ash/system/phonehub/phone_hub_recent_app_button.cc
@@ -5,7 +5,7 @@ #include "ash/system/phonehub/phone_hub_recent_app_button.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/tray/tray_popup_utils.h" +#include "ash/style/style_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/gfx/image/image_skia_operations.h" @@ -33,7 +33,7 @@ gfx::Size(kRecentAppButtonSize, kRecentAppButtonSize))); SetImageHorizontalAlignment(ALIGN_CENTER); SetImageVerticalAlignment(ALIGN_MIDDLE); - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::InstallCircleHighlightPathGenerator(this); SetAccessibleName(visible_app_name); SetTooltipText(visible_app_name);
diff --git a/ash/system/privacy_hub/microphone_privacy_switch_controller.cc b/ash/system/privacy_hub/microphone_privacy_switch_controller.cc deleted file mode 100644 index 38758fc..0000000 --- a/ash/system/privacy_hub/microphone_privacy_switch_controller.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/system/privacy_hub/microphone_privacy_switch_controller.h" - -#include <memory> - -#include "ash/components/audio/cras_audio_handler.h" -#include "ash/constants/ash_pref_names.h" -#include "ash/public/cpp/session/session_observer.h" -#include "ash/session/session_controller_impl.h" -#include "ash/shell.h" -#include "base/bind.h" -#include "components/prefs/pref_service.h" - -namespace ash { - -MicrophonePrivacySwitchController::MicrophonePrivacySwitchController() { - Shell::Get()->session_controller()->AddObserver(this); -} - -MicrophonePrivacySwitchController::~MicrophonePrivacySwitchController() { - Shell::Get()->session_controller()->RemoveObserver(this); -} - -void MicrophonePrivacySwitchController::OnActiveUserPrefServiceChanged( - PrefService* pref_service) { - // Subscribing again to pref changes. - pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>(); - pref_change_registrar_->Init(pref_service); - pref_change_registrar_->Add( - prefs::kUserMicrophoneAllowed, - base::BindRepeating( - &MicrophonePrivacySwitchController::OnPreferenceChanged, - base::Unretained(this))); -} - -void MicrophonePrivacySwitchController::OnPreferenceChanged() { - SetSystemMute(); -} - -void MicrophonePrivacySwitchController::SetSystemMute() { - const bool allowed = pref_change_registrar_->prefs()->GetBoolean( - prefs::kUserMicrophoneAllowed); - CrasAudioHandler::Get()->SetInputMute(!allowed); -} - -} // namespace ash
diff --git a/ash/system/privacy_hub/microphone_privacy_switch_controller.h b/ash/system/privacy_hub/microphone_privacy_switch_controller.h deleted file mode 100644 index 76bf61b3..0000000 --- a/ash/system/privacy_hub/microphone_privacy_switch_controller.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_SYSTEM_PRIVACY_HUB_MICROPHONE_PRIVACY_SWITCH_CONTROLLER_H_ -#define ASH_SYSTEM_PRIVACY_HUB_MICROPHONE_PRIVACY_SWITCH_CONTROLLER_H_ - -#include <memory> - -#include "ash/public/cpp/session/session_observer.h" -#include "components/prefs/pref_change_registrar.h" - -namespace ash { - -// This controller keeps the KUserMicrophoneAllowed preference and the state of -// the system input mute in sync. -class MicrophonePrivacySwitchController : public SessionObserver { - public: - MicrophonePrivacySwitchController(); - ~MicrophonePrivacySwitchController() override; - - MicrophonePrivacySwitchController(const MicrophonePrivacySwitchController&) = - delete; - MicrophonePrivacySwitchController& operator=( - const MicrophonePrivacySwitchController&) = delete; - - // SessionObserver: - void OnActiveUserPrefServiceChanged(PrefService* pref_service) override; - - private: - // A callback that is invoked when the user changes KUserMicrophoneAllowed - // preference from the Privacy Hub UI. - void OnPreferenceChanged(); - - // Updates the microphone mute status according to the user preference. - void SetSystemMute(); - - std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; -}; - -} // namespace ash - -#endif // ASH_SYSTEM_PRIVACY_HUB_MICROPHONE_PRIVACY_SWITCH_CONTROLLER_H_
diff --git a/ash/system/privacy_hub/microphone_privacy_switch_controller_unittest.cc b/ash/system/privacy_hub/microphone_privacy_switch_controller_unittest.cc deleted file mode 100644 index dfff985..0000000 --- a/ash/system/privacy_hub/microphone_privacy_switch_controller_unittest.cc +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/system/privacy_hub/microphone_privacy_switch_controller.h" - -#include "ash/components/audio/cras_audio_handler.h" -#include "ash/constants/ash_pref_names.h" -#include "ash/public/cpp/microphone_mute_notification_delegate.h" -#include "ash/session/session_controller_impl.h" -#include "ash/shell.h" -#include "ash/test/ash_test_base.h" - -namespace ash { - -class FakeMicrophoneMuteNotificationDelegate - : public MicrophoneMuteNotificationDelegate { - public: - absl::optional<std::u16string> GetAppAccessingMicrophone() override { - return absl::nullopt; - } -}; - -class MicrophonePrivacySwitchControllerTest : public AshTestBase { - public: - MicrophonePrivacySwitchControllerTest() = default; - ~MicrophonePrivacySwitchControllerTest() override = default; - - // AshTestBase: - void SetUp() override { - AshTestBase::SetUp(); - - // This makes sure a globale instance of MicrophoneMuteNotificationDelegate - // is created before running tests. - delegate_ = std::make_unique<FakeMicrophoneMuteNotificationDelegate>(); - } - - protected: - void SetUserPref(bool allowed) { - Shell::Get()->session_controller()->GetActivePrefService()->SetBoolean( - prefs::kUserMicrophoneAllowed, allowed); - } - - private: - std::unique_ptr<FakeMicrophoneMuteNotificationDelegate> delegate_; -}; - -TEST_F(MicrophonePrivacySwitchControllerTest, OnPreferenceChanged) { - static constexpr bool user_preferences[] = {false, true, false}; - - for (bool microphone_allowed : user_preferences) { - SetUserPref(microphone_allowed); - EXPECT_EQ(CrasAudioHandler::Get()->IsInputMuted(), !microphone_allowed); - } -} - -} // namespace ash
diff --git a/ash/system/tray/actionable_view.cc b/ash/system/tray/actionable_view.cc index 99ae53b..2217a71 100644 --- a/ash/system/tray/actionable_view.cc +++ b/ash/system/tray/actionable_view.cc
@@ -4,18 +4,18 @@ #include "ash/system/tray/actionable_view.h" +#include "ash/style/style_util.h" #include "ash/system/tray/tray_popup_utils.h" +#include "ash/system/tray/tray_utils.h" #include "base/bind.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/rect_f.h" -#include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/ink_drop_highlight.h" -#include "ui/views/animation/ink_drop_impl.h" -#include "ui/views/animation/ink_drop_mask.h" +#include "ui/views/animation/ink_drop_ripple.h" #include "ui/views/painter.h" namespace ash { @@ -36,12 +36,14 @@ SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); TrayPopupUtils::InstallHighlightPathGenerator(this, ink_drop_style_); views::InkDrop::Get(this)->SetCreateInkDropCallback(base::BindRepeating( - [](Button* host) { return TrayPopupUtils::CreateInkDrop(host); }, this)); - views::InkDrop::Get(this)->SetCreateHighlightCallback(base::BindRepeating( - &TrayPopupUtils::CreateInkDropHighlight, base::Unretained(this))); + [](Button* host) { return StyleUtil::CreateInkDrop(host); }, this)); + views::InkDrop::Get(this)->SetCreateHighlightCallback( + base::BindRepeating(&StyleUtil::CreateInkDropHighlight, + base::Unretained(this), gfx::kPlaceholderColor)); views::InkDrop::Get(this)->SetCreateRippleCallback(base::BindRepeating( [](ActionableView* host) { - return TrayPopupUtils::CreateInkDropRipple(host->ink_drop_style_, host); + return StyleUtil::CreateInkDropRipple( + GetInkDropInsets(host->ink_drop_style_), host); }, this)); }
diff --git a/ash/system/tray/system_menu_button.cc b/ash/system/tray/system_menu_button.cc index a930b7f7..9354d95 100644 --- a/ash/system/tray/system_menu_button.cc +++ b/ash/system/tray/system_menu_button.cc
@@ -5,9 +5,11 @@ #include "ash/system/tray/system_menu_button.h" #include "ash/style/ash_color_provider.h" +#include "ash/style/style_util.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_popup_ink_drop_style.h" #include "ash/system/tray/tray_popup_utils.h" +#include "ash/system/tray/tray_utils.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" @@ -37,8 +39,8 @@ SetTooltipText(l10n_util::GetStringUTF16(accessible_name_id)); - TrayPopupUtils::ConfigureTrayPopupButton( - this, TrayPopupInkDropStyle::HOST_CENTERED); + StyleUtil::SetUpInkDropForButton( + this, GetInkDropInsets(TrayPopupInkDropStyle::HOST_CENTERED)); TrayPopupUtils::InstallHighlightPathGenerator( this, TrayPopupInkDropStyle::HOST_CENTERED); views::FocusRing::Get(this)->SetColorId(ui::kColorAshFocusRing);
diff --git a/ash/system/tray/tray_popup_utils.cc b/ash/system/tray/tray_popup_utils.cc index d7e1f49..f00f81e 100644 --- a/ash/system/tray/tray_popup_utils.cc +++ b/ash/system/tray/tray_popup_utils.cc
@@ -17,20 +17,18 @@ #include "ash/system/tray/hover_highlight_view.h" #include "ash/system/tray/size_range_layout.h" #include "ash/system/tray/tray_constants.h" +#include "ash/system/tray/tray_utils.h" #include "ash/system/tray/unfocusable_label.h" #include "base/bind.h" #include "chromeos/ui/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/color/color_id.h" +#include "ui/compositor/layer.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/geometry/insets.h" +#include "ui/gfx/geometry/rrect_f.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_utils.h" -#include "ui/views/animation/flood_fill_ink_drop_ripple.h" -#include "ui/views/animation/ink_drop.h" -#include "ui/views/animation/ink_drop_highlight.h" -#include "ui/views/animation/ink_drop_impl.h" -#include "ui/views/animation/square_ink_drop_ripple.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/md_text_button.h" @@ -111,14 +109,6 @@ kTrayPopupItemMaxHeight)); } -gfx::Insets GetInkDropInsets(TrayPopupInkDropStyle ink_drop_style) { - if (ink_drop_style == TrayPopupInkDropStyle::HOST_CENTERED || - ink_drop_style == TrayPopupInkDropStyle::INSET_BOUNDS) { - return gfx::Insets(kTrayPopupInkDropInset); - } - return gfx::Insets(); -} - class HighlightPathGenerator : public views::HighlightPathGenerator { public: explicit HighlightPathGenerator(TrayPopupInkDropStyle ink_drop_style) @@ -227,23 +217,6 @@ kFocusBorderThickness, gfx::InsetsF()); } -void TrayPopupUtils::ConfigureTrayPopupButton( - views::Button* button, - TrayPopupInkDropStyle ink_drop_style, - bool highlight_on_hover, - bool highlight_on_focus) { - button->SetInstallFocusRingOnFocus(true); - views::InkDropHost* const ink_drop = views::InkDrop::Get(button); - ink_drop->SetMode(views::InkDropHost::InkDropMode::ON); - button->SetHasInkDropActionOnClick(true); - ink_drop->SetCreateInkDropCallback(base::BindRepeating( - &CreateInkDrop, button, highlight_on_hover, highlight_on_focus)); - ink_drop->SetCreateRippleCallback( - base::BindRepeating(&CreateInkDropRipple, ink_drop_style, button)); - ink_drop->SetCreateHighlightCallback( - base::BindRepeating(&CreateInkDropHighlight, button)); -} - void TrayPopupUtils::ConfigureAsStickyHeader(views::View* view) { view->SetID(VIEW_ID_STICKY_HEADER); view->SetBorder(views::CreateEmptyBorder( @@ -273,35 +246,6 @@ return separator; } -std::unique_ptr<views::InkDrop> TrayPopupUtils::CreateInkDrop( - views::Button* host, - bool highlight_on_hover, - bool highlight_on_focus) { - return views::InkDrop::CreateInkDropForFloodFillRipple( - views::InkDrop::Get(host), highlight_on_hover, highlight_on_focus); -} - -std::unique_ptr<views::InkDropRipple> TrayPopupUtils::CreateInkDropRipple( - TrayPopupInkDropStyle ink_drop_style, - const views::Button* host) { - const std::pair<SkColor, float> base_color_and_opacity = - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity(); - return std::make_unique<views::FloodFillInkDropRipple>( - host->size(), GetInkDropInsets(ink_drop_style), - views::InkDrop::Get(host)->GetInkDropCenterBasedOnLastEvent(), - base_color_and_opacity.first, base_color_and_opacity.second); -} - -std::unique_ptr<views::InkDropHighlight> TrayPopupUtils::CreateInkDropHighlight( - const views::View* host) { - const std::pair<SkColor, float> base_color_and_opacity = - AshColorProvider::Get()->GetInkDropBaseColorAndOpacity(); - auto highlight = std::make_unique<views::InkDropHighlight>( - gfx::SizeF(host->size()), base_color_and_opacity.first); - highlight->set_visible_opacity(base_color_and_opacity.second); - return highlight; -} - void TrayPopupUtils::InstallHighlightPathGenerator( views::View* host, TrayPopupInkDropStyle ink_drop_style) {
diff --git a/ash/system/tray/tray_popup_utils.h b/ash/system/tray/tray_popup_utils.h index 92bae35..294814dd8 100644 --- a/ash/system/tray/tray_popup_utils.h +++ b/ash/system/tray/tray_popup_utils.h
@@ -18,9 +18,6 @@ namespace views { class Button; class ImageView; -class InkDrop; -class InkDropRipple; -class InkDropHighlight; class Label; class LabelButton; class Painter; @@ -125,13 +122,6 @@ // Creates a default focus painter used for most things in tray popups. static std::unique_ptr<views::Painter> CreateFocusPainter(); - // Common setup for various buttons in the system menu. - static void ConfigureTrayPopupButton( - views::Button* button, - TrayPopupInkDropStyle ink_drop_style = TrayPopupInkDropStyle::FILL_BOUNDS, - bool highlight_on_hover = false, - bool highlight_on_focus = false); - // Sets up |view| to be a sticky header in a tray detail scroll view. static void ConfigureAsStickyHeader(views::View* view); @@ -154,32 +144,6 @@ // returned separator. static views::Separator* CreateVerticalSeparator(); - // Creates in InkDrop instance for |host|. - // All styles are configured to show the highlight when the ripple is visible. - // - // All targetable views in the system menu should delegate - // InkDropHost::CreateInkDrop() calls here. - static std::unique_ptr<views::InkDrop> CreateInkDrop( - views::Button* host, - bool highlight_on_hover = false, - bool highlight_on_focus = false); - - // Creates an InkDropRipple instance for |host| according to the - // |ink_drop_style|. The ripple will be centered on |center_point|. - // - // All targetable views in the system menu should delegate - // InkDropHost::CreateInkDropRipple() calls here. - static std::unique_ptr<views::InkDropRipple> CreateInkDropRipple( - TrayPopupInkDropStyle ink_drop_style, - const views::Button* host); - - // Creates in InkDropHighlight instance for |host|. - // - // All targetable views in the system menu should delegate - // InkDropHost::CreateInkDropHighlight() calls here. - static std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight( - const views::View* host); - // Installs a HighlightPathGenerator matching the TrayPopupInkDropStyle. static void InstallHighlightPathGenerator( views::View* host,
diff --git a/ash/system/tray/tray_utils.cc b/ash/system/tray/tray_utils.cc index bce61249..0d0875b 100644 --- a/ash/system/tray/tray_utils.cc +++ b/ash/system/tray/tray_utils.cc
@@ -144,4 +144,12 @@ return insets; } +gfx::Insets GetInkDropInsets(TrayPopupInkDropStyle ink_drop_style) { + if (ink_drop_style == TrayPopupInkDropStyle::HOST_CENTERED || + ink_drop_style == TrayPopupInkDropStyle::INSET_BOUNDS) { + return gfx::Insets(kTrayPopupInkDropInset); + } + return gfx::Insets(); +} + } // namespace ash
diff --git a/ash/system/tray/tray_utils.h b/ash/system/tray/tray_utils.h index 587cec8..f64d9c5d5 100644 --- a/ash/system/tray/tray_utils.h +++ b/ash/system/tray/tray_utils.h
@@ -7,6 +7,7 @@ #include <cstdint> +#include "ash/system/tray/tray_popup_ink_drop_style.h" #include "components/session_manager/session_manager_types.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" @@ -50,6 +51,9 @@ // bubbles. (Palette Tray, IME Tray). gfx::Insets GetSecondaryBubbleInsets(); +// Gets the InkDrop insets based on `ink_drop_style`. +gfx::Insets GetInkDropInsets(TrayPopupInkDropStyle ink_drop_style); + } // namespace ash #endif // ASH_SYSTEM_TRAY_TRAY_UTILS_H_
diff --git a/ash/system/unified/custom_shape_button.cc b/ash/system/unified/custom_shape_button.cc index 76cd680..92db30aa 100644 --- a/ash/system/unified/custom_shape_button.cc +++ b/ash/system/unified/custom_shape_button.cc
@@ -5,7 +5,7 @@ #include "ash/system/unified/custom_shape_button.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/tray/tray_popup_utils.h" +#include "ash/style/style_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/compositor/paint_recorder.h" @@ -37,7 +37,7 @@ CustomShapeButton::CustomShapeButton(PressedCallback callback) : ImageButton(std::move(callback)) { - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::HighlightPathGenerator::Install( this, std::make_unique<CustomShapeButtonHighlightPathGenerator>()); views::FocusRing::Get(this)->SetColorId(ui::kColorAshFocusRing);
diff --git a/ash/system/unified/deferred_update_dialog.cc b/ash/system/unified/deferred_update_dialog.cc new file mode 100644 index 0000000..80dfd5af --- /dev/null +++ b/ash/system/unified/deferred_update_dialog.cc
@@ -0,0 +1,110 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/system/unified/deferred_update_dialog.h" + +#include "ash/strings/grit/ash_strings.h" +#include "chromeos/ash/components/dbus/update_engine/update_engine_client.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/chromeos/resources/grit/ui_chromeos_resources.h" +#include "ui/views/bubble/bubble_dialog_model_host.h" +#include "ui/views/window/dialog_delegate.h" + +namespace ash { + +DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(DeferredUpdateDialog, + kAutoUpdateCheckboxId); +DeferredUpdateDialog* DeferredUpdateDialog::dialog_ = nullptr; + +// static +void DeferredUpdateDialog::CreateDialog(Action callback_action, + base::OnceClosure callback) { + // Avoid duplicate dialogs. + if (dialog_) + return; + + // dialog_ will be released when the dialog is closed. + dialog_ = new DeferredUpdateDialog(); + + auto ok_text = callback_action == kSignOut + ? IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SIGN_OUT + : IDS_DEFERRED_UPDATE_DIALOG_UPDATE_SHUT_DOWN; + auto cancel_text = callback_action == kSignOut + ? IDS_DEFERRED_UPDATE_DIALOG_SIGN_OUT + : IDS_DEFERRED_UPDATE_DIALOG_SHUT_DOWN; + std::unique_ptr<ui::DialogModel> dialog_model = + ui::DialogModel::Builder(std::make_unique<ui::DialogModelDelegate>()) + .SetTitle(l10n_util::GetStringUTF16(IDS_DEFERRED_UPDATE_DIALOG_TITLE)) + .AddOkButton( + base::BindOnce(&DeferredUpdateDialog::OnApplyDeferredUpdate, + base::Unretained(dialog_)), + l10n_util::GetStringUTF16(ok_text)) + .AddCancelButton( + base::BindOnce(&DeferredUpdateDialog::OnContinueWithoutUpdate, + base::Unretained(dialog_)), + l10n_util::GetStringUTF16(cancel_text)) + .AddBodyText(ui::DialogModelLabel( + l10n_util::GetStringUTF16(IDS_DEFERRED_UPDATE_DIALOG_TEXT))) + .AddCheckbox(kAutoUpdateCheckboxId, + ui::DialogModelLabel(l10n_util::GetStringUTF16( + IDS_DEFERRED_UPDATE_DIALOG_CHECKBOX))) + .SetDialogDestroyingCallback( + base::BindOnce(&DeferredUpdateDialog::OnDialogClosing, + base::Unretained(dialog_), std::move(callback))) + .Build(); + + dialog_->dialog_model_ = dialog_model.get(); + dialog_->dialog_result_ = kClose; + + auto bubble = views::BubbleDialogModelHost::CreateModal( + std::move(dialog_model), ui::MODAL_TYPE_SYSTEM); + bubble->SetOwnedByWidget(true); + views::DialogDelegate::CreateDialogWidget(std::move(bubble), + /*context=*/nullptr, + /*parent=*/nullptr) + ->Show(); +} + +// Invoked when "ok" button is clicked. +void DeferredUpdateDialog::OnApplyDeferredUpdate() { + DCHECK(dialog_model_); + ui::DialogModelCheckbox* check_box = + dialog_model_->GetCheckboxByUniqueId(kAutoUpdateCheckboxId); + if (check_box && check_box->is_checked()) { + dialog_result_ = kApplyAutoUpdate; + } else { + dialog_result_ = kApplyUpdate; + } +} + +// Invoked when "cancel" button is clicked. +void DeferredUpdateDialog::OnContinueWithoutUpdate() { + dialog_result_ = kIgnoreUpdate; +} + +// Invoked when the dialog is closing. +void DeferredUpdateDialog::OnDialogClosing(base::OnceClosure callback) { + dialog_model_ = nullptr; + + switch (dialog_result_) { + case kApplyAutoUpdate: + UpdateEngineClient::Get()->ToggleFeature( + update_engine::kFeatureConsumerAutoUpdate, + /*enable=*/true); + [[fallthrough]]; + case kApplyUpdate: + UpdateEngineClient::Get()->ApplyDeferredUpdate(std::move(callback)); + break; + case kIgnoreUpdate: + std::move(callback).Run(); + break; + case kClose: + break; + } + + delete this; + dialog_ = nullptr; +} + +} // namespace ash \ No newline at end of file
diff --git a/ash/system/unified/deferred_update_dialog.h b/ash/system/unified/deferred_update_dialog.h new file mode 100644 index 0000000..287186c --- /dev/null +++ b/ash/system/unified/deferred_update_dialog.h
@@ -0,0 +1,57 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_SYSTEM_UNIFIED_DEFERRED_UPDATE_DIALOG_H_ +#define ASH_SYSTEM_UNIFIED_DEFERRED_UPDATE_DIALOG_H_ + +#include "base/callback.h" +#include "ui/base/models/dialog_model.h" + +namespace ash { + +class DeferredUpdateDialog { + public: + enum Action { + kShutDown, + kSignOut, + }; + + DeferredUpdateDialog(DeferredUpdateDialog&) = delete; + DeferredUpdateDialog& operator=(DeferredUpdateDialog&) = delete; + virtual ~DeferredUpdateDialog() = default; + + // Shows the deferred update dialog. + static void CreateDialog(Action callback_action, base::OnceClosure callback); + + private: + enum DialogResult { + // Apply the deferred update and enables automatic update. + kApplyAutoUpdate, + // Apply the deferred update. + kApplyUpdate, + // Ignore the deferred update and run the callback passed in. + kIgnoreUpdate, + // Close the dialog without doing anything. + kClose, + }; + + DeferredUpdateDialog() = default; + + // Invoked when "ok" button is clicked. + void OnApplyDeferredUpdate(); + // Invoked when "cancel" button is clicked. + void OnContinueWithoutUpdate(); + // Invoked when the dialog is closing. + void OnDialogClosing(base::OnceClosure callback); + + DECLARE_CLASS_ELEMENT_IDENTIFIER_VALUE(kAutoUpdateCheckboxId); + static DeferredUpdateDialog* dialog_; + + ui::DialogModel* dialog_model_ = nullptr; + DialogResult dialog_result_ = kClose; +}; + +} // namespace ash + +#endif // ASH_SYSTEM_UNIFIED_DEFERRED_UPDATE_DIALOG_H_
diff --git a/ash/system/unified/feature_pod_button.cc b/ash/system/unified/feature_pod_button.cc index f836905..d8597fa 100644 --- a/ash/system/unified/feature_pod_button.cc +++ b/ash/system/unified/feature_pod_button.cc
@@ -7,8 +7,8 @@ #include "ash/resources/vector_icons/vector_icons.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" +#include "ash/style/style_util.h" #include "ash/system/tray/tray_constants.h" -#include "ash/system/tray/tray_popup_utils.h" #include "ash/system/unified/feature_pod_controller_base.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" @@ -88,7 +88,7 @@ AddChildView(detailed_view_arrow_); AddChildView(sub_label_); - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false);
diff --git a/ash/system/unified/unified_system_tray_controller.cc b/ash/system/unified/unified_system_tray_controller.cc index 880a41b..4e12ccf 100644 --- a/ash/system/unified/unified_system_tray_controller.cc +++ b/ash/system/unified/unified_system_tray_controller.cc
@@ -36,6 +36,7 @@ #include "ash/system/media/unified_media_controls_detailed_view_controller.h" #include "ash/system/model/clock_model.h" #include "ash/system/model/system_tray_model.h" +#include "ash/system/model/update_model.h" #include "ash/system/nearby_share/nearby_share_feature_pod_controller.h" #include "ash/system/network/network_detailed_view_controller.h" #include "ash/system/network/network_feature_pod_controller.h" @@ -50,6 +51,7 @@ #include "ash/system/time/unified_calendar_view_controller.h" #include "ash/system/tray/system_tray_item_uma_type.h" #include "ash/system/tray/tray_constants.h" +#include "ash/system/unified/deferred_update_dialog.h" #include "ash/system/unified/detailed_view_controller.h" #include "ash/system/unified/feature_pod_button.h" #include "ash/system/unified/feature_pod_controller_base.h" @@ -182,7 +184,15 @@ base::RecordAction(base::UserMetricsAction("StatusArea_SignOut")); if (Shell::Get()->session_controller()->IsDemoSession()) base::RecordAction(base::UserMetricsAction("DemoMode.ExitFromSystemTray")); - Shell::Get()->session_controller()->RequestSignOut(); + + if (HasDeferredUpdate()) { + DeferredUpdateDialog::CreateDialog( + DeferredUpdateDialog::Action::kSignOut, + base::BindOnce(&SessionControllerImpl::RequestSignOut, + base::Unretained(Shell::Get()->session_controller()))); + } else { + Shell::Get()->session_controller()->RequestSignOut(); + } } void UnifiedSystemTrayController::HandleLockAction() { @@ -200,9 +210,18 @@ void UnifiedSystemTrayController::HandlePowerAction() { base::RecordAction(base::UserMetricsAction("Tray_ShutDown")); - Shell::Get()->lock_state_controller()->RequestShutdown( - ShutdownReason::TRAY_SHUT_DOWN_BUTTON); - CloseBubble(); + + if (HasDeferredUpdate()) { + DeferredUpdateDialog::CreateDialog( + DeferredUpdateDialog::Action::kShutDown, + base::BindOnce(&LockStateController::RequestShutdown, + base::Unretained(Shell::Get()->lock_state_controller()), + ShutdownReason::TRAY_SHUT_DOWN_BUTTON)); + } else { + Shell::Get()->lock_state_controller()->RequestShutdown( + ShutdownReason::TRAY_SHUT_DOWN_BUTTON); + CloseBubble(); + } } void UnifiedSystemTrayController::HandlePageSwitchAction(int page) { @@ -665,4 +684,8 @@ return base::Milliseconds(kSystemMenuCollapseExpandAnimationDurationMs); } +bool UnifiedSystemTrayController::HasDeferredUpdate() const { + return Shell::Get()->system_tray_model()->update_model()->update_deferred(); +} + } // namespace ash
diff --git a/ash/system/unified/unified_system_tray_controller.h b/ash/system/unified/unified_system_tray_controller.h index fc29efe..d7f11f68 100644 --- a/ash/system/unified/unified_system_tray_controller.h +++ b/ash/system/unified/unified_system_tray_controller.h
@@ -245,6 +245,8 @@ // views::AnimationDelegateViews: base::TimeDelta GetAnimationDurationForReporting() const override; + bool HasDeferredUpdate() const; + // Model that stores UI specific variables. Unowned. scoped_refptr<UnifiedSystemTrayModel> model_;
diff --git a/ash/system/update/update_notification_controller.cc b/ash/system/update/update_notification_controller.cc index 4caabdd..220609a 100644 --- a/ash/system/update/update_notification_controller.cc +++ b/ash/system/update/update_notification_controller.cc
@@ -21,6 +21,7 @@ #include "base/metrics/user_metrics.h" #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" +#include "chromeos/ash/components/dbus/update_engine/update_engine_client.h" #include "components/vector_icons/vector_icons.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/l10n/l10n_util.h" @@ -105,7 +106,14 @@ RelaunchNotificationState::kRequired) notification->SetSystemPriority(); - if (model_->update_required()) { + if (model_->update_deferred()) { + notification->set_buttons({ + message_center::ButtonInfo(l10n_util::GetStringUTF16( + IDS_UPDATE_NOTIFICATION_APPLY_UPDATE_BUTTON)), + message_center::ButtonInfo(l10n_util::GetStringUTF16( + IDS_UPDATE_NOTIFICATION_AUTOMATIC_UPDATE_BUTTON)), + }); + } else if (model_->update_required()) { std::vector<message_center::ButtonInfo> notification_actions; if (model_->rollback()) { notification_actions.push_back(message_center::ButtonInfo( @@ -132,7 +140,8 @@ } bool UpdateNotificationController::ShouldShowUpdate() const { - return model_->update_required() || model_->update_over_cellular_available(); + return model_->update_required() || + model_->update_over_cellular_available() || model_->update_deferred(); } std::u16string UpdateNotificationController::GetTitle() const { @@ -189,6 +198,11 @@ if (model_->update_type() == UpdateType::kLacros) return l10n_util::GetStringUTF16(IDS_UPDATE_NOTIFICATION_MESSAGE_LACROS); + if (model_->update_deferred()) { + return l10n_util::GetStringUTF16( + IDS_UPDATE_NOTIFICATION_MESSAGE_DEFERRED_UPDATE); + } + const std::u16string system_app_name = l10n_util::GetStringUTF16(IDS_ASH_MESSAGE_CENTER_SYSTEM_APP_NAME); if (model_->factory_reset_required() && !model_->rollback()) { @@ -295,30 +309,38 @@ return; } - // Restart - DCHECK(button_index.value() == 0); - message_center::MessageCenter::Get()->RemoveNotification(kNotificationId, - false /* by_user */); + if (button_index.value() == 0) { + message_center::MessageCenter::Get()->RemoveNotification( + kNotificationId, false /* by_user */); - if (model_->update_required()) { - if (slow_boot_file_path_exists_) { - // An active dialog exists already. - if (confirmation_dialog_) - return; + if (model_->update_deferred()) { + // When the "update" button is clicked, apply the deferred update. + ash::UpdateEngineClient::Get()->ApplyDeferredUpdate(base::DoNothing()); + } else if (model_->update_required()) { + // Restart + if (slow_boot_file_path_exists_) { + // An active dialog exists already. + if (confirmation_dialog_) + return; - confirmation_dialog_ = new ShutdownConfirmationDialog( - IDS_DIALOG_TITLE_SLOW_BOOT, IDS_DIALOG_MESSAGE_SLOW_BOOT, - base::BindOnce(&UpdateNotificationController::RestartForUpdate, - weak_ptr_factory_.GetWeakPtr()), - base::BindOnce(&UpdateNotificationController::RestartCancelled, - weak_ptr_factory_.GetWeakPtr())); + confirmation_dialog_ = new ShutdownConfirmationDialog( + IDS_DIALOG_TITLE_SLOW_BOOT, IDS_DIALOG_MESSAGE_SLOW_BOOT, + base::BindOnce(&UpdateNotificationController::RestartForUpdate, + weak_ptr_factory_.GetWeakPtr()), + base::BindOnce(&UpdateNotificationController::RestartCancelled, + weak_ptr_factory_.GetWeakPtr())); + } else { + RestartForUpdate(); + } } else { - RestartForUpdate(); + // Shows the about chrome OS page and checks for update after the page is + // loaded. + Shell::Get()->system_tray_model()->client()->ShowAboutChromeOS(); } } else { - // Shows the about chrome OS page and checks for update after the page is - // loaded. - Shell::Get()->system_tray_model()->client()->ShowAboutChromeOS(); + // When the "automatic update" button is clicked, take user to the ChromeOS + // additional details page that has the automatic update toggle. + Shell::Get()->system_tray_model()->client()->ShowAboutChromeOSDetails(); } }
diff --git a/ash/system/update/update_notification_controller_unittest.cc b/ash/system/update/update_notification_controller_unittest.cc index 284a844b..ea4a3c6 100644 --- a/ash/system/update/update_notification_controller_unittest.cc +++ b/ash/system/update/update_notification_controller_unittest.cc
@@ -685,4 +685,26 @@ EXPECT_EQ(1, GetSessionControllerClient()->attempt_restart_chrome_count()); } +TEST_F(UpdateNotificationControllerTest, VisibilityAfterDeferredUpdate) { + // Simulate a deferred update. + Shell::Get()->system_tray_model()->SetUpdateDeferred(true); + + // Wait until everything is complete and then check if the notification is + // visible. + task_environment()->RunUntilIdle(); + + // The notification is now visible. + ASSERT_TRUE(HasNotification()); + EXPECT_EQ(kSystemNotificationColorNormal, *GetNotificationColor()); + EXPECT_TRUE(strcmp(kSystemMenuUpdateIcon.name, GetNotificationIcon().name) == + 0); + EXPECT_EQ("Update available", GetNotificationTitle()); + EXPECT_EQ( + "Get the latest features and security improvements. Updates happen in " + "the background.", + GetNotificationMessage()); + EXPECT_EQ("Update", GetNotificationButton(0)); + EXPECT_EQ("Automatic updates", GetNotificationButton(1)); +} + } // namespace ash
diff --git a/ash/test/ash_test_base.cc b/ash/test/ash_test_base.cc index de98a34c..dfd11299 100644 --- a/ash/test/ash_test_base.cc +++ b/ash/test/ash_test_base.cc
@@ -27,7 +27,6 @@ #include "ash/shell.h" #include "ash/system/status_area_widget.h" #include "ash/test/ash_test_helper.h" -#include "ash/test/ash_test_ui_stabilizer.h" #include "ash/test/test_widget_builder.h" #include "ash/test/test_window_builder.h" #include "ash/test_shell_delegate.h" @@ -122,12 +121,6 @@ } void AshTestBase::SetUp(std::unique_ptr<TestShellDelegate> delegate) { - // In pixel tests, override the current time before setting up system UI - // components so that the components relying on the time, like the time view, - // show as expected. - if (ui_stabilizer_) - ui_stabilizer_->OverrideTime(); - // At this point, the task APIs should already be provided by // |task_environment_|. CHECK(base::ThreadTaskRunnerHandle::IsSet()); @@ -139,13 +132,9 @@ params.start_session = start_session_; params.delegate = std::move(delegate); params.local_state = local_state(); + params.is_pixel_test = is_pixel_test_; ash_test_helper_ = std::make_unique<AshTestHelper>(); ash_test_helper_->SetUp(std::move(params)); - - if (ui_stabilizer_) { - SimulateUserLogin(ui_stabilizer_->account_id()); - ui_stabilizer_->StabilizeUi(GetPrimaryDisplay().size()); - } } void AshTestBase::TearDown() { @@ -335,11 +324,10 @@ // stabilizes the system UI for pixel tests should be executed during setup. CHECK(!setup_called_); - CHECK(!ui_stabilizer_); - ui_stabilizer_ = std::make_unique<AshTestUiStabilizer>(); + is_pixel_test_ = true; // In pixel tests, a fake user account is used to set the wallpaper. - // Therefore, do not start the session as default. + // Therefore, do not start the session by default. start_session_ = false; } @@ -386,10 +374,7 @@ void AshTestBase::SimulateUserLogin(const AccountId& account_id, user_manager::UserType user_type) { - TestSessionControllerClient* session = GetSessionControllerClient(); - session->AddUserSession(account_id, account_id.GetUserEmail(), user_type); - session->SwitchActiveUser(account_id); - session->SetSessionState(SessionState::ACTIVE); + ash_test_helper_->SimulateUserLogin(account_id, user_type); } void AshTestBase::SimulateNewUserFirstLogin(const std::string& user_email) {
diff --git a/ash/test/ash_test_base.h b/ash/test/ash_test_base.h index 90bbbfa..9a44a1f 100644 --- a/ash/test/ash_test_base.h +++ b/ash/test/ash_test_base.h
@@ -69,7 +69,6 @@ class AmbientAshTestHelper; class AppListTestHelper; class AshTestHelper; -class AshTestUiStabilizer; class Shelf; class TestAppListClient; class TestShellDelegate; @@ -333,6 +332,9 @@ // SetUp() doesn't activate session if this is set to false. bool start_session_ = true; + // True if the test is a pixel diff test. Set by `PrepareForPixelDiffTest()`. + bool is_pixel_test_ = false; + // |task_environment_| is initialized-once at construction time but // subclasses may elect to provide their own. std::unique_ptr<base::test::TaskEnvironment> task_environment_; @@ -344,9 +346,6 @@ std::unique_ptr<AshTestHelper> ash_test_helper_; std::unique_ptr<ui::test::EventGenerator> event_generator_; - - // Used only for pixel tests. Set by `PrepareForPixelDiffTest()`. - std::unique_ptr<AshTestUiStabilizer> ui_stabilizer_; }; class NoSessionAshTestBase : public AshTestBase {
diff --git a/ash/test/ash_test_helper.cc b/ash/test/ash_test_helper.cc index 6c77d237..3a7c153 100644 --- a/ash/test/ash_test_helper.cc +++ b/ash/test/ash_test_helper.cc
@@ -28,6 +28,7 @@ #include "ash/system/message_center/session_state_notification_blocker.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/screen_layout_observer.h" +#include "ash/test/ash_test_ui_stabilizer.h" #include "ash/test/ash_test_views_delegate.h" #include "ash/test/toplevel_window.h" #include "ash/test_shell_delegate.h" @@ -232,6 +233,11 @@ } void AshTestHelper::SetUp(InitParams init_params) { + if (init_params.is_pixel_test) { + ui_stabilizer_ = std::make_unique<AshTestUiStabilizer>(); + ui_stabilizer_->OverrideTime(); + } + // This block of objects are conditionally initialized here rather than in the // constructor to make it easier for test classes to override them. if (!input_method::InputMethodManager::Get()) { @@ -360,6 +366,16 @@ // Fake the |ec_lid_angle_driver_status_| in the unittests. AccelerometerReader::GetInstance()->SetECLidAngleDriverStatusForTesting( ECLidAngleDriverStatus::NOT_SUPPORTED); + + if (init_params.is_pixel_test) { + SimulateUserLogin(ui_stabilizer_->account_id()); + + const gfx::Size primary_display_size = + display::Screen::GetScreen() + ->GetDisplayNearestWindow(Shell::GetPrimaryRootWindow()) + .size(); + ui_stabilizer_->StabilizeUi(primary_display_size); + } } display::Display AshTestHelper::GetSecondaryDisplay() const { @@ -367,4 +383,13 @@ .GetSecondaryDisplay(); } +void AshTestHelper::SimulateUserLogin(const AccountId& account_id, + user_manager::UserType user_type) { + session_controller_client_->AddUserSession( + account_id, account_id.GetUserEmail(), user_type); + session_controller_client_->SwitchActiveUser(account_id); + session_controller_client_->SetSessionState( + session_manager::SessionState::ACTIVE); +} + } // namespace ash
diff --git a/ash/test/ash_test_helper.h b/ash/test/ash_test_helper.h index 081cecd..37773d2 100644 --- a/ash/test/ash_test_helper.h +++ b/ash/test/ash_test_helper.h
@@ -47,6 +47,7 @@ class AppListTestHelper; class AmbientAshTestHelper; +class AshTestUiStabilizer; class TestKeyboardControllerObserver; class TestNewWindowDelegateProvider; class TestWallpaperControllerClient; @@ -70,6 +71,9 @@ // If this is not set, a TestShellDelegate will be used automatically. std::unique_ptr<ShellDelegate> delegate; PrefService* local_state = nullptr; + + // True if the initialized test is a pixel diff test. + bool is_pixel_test = false; }; // Instantiates/destroys an AshTestHelper. This can happen in a @@ -104,6 +108,12 @@ display::Display GetSecondaryDisplay() const; + // Simulates a user sign-in. It creates a new user session, adds it to + // existing user sessions and makes it the active user session. + void SimulateUserLogin( + const AccountId& account_id, + user_manager::UserType user_type = user_manager::USER_TYPE_REGULAR); + TestSessionControllerClient* test_session_controller_client() { return session_controller_client_.get(); } @@ -174,6 +184,10 @@ test_keyboard_controller_observer_; std::unique_ptr<AmbientAshTestHelper> ambient_ash_test_helper_; std::unique_ptr<TestWallpaperControllerClient> wallpaper_controller_client_; + + // Used only for pixel tests. + std::unique_ptr<AshTestUiStabilizer> ui_stabilizer_; + chromeos::bluetooth_config::ScopedBluetoothConfigTestHelper scoped_bluetooth_config_test_helper_;
diff --git a/ash/webui/eche_app_ui/eche_app_manager_unittest.cc b/ash/webui/eche_app_ui/eche_app_manager_unittest.cc index 37d4595f..8172683 100644 --- a/ash/webui/eche_app_ui/eche_app_manager_unittest.cc +++ b/ash/webui/eche_app_ui/eche_app_manager_unittest.cc
@@ -68,6 +68,7 @@ const char kFakeBoardName[] = "atlas"; const char kFakeGaiaId[] = "123"; const size_t kNumTestDevices = 3; +const char kFakeDeviceType[] = "Chromebook"; class EcheAppManagerTest : public testing::Test { public: @@ -113,6 +114,7 @@ .SetDeviceName(kFakeDeviceName) .SetBoardName(kFakeBoardName) .SetGaiaId(kFakeGaiaId) + .SetDeviceType(kFakeDeviceType) .Build(), fake_phone_hub_manager_.get(), fake_device_sync_client_.get(), fake_multidevice_setup_client_.get(), fake_secure_channel_client_.get(),
diff --git a/ash/webui/eche_app_ui/system_info.cc b/ash/webui/eche_app_ui/system_info.cc index e232160..424d263 100644 --- a/ash/webui/eche_app_ui/system_info.cc +++ b/ash/webui/eche_app_ui/system_info.cc
@@ -14,7 +14,8 @@ SystemInfo::Builder::~Builder() = default; std::unique_ptr<SystemInfo> SystemInfo::Builder::Build() { - return base::WrapUnique(new SystemInfo(device_name_, board_name_, gaia_id_)); + return base::WrapUnique( + new SystemInfo(device_name_, board_name_, gaia_id_, device_type_)); } SystemInfo::Builder& SystemInfo::Builder::SetDeviceName( @@ -35,14 +36,24 @@ return *this; } +SystemInfo::Builder& SystemInfo::Builder::SetDeviceType( + const std::string& device_type) { + device_type_ = device_type; + return *this; +} + SystemInfo::SystemInfo(const SystemInfo& other) = default; SystemInfo::~SystemInfo() = default; SystemInfo::SystemInfo(const std::string& device_name, const std::string& board_name, - const std::string& gaia_id) - : device_name_(device_name), board_name_(board_name), gaia_id_(gaia_id) {} + const std::string& gaia_id, + const std::string& device_type) + : device_name_(device_name), + board_name_(board_name), + gaia_id_(gaia_id), + device_type_(device_type) {} } // namespace eche_app } // namespace ash
diff --git a/ash/webui/eche_app_ui/system_info.h b/ash/webui/eche_app_ui/system_info.h index 55541e58..3e3aa98 100644 --- a/ash/webui/eche_app_ui/system_info.h +++ b/ash/webui/eche_app_ui/system_info.h
@@ -23,11 +23,13 @@ Builder& SetBoardName(const std::string& board_name); Builder& SetDeviceName(const std::string& device_name); Builder& SetGaiaId(const std::string& gaia_id); + Builder& SetDeviceType(const std::string& device_type); private: std::string board_name_; std::string device_name_; std::string gaia_id_; + std::string device_type_; }; SystemInfo(const SystemInfo& other); @@ -36,16 +38,19 @@ std::string GetDeviceName() const { return device_name_; } std::string GetBoardName() const { return board_name_; } std::string GetGaiaId() const { return gaia_id_; } + std::string GetDeviceType() const { return device_type_; } protected: SystemInfo(const std::string& device_name, const std::string& board_name, - const std::string& gaia_id); + const std::string& gaia_id, + const std::string& device_type); private: std::string device_name_; std::string board_name_; std::string gaia_id_; + std::string device_type_; }; } // namespace eche_app
diff --git a/ash/webui/eche_app_ui/system_info_provider.cc b/ash/webui/eche_app_ui/system_info_provider.cc index 656521d7..ae2feda1 100644 --- a/ash/webui/eche_app_ui/system_info_provider.cc +++ b/ash/webui/eche_app_ui/system_info_provider.cc
@@ -24,6 +24,7 @@ const char kJsonWifiConnectionStateKey[] = "wifi_connection_state"; const char kJsonDebugModeKey[] = "debug_mode"; const char kJsonGaiaIdKey[] = "gaia_id"; +const char kJsonDeviceTypeKey[] = "device_type"; using chromeos::network_config::mojom::ConnectionStateType; // TODO(https://crbug.com/1164001): remove when it moved to ash. @@ -71,6 +72,8 @@ json_dictionary.SetBoolKey(kJsonTabletModeKey, TabletMode::Get()->InTabletMode()); json_dictionary.SetStringKey(kJsonGaiaIdKey, system_info_->GetGaiaId()); + json_dictionary.SetStringKey(kJsonDeviceTypeKey, + system_info_->GetDeviceType()); auto found_type = CONNECTION_STATE_TYPE.find(wifi_connection_state_); std::string connecton_state_string = found_type == CONNECTION_STATE_TYPE.end() ? "" : found_type->second;
diff --git a/ash/webui/eche_app_ui/system_info_provider.h b/ash/webui/eche_app_ui/system_info_provider.h index dad6e0a9..101692c 100644 --- a/ash/webui/eche_app_ui/system_info_provider.h +++ b/ash/webui/eche_app_ui/system_info_provider.h
@@ -22,6 +22,7 @@ extern const char kJsonWifiConnectionStateKey[]; extern const char kJsonDebugModeKey[]; extern const char kJsonGaiaIdKey[]; +extern const char kJsonDeviceTypeKey[]; class SystemInfo;
diff --git a/ash/webui/eche_app_ui/system_info_provider_unittest.cc b/ash/webui/eche_app_ui/system_info_provider_unittest.cc index b68cff5d1..d4120f1 100644 --- a/ash/webui/eche_app_ui/system_info_provider_unittest.cc +++ b/ash/webui/eche_app_ui/system_info_provider_unittest.cc
@@ -27,6 +27,7 @@ ConnectionStateType::kConnected; const bool kFakeDebugMode = false; const char kFakeGaiaId[] = "123"; +const char kFakeDeviceType[] = "Chromebook"; void ParseJson(const std::string& json, std::string& device_name, @@ -34,7 +35,8 @@ bool& tablet_mode, std::string& wifi_connection_state, bool& debug_mode, - std::string& gaia_id) { + std::string& gaia_id, + std::string& device_type) { absl::optional<base::Value> message_value = base::JSONReader::Read(json); base::Value::Dict* message_dictionary = message_value->GetIfDict(); const std::string* device_name_ptr = @@ -61,6 +63,10 @@ message_dictionary->FindString(kJsonGaiaIdKey); if (gaia_id_ptr) gaia_id = *gaia_id_ptr; + const std::string* device_type_ptr = + message_dictionary->FindString(kJsonDeviceTypeKey); + if (device_type_ptr) + device_type = *device_type_ptr; } class TaskRunner { @@ -191,6 +197,7 @@ .SetDeviceName(kFakeDeviceName) .SetBoardName(kFakeBoardName) .SetGaiaId(kFakeGaiaId) + .SetDeviceType(kFakeDeviceType) .Build(), remote_cros_network_config_.get()); fake_observer_ = std::make_unique<FakeObserver>(); @@ -255,11 +262,12 @@ std::string wifi_connection_state = ""; bool debug_mode = true; std::string gaia_id = ""; + std::string device_type = ""; GetSystemInfo(); std::string json = Callback::GetSystemInfo(); ParseJson(json, device_name, board_name, tablet_mode, wifi_connection_state, - debug_mode, gaia_id); + debug_mode, gaia_id, device_type); EXPECT_EQ(device_name, kFakeDeviceName); EXPECT_EQ(board_name, kFakeBoardName); @@ -267,6 +275,7 @@ EXPECT_EQ(wifi_connection_state, "connected"); EXPECT_EQ(debug_mode, kFakeDebugMode); EXPECT_EQ(gaia_id, kFakeGaiaId); + EXPECT_EQ(device_type, kFakeDeviceType); } TEST_F(SystemInfoProviderTest, ObserverCalledWhenBacklightChanged) {
diff --git a/ash/webui/os_feedback_ui/resources/file_attachment.html b/ash/webui/os_feedback_ui/resources/file_attachment.html index d6bffdf..9c950ad 100644 --- a/ash/webui/os_feedback_ui/resources/file_attachment.html +++ b/ash/webui/os_feedback_ui/resources/file_attachment.html
@@ -13,7 +13,13 @@ } .file-input { + background: none; + border: none; + color: var(--cros-color-prominent); cursor: pointer; + font-size: 13px; + line-height: 20px; + padding: 0; } .error-outline { @@ -37,8 +43,11 @@ } #replaceFileInfo { + font-family: var(--feedback-roboto-font-family); + font-size: 13px; + line-height: 20px; overflow: hidden; - padding-inline-end: 12px; + padding: 4px 12px 4px 0; } #selectFileDialog { @@ -59,13 +68,7 @@ } #addFileLabel { - background: none; - border: none; - color: var(--cros-color-prominent); - font-size: 13px; font-weight: var(--feedback-medium-font-weight); - line-height: 20px; - padding: 0; } #addFileIcon { @@ -78,6 +81,31 @@ top: auto; } + #selectFileCheckbox { + margin-inline-end: 10px; + margin-inline-start: 12px; + } + + #selectedImageButton { + background: none; + border: none; + height: 48px; + padding: 0; + width: 68px; + } + + #selectedFileImage { + border-radius: 0 4px 4px 0; + display: block; + height: 48px; + transition: all 250ms ease; + width: 68px; + } + + #selectedFileName, + #replaceFileLabel { + font-weight: var(--feedback-regular-font-weight); + } </style> <div id="addFileContainer" hidden="[[hasSelectedAFile_]]"> <button id="addFileLabel" class="file-input" @@ -89,7 +117,7 @@ <input id="selectFileDialog" type="file" on-change="handleFileSelectChange_" tabindex="-1"> <div id="replaceFileContainer" hidden="[[!hasSelectedAFile_]]"> - <input type="checkbox" id="selectFileCheckbox"> + <cr-checkbox id="selectFileCheckbox"></cr-checkbox> <div id="replaceFileInfo"> <div id="selectedFileName" class="overflow-text">[[selectedFileName_]]</div> <button id="replaceFileButton" class="file-input"
diff --git a/ash/webui/os_feedback_ui/resources/file_attachment.js b/ash/webui/os_feedback_ui/resources/file_attachment.js index 8ae6fbe..514d833 100644 --- a/ash/webui/os_feedback_ui/resources/file_attachment.js +++ b/ash/webui/os_feedback_ui/resources/file_attachment.js
@@ -6,6 +6,7 @@ import './os_feedback_shared_css.js'; import 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import 'chrome://resources/cr_elements/icons.m.js'; +import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
diff --git a/ash/webui/os_feedback_ui/resources/os_feedback_shared_css.html b/ash/webui/os_feedback_ui/resources/os_feedback_shared_css.html index 2023ed00..ee1c83c 100644 --- a/ash/webui/os_feedback_ui/resources/os_feedback_shared_css.html +++ b/ash/webui/os_feedback_ui/resources/os_feedback_shared_css.html
@@ -80,5 +80,11 @@ cr-button { line-height: 20px; } + + cr-checkbox { + --cr-checkbox-label-padding-start: 0; + --cr-checkbox-size: 20px; + margin-inline-end: 12px; + } </style> </template>
diff --git a/ash/webui/os_feedback_ui/resources/share_data_page.html b/ash/webui/os_feedback_ui/resources/share_data_page.html index b486bdc..9aad6bb1 100644 --- a/ash/webui/os_feedback_ui/resources/share_data_page.html +++ b/ash/webui/os_feedback_ui/resources/share_data_page.html
@@ -36,6 +36,7 @@ #screenshotContainer { align-items: center; + box-sizing: border-box; height: 48px; margin-inline-end: 12px; width: 50%; @@ -68,6 +69,7 @@ #addFileContainer { align-items: center; + box-sizing: border-box; height: 48px; margin-inline-start: 12px; width: 50%; @@ -131,12 +133,6 @@ margin-bottom: 24px; } - cr-checkbox { - --cr-checkbox-label-padding-start: 0; - --cr-checkbox-size: 20px; - margin-inline-end: 12px; - } - h2 { margin: 0 0 8px 0; }
diff --git a/ash/webui/personalization_app/resources/BUILD.gn b/ash/webui/personalization_app/resources/BUILD.gn index 64298fa2..6272a93 100644 --- a/ash/webui/personalization_app/resources/BUILD.gn +++ b/ash/webui/personalization_app/resources/BUILD.gn
@@ -66,8 +66,6 @@ "trusted/wallpaper/wallpaper_reducers.ts", "trusted/wallpaper/wallpaper_state.ts", "trusted/wallpaper/index.ts", - - "untrusted/setup.ts", ] # Files holding a Polymer element definition AND have an equivalent .html file.
diff --git a/ash/webui/personalization_app/resources/untrusted/collections_grid.ts b/ash/webui/personalization_app/resources/untrusted/collections_grid.ts index bfce18d..1383c13 100644 --- a/ash/webui/personalization_app/resources/untrusted/collections_grid.ts +++ b/ash/webui/personalization_app/resources/untrusted/collections_grid.ts
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import '//resources/polymer/v3_0/iron-list/iron-list.js'; -import './setup.js'; +import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; +import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; +import '../common/icons.html.js'; +import '../css/common.css.js'; import '../css/wallpaper.css.js'; -import {loadTimeData} from '//resources/js/load_time_data.m.js'; import {assert} from 'chrome://resources/js/assert_ts.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js'; import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
diff --git a/ash/webui/personalization_app/resources/untrusted/setup.ts b/ash/webui/personalization_app/resources/untrusted/setup.ts deleted file mode 100644 index a6e16c4e..0000000 --- a/ash/webui/personalization_app/resources/untrusted/setup.ts +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview imports javascript files that have side effects. Makes sure - * they are imported in the correct order. - */ - -// Import necessary built in modules before ../common files. This will -// guarantee that polymer and certain polymer elements are loaded first. -import '//resources/polymer/v3_0/iron-icon/iron-icon.js'; -import '//resources/cr_elements/shared_vars_css.m.js'; -import '../common/icons.html.js'; -import '../css/common.css.js'; -import '/strings.m.js';
diff --git a/ash/webui/projector_app/projector_screencast.cc b/ash/webui/projector_app/projector_screencast.cc index 072aec1..4c2c45b 100644 --- a/ash/webui/projector_app/projector_screencast.cc +++ b/ash/webui/projector_app/projector_screencast.cc
@@ -11,6 +11,7 @@ base::Value ProjectorScreencastVideo::ToValue() const { base::Value::Dict dict; dict.Set("srcUrl", src_url); + dict.Set("fileId", file_id); return base::Value(std::move(dict)); } @@ -27,6 +28,7 @@ base::Value::Dict dict; dict.Set("containerFolderId", container_folder_id); dict.Set("name", name); + dict.Set("metadataFileId", metadata_file_id); dict.Set("video", video.ToValue()); return base::Value(std::move(dict));
diff --git a/ash/webui/projector_app/projector_screencast.h b/ash/webui/projector_app/projector_screencast.h index dff6959..adc7900 100644 --- a/ash/webui/projector_app/projector_screencast.h +++ b/ash/webui/projector_app/projector_screencast.h
@@ -18,6 +18,7 @@ base::Value ToValue() const; // TODO(b/236857019): Add thumbnail link and video file id. std::string src_url; + std::string file_id; }; // Struct of screencast model. @@ -34,6 +35,9 @@ std::string name; + // The Drive server side item id of ".projector" file. + std::string metadata_file_id; + ProjectorScreencastVideo video; // TODO(b/236857019): 1 Implement following fields: status, metadata_file_id,
diff --git a/ash/webui/projector_app/public/cpp/BUILD.gn b/ash/webui/projector_app/public/cpp/BUILD.gn index 3b402e4..2657290 100644 --- a/ash/webui/projector_app/public/cpp/BUILD.gn +++ b/ash/webui/projector_app/public/cpp/BUILD.gn
@@ -10,4 +10,5 @@ "projector_app_constants.cc", "projector_app_constants.h", ] + deps = [ "//base:base" ] }
diff --git a/ash/webui/projector_app/public/cpp/projector_app_constants.cc b/ash/webui/projector_app/public/cpp/projector_app_constants.cc index 648b463..e3eeb9a8 100644 --- a/ash/webui/projector_app/public/cpp/projector_app_constants.cc +++ b/ash/webui/projector_app/public/cpp/projector_app_constants.cc
@@ -29,4 +29,10 @@ const char kChromeUITrustedProjectorSwaAppId[] = "fgnpbdobngpkonkajbmelfhjkemaddhp"; +const base::FilePath::CharType kProjectorMetadataFileExtension[] = + FILE_PATH_LITERAL(".projector"); + +const base::FilePath::CharType kProjectorMediaFileExtension[] = + FILE_PATH_LITERAL(".webm"); + } // namespace ash
diff --git a/ash/webui/projector_app/public/cpp/projector_app_constants.h b/ash/webui/projector_app/public/cpp/projector_app_constants.h index 94d540a..d721c64 100644 --- a/ash/webui/projector_app/public/cpp/projector_app_constants.h +++ b/ash/webui/projector_app/public/cpp/projector_app_constants.h
@@ -5,6 +5,8 @@ #ifndef ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_ #define ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_ +#include "base/files/file_path.h" + namespace ash { extern const char kChromeUIProjectorAppHost[]; @@ -23,6 +25,13 @@ extern const char kChromeUITrustedProjectorSwaAppId[]; +// File extension of Projector metadata file. It is used to identify Projector +// screencasts at processing pending screencasts and fetching screencast list. +extern const base::FilePath::CharType kProjectorMetadataFileExtension[]; + +// File extension of Projector media file. +extern const base::FilePath::CharType kProjectorMediaFileExtension[]; + } // namespace ash #endif // ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_
diff --git a/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.html b/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.html index 8ad21ec551..4fffb547 100644 --- a/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.html +++ b/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.html
@@ -5,7 +5,7 @@ </style> <base-page equal-panes> <div slot="left-pane"> - <h1>[[i18n('firmwareUpdatePageTitleText')]]</h1> + <h1 id="titleText">[[getTitleText_(status_)]]</h1> <div class="icon-message"> <iron-icon icon="shimless-icon:warning" class="warning-icon small-icon" hidden="[[!shouldShowWarning_]]">
diff --git a/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.js b/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.js index 5562fe8..394d1e5c 100644 --- a/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.js +++ b/ash/webui/shimless_rma/resources/reimaging_firmware_update_page.js
@@ -183,6 +183,17 @@ this.imgAlt_ = this.i18n( !this.status_ ? 'downloadingAltText' : STATUS_ALT_MAP[this.status_]); } + + /** + * @return {string} + * @protected + */ + getTitleText_() { + return this.i18n( + this.status_ === UpdateRoFirmwareStatus.kComplete ? + 'firmwareUpdateInstallCompleteTitleText' : + 'firmwareUpdateInstallImageTitleText'); + } } customElements.define(UpdateRoFirmwarePage.is, UpdateRoFirmwarePage);
diff --git a/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.html b/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.html index bc37107f..48d28311 100644 --- a/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.html +++ b/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.html
@@ -153,6 +153,7 @@ #logSavedIconText { align-items: center; + display: flex; } </style> @@ -185,7 +186,8 @@ <div id="buttonContainer"> <cr-button id="diagnosticsButton" class="button-card" on-click="onDiagnosticsButtonClick_" disabled="[[allButtonsDisabled]]"> - <iron-icon icon$="[[getDiagnosticsIcon_(allButtonsDisabled)]]" class="button-icon"> + <iron-icon icon$="[[getDiagnosticsIcon_(allButtonsDisabled)]]" + class="button-icon"> </iron-icon> <div class="button-text"> <div class="button-label"> @@ -198,7 +200,9 @@ </cr-button> <cr-button id="rmaLogButton" class="button-card" on-click="onRmaLogButtonClick_" disabled="[[allButtonsDisabled]]"> - <iron-icon icon$="[[getRmaLogIcon_(allButtonsDisabled)]]" class="button-icon"></iron-icon> + <iron-icon icon$="[[getRmaLogIcon_(allButtonsDisabled)]]" + class="button-icon"> + </iron-icon> <div class="button-text"> <div class="button-label"> <span>[[i18n('repairCompletedLogsButtonText')]]</span> @@ -214,7 +218,8 @@ disabled$="[[disableBatteryCutButton_(pluggedIn_, allButtonsDisabled)]]"> <iron-icon id="batteryCutoffIcon" - icon$="[[getBatteryCutoffIcon_(allButtonsDisabled)]]" class="button-icon"> + icon$="[[getBatteryCutoffIcon_(allButtonsDisabled)]]" + class="button-icon"> </iron-icon> <div class="button-text"> <div class="button-label"> @@ -251,10 +256,10 @@ slot="button-container" hidden="[[!shouldShowLogSaveAttemptContainer_(usbLogState_)]]"> <div id="logSavedIconText"> - <iron-icon id="verificationIcon" icon="shimless-icon:check" - class="small-icon"> + <iron-icon id="verificationIcon" class="small-icon" + icon="[[getSaveLogResultIcon_(usbLogState_)]]"> </iron-icon> - [[logSavedStatusText_]] + <span id="logSavedStatusText">[[logSavedStatusText_]]</span> </div> <cr-button id="logSaveDoneDialogButton" class="text-button action-button" on-click="closeLogsDialog_"> @@ -286,10 +291,12 @@ [[i18n('repairCompletedBatteryCutoffCountdownDescription')]] </div> <div class="dialog-footer" slot="button-container"> - <cr-button id="closeBatteryCutoffDialogButton" on-click="onCutoffCancelClick_"> + <cr-button id="closeBatteryCutoffDialogButton" + on-click="onCutoffCancelClick_"> [[i18n('cancelButtonLabel')]] </cr-button> - <cr-button id="batteryCutoffShutdownButton" class="text-button action-button" + <cr-button id="batteryCutoffShutdownButton" + class="text-button action-button" on-click="onCutoffShutdownButtonClick_"> [[i18n('repairCompletedBatteryCutoffShutdownButton')]] </cr-button>
diff --git a/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.js b/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.js index 371d712..608deb7 100644 --- a/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.js +++ b/ash/webui/shimless_rma/resources/wrapup_repair_complete_page.js
@@ -304,6 +304,9 @@ this.logSavedStatusText_ = this.i18n('rmaLogsSaveSuccessText', result.savePath.path); this.usbLogState_ = USBLogState.LOG_SAVE_SUCCESS; + } else { + this.logSavedStatusText_ = this.i18n('rmaLogsSaveFailText'); + this.usbLogState_ = USBLogState.LOG_SAVE_FAIL; } }); } @@ -426,6 +429,21 @@ return this.usbLogState_ === USBLogState.LOG_SAVE_SUCCESS || this.usbLogState_ === USBLogState.LOG_SAVE_FAIL; } + + /** + * @return {string} + * @protected + */ + getSaveLogResultIcon_() { + switch (this.usbLogState_) { + case USBLogState.LOG_SAVE_SUCCESS: + return 'shimless-icon:check'; + case USBLogState.LOG_SAVE_FAIL: + return 'shimless-icon:warning'; + default: + return ''; + } + } } customElements.define(WrapupRepairCompletePage.is, WrapupRepairCompletePage);
diff --git a/ash/webui/shimless_rma/shimless_rma.cc b/ash/webui/shimless_rma/shimless_rma.cc index da1dc12c..2e605023 100644 --- a/ash/webui/shimless_rma/shimless_rma.cc +++ b/ash/webui/shimless_rma/shimless_rma.cc
@@ -242,6 +242,7 @@ {"repairCompletedBatteryCutoffShutdownButton", IDS_SHIMLESS_RMA_REPAIR_COMPLETED_BATTERY_CUTOFF_SHUTDOWN_BUTTON}, {"rmaLogsSaveSuccessText", IDS_SHIMLESS_RMA_LOGS_SAVE_SUCCESS}, + {"rmaLogsSaveFailText", IDS_SHIMLESS_RMA_LOGS_SAVE_FAIL}, // Powerwash dialog {"powerwashDialogTitle", IDS_SHIMLESS_RMA_POWERWASH_DIALOG_TITLE}, {"powerwashDialogShutdownDescription", @@ -290,7 +291,10 @@ {"confirmDeviceInfoSkuWarning", IDS_SHIMLESS_RMA_CONFIRM_DEVICE_INFO_SKU_WARNING}, // Firmware reimaging page - {"firmwareUpdatePageTitleText", IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_TITLE}, + {"firmwareUpdateInstallImageTitleText", + IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_IMAGE_TITLE}, + {"firmwareUpdateInstallCompleteTitleText", + IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_COMPLETE_TITLE}, {"firmwareUpdateWaitForUsbText", IDS_SHIMLESS_RMA_FIRMWARE_WAIT_FOR_USB}, {"firmwareUpdateFileNotFoundText", IDS_SHIMLESS_RMA_FIRMWARE_FILE_NOT_FOUND},
diff --git a/ash/wm/client_controlled_state.cc b/ash/wm/client_controlled_state.cc index 5da23b14..346db9b 100644 --- a/ash/wm/client_controlled_state.cc +++ b/ash/wm/client_controlled_state.cc
@@ -78,7 +78,8 @@ bool was_pinned = window_state->IsPinned(); bool was_trusted_pinned = window_state->IsTrustedPinned(); - set_next_bounds_change_animation_type(kAnimationCrossFade); + set_next_bounds_change_animation_type( + WindowState::BoundsChangeAnimationType::kCrossFade); EnterNextState(window_state, next_state_type); VLOG(1) << "Processing Pinned Transition: event=" << event_type @@ -215,19 +216,22 @@ const gfx::Rect& bounds = set_bounds_event->requested_bounds(); if (set_bounds_locally_) { switch (next_bounds_change_animation_type_) { - case kAnimationNone: + case WindowState::BoundsChangeAnimationType::kNone: window_state->SetBoundsDirect(bounds); break; - case kAnimationCrossFade: + case WindowState::BoundsChangeAnimationType::kCrossFade: window_state->SetBoundsDirectCrossFade(bounds); break; - case kAnimationAnimated: + case WindowState::BoundsChangeAnimationType::kAnimate: window_state->SetBoundsDirectAnimated( bounds, bounds_change_animation_duration_); break; + case WindowState::BoundsChangeAnimationType::kAnimateZero: + NOTREACHED(); + break; } - next_bounds_change_animation_type_ = kAnimationNone; - + next_bounds_change_animation_type_ = + WindowState::BoundsChangeAnimationType::kNone; } else if (!window_state->IsPinned()) { // TODO(oshima): Define behavior for pinned app. bounds_change_animation_duration_ = set_bounds_event->duration();
diff --git a/ash/wm/client_controlled_state.h b/ash/wm/client_controlled_state.h index e5a4960e..ea65eb9 100644 --- a/ash/wm/client_controlled_state.h +++ b/ash/wm/client_controlled_state.h
@@ -64,18 +64,10 @@ void set_bounds_locally(bool set) { set_bounds_locally_ = set; } bool set_bounds_locally() const { return set_bounds_locally_; } - // Type of animation type to be applied when changing bounds locally. - // TODO(oshima): Use transform animation for snapping. - enum BoundsChangeAnimationType { - kAnimationNone, - kAnimationCrossFade, - kAnimationAnimated, - }; - // Sets the type of animation for the next bounds change // applied locally. void set_next_bounds_change_animation_type( - BoundsChangeAnimationType animation_type) { + WindowState::BoundsChangeAnimationType animation_type) { next_bounds_change_animation_type_ = animation_type; } @@ -121,7 +113,8 @@ base::TimeDelta bounds_change_animation_duration_ = WindowState::kBoundsChangeSlideDuration; - BoundsChangeAnimationType next_bounds_change_animation_type_ = kAnimationNone; + WindowState::BoundsChangeAnimationType next_bounds_change_animation_type_ = + WindowState::BoundsChangeAnimationType::kNone; }; } // namespace ash
diff --git a/ash/wm/default_state.cc b/ash/wm/default_state.cc index 09109a64..ded9a60 100644 --- a/ash/wm/default_state.cc +++ b/ash/wm/default_state.cc
@@ -665,7 +665,7 @@ if (IsMinimizedWindowStateType(previous_state_type) || window_state->IsFullscreen() || window_state->IsPinned() || window_state->bounds_animation_type() == - WindowState::BoundsChangeAnimationType::IMMEDIATE) { + WindowState::BoundsChangeAnimationType::kNone) { window_state->SetBoundsDirect(bounds_in_parent); } else if (window_state->IsMaximized() || IsMaximizedOrFullscreenOrPinnedWindowStateType( @@ -714,7 +714,7 @@ return; if (window_state->bounds_animation_type() == - WindowState::BoundsChangeAnimationType::IMMEDIATE) { + WindowState::BoundsChangeAnimationType::kNone) { window_state->SetBoundsDirect(bounds); } else { window_state->SetBoundsDirectAnimated(bounds);
diff --git a/ash/wm/desks/persistent_desks_bar_button.cc b/ash/wm/desks/persistent_desks_bar_button.cc index 1a32ade4..1eb19fbf 100644 --- a/ash/wm/desks/persistent_desks_bar_button.cc +++ b/ash/wm/desks/persistent_desks_bar_button.cc
@@ -7,7 +7,7 @@ #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/style/ash_color_provider.h" -#include "ash/system/tray/tray_popup_utils.h" +#include "ash/style/style_util.h" #include "ash/wm/desks/desk.h" #include "ash/wm/desks/desks_controller.h" #include "ash/wm/desks/persistent_desks_bar_context_menu.h" @@ -81,7 +81,7 @@ // Keeping the same inkdrop and highlight as the buttons inside the system // tray menu for now since specs are not ready. // TODO(minch): Update once the specs are ready and need to be updated. - TrayPopupUtils::ConfigureTrayPopupButton(this); + StyleUtil::SetUpInkDropForButton(this); views::InstallCircleHighlightPathGenerator(this); }
diff --git a/ash/wm/desks/templates/saved_desk_item_view.cc b/ash/wm/desks/templates/saved_desk_item_view.cc index a23f9fc..5ecd4db6 100644 --- a/ash/wm/desks/templates/saved_desk_item_view.cc +++ b/ash/wm/desks/templates/saved_desk_item_view.cc
@@ -127,6 +127,8 @@ const bool is_admin_managed = desk_template_->source() == DeskTemplateSource::kPolicy; + SetFocusBehavior(views::View::FocusBehavior::ALWAYS); + views::Builder<SavedDeskItemView>(this) .SetPreferredSize(kPreferredSize) .SetUseDefaultFillLayout(true) @@ -299,6 +301,19 @@ } } +void SavedDeskItemView::MaybeShowReplaceDialog(DeskTemplateType type, + const base::GUID& uuid) { + // Show replace template dialog. If accepted, replace old template and commit + // name change. + aura::Window* root_window = GetWidget()->GetNativeWindow()->GetRootWindow(); + saved_desk_util::GetSavedDeskDialogController()->ShowReplaceDialog( + root_window, name_view_->GetText(), type, + base::BindOnce(&SavedDeskItemView::ReplaceTemplate, + weak_ptr_factory_.GetWeakPtr(), uuid.AsLowercaseString()), + base::BindOnce(&SavedDeskItemView::RevertTemplateName, + weak_ptr_factory_.GetWeakPtr())); +} + void SavedDeskItemView::ReplaceTemplate(const std::string& uuid) { // Make sure we delete the template we are replacing first, so that we don't // get template name collisions. Passing `nullopt` as `record_for_type` since @@ -497,17 +512,25 @@ UpdateTemplateName(); } -void SavedDeskItemView::MaybeShowReplaceDialog(DeskTemplateType type, - const base::GUID& uuid) { - // Show replace template dialog. If accepted, replace old template and commit - // name change. - aura::Window* root_window = GetWidget()->GetNativeWindow()->GetRootWindow(); - saved_desk_util::GetSavedDeskDialogController()->ShowReplaceDialog( - root_window, name_view_->GetText(), type, - base::BindOnce(&SavedDeskItemView::ReplaceTemplate, - weak_ptr_factory_.GetWeakPtr(), uuid.AsLowercaseString()), - base::BindOnce(&SavedDeskItemView::RevertTemplateName, - weak_ptr_factory_.GetWeakPtr())); +void SavedDeskItemView::OnFocus() { + auto* highlight_controller = Shell::Get() + ->overview_controller() + ->overview_session() + ->highlight_controller(); + DCHECK(highlight_controller); + AccessibilityControllerImpl* accessibility_controller = + Shell::Get()->accessibility_controller(); + if (highlight_controller->IsFocusHighlightVisible() || + accessibility_controller->spoken_feedback().enabled()) { + highlight_controller->MoveHighlightToView(this); + } + OnViewHighlighted(); + View::OnFocus(); +} + +void SavedDeskItemView::OnBlur() { + OnViewUnhighlighted(); + View::OnBlur(); } views::Button::KeyClickAction SavedDeskItemView::GetKeyClickActionForEvent(
diff --git a/ash/wm/desks/templates/saved_desk_item_view.h b/ash/wm/desks/templates/saved_desk_item_view.h index 362e4d96..0a246cb 100644 --- a/ash/wm/desks/templates/saved_desk_item_view.h +++ b/ash/wm/desks/templates/saved_desk_item_view.h
@@ -114,6 +114,8 @@ void OnThemeChanged() override; void OnViewFocused(views::View* observed_view) override; void OnViewBlurred(views::View* observed_view) override; + void OnFocus() override; + void OnBlur() override; KeyClickAction GetKeyClickActionForEvent(const ui::KeyEvent& event) override; // views::TextfieldController:
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index 8c1c3e67..e2fd6e2a 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -6324,8 +6324,7 @@ // Test the split view and overview functionalities in clamshell mode. Split // view is only active when overview is active in clamshell mode. class SplitViewOverviewSessionInClamshellTest - : public SplitViewOverviewSessionTest, - public ::testing::WithParamInterface<bool> { + : public SplitViewOverviewSessionTest { public: SplitViewOverviewSessionInClamshellTest() = default; @@ -6338,20 +6337,11 @@ // AshTestBase: void SetUp() override { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); - } else { - scoped_feature_list_.InitAndDisableFeature( - chromeos::wm::features::kVerticalSnap); - } SplitViewOverviewSessionTest::SetUp(); Shell::Get()->tablet_mode_controller()->SetEnabledForTest(false); DCHECK(ShouldAllowSplitView()); } - bool IsVerticalSnapEnabled() const { return GetParam(); } - aura::Window* CreateWindowWithHitTestComponent(int hit_test_component, const gfx::Rect& bounds) { return CreateTestWindowInShellWithDelegate( @@ -6375,12 +6365,10 @@ // aura::Test::TestWindowDelegate: void OnWindowDestroyed(aura::Window* window) override { delete this; } }; - - base::test::ScopedFeatureList scoped_feature_list_; }; // Test some basic functionalities in clamshell splitview mode. -TEST_P(SplitViewOverviewSessionInClamshellTest, BasicFunctionalitiesTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, BasicFunctionalitiesTest) { UpdateDisplay("600x400"); EXPECT_FALSE(Shell::Get()->tablet_mode_controller()->InTabletMode()); @@ -6528,7 +6516,7 @@ // Test overview exit animation histograms when you drag to snap two windows on // opposite sides. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, BothSnappedOverviewExitAnimationHistogramTest) { ui::ScopedAnimationDurationScaleMode anmatin_scale( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); @@ -6553,7 +6541,7 @@ // Test that when overview and splitview are both active, only resize that // happens on eligible window components will change snapped window bounds and // overview bounds at the same time. -TEST_P(SplitViewOverviewSessionInClamshellTest, ResizeWindowTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, ResizeWindowTest) { UpdateDisplay("600x400"); const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> window1( @@ -6691,7 +6679,7 @@ } // Test closing the split view window while resizing it. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, CloseWindowWhileResizingItTest) { UpdateDisplay("600x400"); const gfx::Rect bounds(400, 400); @@ -6746,7 +6734,7 @@ // Tests that when a split view window carries over to clamshell split view // while the divider is being dragged, the window resize is properly completed. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, CarryOverToClamshellSplitViewWhileResizing) { std::unique_ptr<aura::Window> snapped_window = CreateTestWindow(); std::unique_ptr<aura::Window> overview_window = CreateTestWindow(); @@ -6788,7 +6776,7 @@ // Test that overview and clamshell split view end if you double click the edge // of the split view window where it meets the overview grid. -TEST_P(SplitViewOverviewSessionInClamshellTest, HorizontalMaximizeTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, HorizontalMaximizeTest) { const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> snapped_window( CreateWindowWithHitTestComponent(HTRIGHT, bounds)); @@ -6806,7 +6794,7 @@ // Test that when laptop splitview mode is active, moving the snapped window // will end splitview and overview at the same time. -TEST_P(SplitViewOverviewSessionInClamshellTest, MoveWindowTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, MoveWindowTest) { const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> window1( CreateWindowWithHitTestComponent(HTCAPTION, bounds)); @@ -6828,7 +6816,7 @@ // Test that in clamshell splitview mode, if the snapped window is minimized, // splitview mode and overview mode are both ended. -TEST_P(SplitViewOverviewSessionInClamshellTest, MinimizedWindowTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, MinimizedWindowTest) { const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); @@ -6847,7 +6835,7 @@ } // Test snapped window bounds with adjustment for the minimum size of a window. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, SnappedWindowBoundsWithMinimumSizeTest) { const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> window1( @@ -6915,7 +6903,7 @@ // Tests that on a display in portrait orientation, clamshell split view still // uses snap positions on the left and right. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, PortraitClamshellSplitViewSnapPositionsTest) { UpdateDisplay("800x600/l"); const int height = 800 - ShelfConfig::Get()->shelf_size(); @@ -6928,11 +6916,11 @@ const gfx::Rect left_snapped_bounds(300, height); const gfx::Rect right_snapped_bounds(300, 0, 300, height); EXPECT_EQ( - IsVerticalSnapEnabled() ? top_snapped_bounds : left_snapped_bounds, + top_snapped_bounds, split_view_controller()->GetSnappedWindowBoundsInScreen( SplitViewController::LEFT, /*window_for_minimum_size=*/nullptr)); EXPECT_EQ( - IsVerticalSnapEnabled() ? bottom_snapped_bounds : right_snapped_bounds, + bottom_snapped_bounds, split_view_controller()->GetSnappedWindowBoundsInScreen( SplitViewController::RIGHT, /*window_for_minimum_size=*/nullptr)); @@ -6948,18 +6936,18 @@ EXPECT_FALSE(tablet_mode_controller_test_api.IsTabletModeStarted()); // Check the snapped window bounds again. They should be the same as before. EXPECT_EQ( - IsVerticalSnapEnabled() ? top_snapped_bounds : left_snapped_bounds, + top_snapped_bounds, split_view_controller()->GetSnappedWindowBoundsInScreen( SplitViewController::LEFT, /*window_for_minimum_size=*/nullptr)); EXPECT_EQ( - IsVerticalSnapEnabled() ? bottom_snapped_bounds : right_snapped_bounds, + bottom_snapped_bounds, split_view_controller()->GetSnappedWindowBoundsInScreen( SplitViewController::RIGHT, /*window_for_minimum_size=*/nullptr)); } // Tests that the ratio between the divider position and the work area width is // the same before and after changing the display orientation in clamshell mode. -TEST_P(SplitViewOverviewSessionInClamshellTest, DisplayOrientationChangeTest) { +TEST_F(SplitViewOverviewSessionInClamshellTest, DisplayOrientationChangeTest) { UpdateDisplay("600x400"); const gfx::Rect bounds(400, 400); std::unique_ptr<aura::Window> split_view_window( @@ -7009,7 +6997,7 @@ } // Verify that an item's unsnappable indicator is updated for display rotation. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, OverviewUnsnappableIndicatorVisibilityAfterDisplayRotation) { UpdateDisplay("900x600"); std::unique_ptr<aura::Window> snapped_window = CreateTestWindow(); @@ -7046,7 +7034,7 @@ // Tests that dragging a window from overview creates a drop target on the same // display, even if the window bounds are mostly on another display. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, DragFromOverviewWithBoundsMostlyOnAnotherDisplay) { UpdateDisplay("700x600,700x600"); const aura::Window::Windows root_windows = Shell::Get()->GetAllRootWindows(); @@ -7086,7 +7074,7 @@ } // Tests that Alt+[ and Alt+] do not start overview. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, AltSquareBracketNotStartOverview) { std::unique_ptr<aura::Window> window1 = CreateTestWindow(); std::unique_ptr<aura::Window> window2 = CreateTestWindow(); @@ -7110,7 +7098,7 @@ } // Tests using Alt+[ on a left split view window. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, AltLeftSquareBracketOnLeftSplitViewWindow) { std::unique_ptr<aura::Window> snapped_window = CreateTestWindow(); std::unique_ptr<aura::Window> overview_window = CreateTestWindow(); @@ -7130,7 +7118,7 @@ } // Tests using Alt+] on a right split view window. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, AltRightSquareBracketOnRightSplitViewWindow) { std::unique_ptr<aura::Window> snapped_window = CreateTestWindow(); std::unique_ptr<aura::Window> overview_window = CreateTestWindow(); @@ -7152,7 +7140,7 @@ // Tests using Alt+[ on a right split view window, and Alt+] on a left split // view window. -TEST_P(SplitViewOverviewSessionInClamshellTest, +TEST_F(SplitViewOverviewSessionInClamshellTest, AltSquareBracketOnSplitViewWindow) { std::unique_ptr<aura::Window> snapped_window = CreateTestWindow(); std::unique_ptr<aura::Window> overview_window = CreateTestWindow(); @@ -7195,7 +7183,7 @@ SplitViewOverviewSessionInClamshellTest; // Test |SplitViewController::Get|. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, GetSplitViewController) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7211,7 +7199,7 @@ } // Test |SplitViewController::GetSnappedWindowBoundsInScreen|. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, GetSnappedBounds) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7249,7 +7237,7 @@ // Test that if clamshell split view is started by snapping a window that is the // only overview window, then split view ends as soon as it starts, and overview // ends along with it. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, SplitViewEndsImmediatelyIfOverviewIsEmpty) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7268,7 +7256,7 @@ // stays active (instead of ending as soon as it starts), and overview also // stays active. Then close the overview window and verify that split view and // overview are ended. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, SplitViewViableWithOverviewWindowOnOtherDisplay) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7288,7 +7276,7 @@ } // Test dragging to snap an overview item on an external display. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DraggingOnExternalDisplay) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7350,7 +7338,7 @@ } // Test dragging from one display to another. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, MultiDisplayDragging) { wm::CursorManager* cursor_manager = Shell::Get()->cursor_manager(); UpdateDisplay("800x600,800x600"); @@ -7481,7 +7469,7 @@ } // Verify the drop target positions for multi-display dragging. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DropTargetPositionTest) { wm::CursorManager* cursor_manager = Shell::Get()->cursor_manager(); UpdateDisplay("800x600,800x600"); @@ -7528,7 +7516,7 @@ // Verify that the drop target in each overview grid has the correct bounds when // a maximized window is being dragged. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DropTargetBoundsForMaximizedWindowDraggedToOtherDisplay) { UpdateDisplay("1000x400,1000x400/l"); std::unique_ptr<aura::Window> window = CreateTestWindow(); @@ -7564,7 +7552,7 @@ // Verify that the drop target in each overview grid has bounds representing // anticipation that if the dragged window is dropped into that grid, it will // shrink to fit into the corresponding work area. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DropTargetBoundsOnDisplayWhereDraggedWindowDoesNotFitIntoWorkArea) { UpdateDisplay("600x500,1200x1000"); // Drags |item| from the right display to the left display and back, and @@ -7623,7 +7611,7 @@ } // Test dragging from one overview grid and dropping into another overview grid. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DragAndDropIntoAnotherOverviewGrid) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7658,7 +7646,7 @@ // Test that overview widgets are stacked in the correct order after an overview // window is dragged from one overview grid and dropped into another. Also test // that the destination overview grid is arranged in the correct order. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, OverviewWidgetStackingOrderAndGridOrderWithMultiDisplayDragging) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7725,7 +7713,7 @@ } // Test dragging from one display to another and then snapping. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DragFromOneDisplayToAnotherAndSnap) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7757,7 +7745,7 @@ // Verify that window resizing performance is recorded to the correct histogram // depending on whether the overview grid is empty. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, WindowResizingPerformanceHistogramsTest) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -7801,7 +7789,7 @@ // recorded to the histogram, but this test does provide evidence of timing // accuracy as the time in multi-display split view is measured from the time // when the user action "SplitView_MultiDisplaySplitView" is recorded. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, MultiDisplaySplitViewMetrics) { base::UserActionTester user_action_tester; base::HistogramTester histogram_tester; @@ -7882,7 +7870,7 @@ // of the window fits into the left or top, with the default divider position. // (If the work area length is odd, then the right or bottom will be one pixel // larger.) -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, SnapWindowWithMinimumSizeTest) { // The divider is 8 thick. For the default divider position, the remaining 792 // of the work area on the first root window is divided into 396 on each side, @@ -7932,7 +7920,7 @@ // Verify that when in overview mode, the selector items unsnappable indicator // shows up when expected. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, OverviewUnsnappableIndicatorVisibility) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -8004,7 +7992,7 @@ // Test that enabling the docked magnifier ends clamshell split view on all // displays. -TEST_P(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, +TEST_F(SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, DockedMagnifierEndsClamshellSplitView) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -8028,12 +8016,4 @@ EXPECT_FALSE(SplitViewController::Get(root_windows[1])->InSplitViewMode()); } -INSTANTIATE_TEST_SUITE_P(All, - SplitViewOverviewSessionInClamshellTest, - ::testing::Bool()); -INSTANTIATE_TEST_SUITE_P( - All, - SplitViewOverviewSessionInClamshellTestMultiDisplayOnly, - ::testing::Bool()); - } // namespace ash
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc index 3250e87..99c66cd 100644 --- a/ash/wm/splitview/split_view_controller.cc +++ b/ash/wm/splitview/split_view_controller.cc
@@ -1914,8 +1914,6 @@ } void SplitViewController::OnTabletModeEnded() { - DCHECK(IsLayoutPrimary(Shell::GetPrimaryRootWindow()) || - chromeos::wm::features::IsVerticalSnapEnabled()); is_previous_layout_right_side_up_ = true; }
diff --git a/ash/wm/splitview/split_view_controller.h b/ash/wm/splitview/split_view_controller.h index 1841adf..0ad28e2 100644 --- a/ash/wm/splitview/split_view_controller.h +++ b/ash/wm/splitview/split_view_controller.h
@@ -129,11 +129,9 @@ // true false right left // false true top bottom // false false bottom top - // In tablet mode, these functions return values based on display orientation. - // In clamshell mode, these functions return above values if - // `chromeos::wm::features::IsVerticalSnapEnabled()`; otherwise they return - // true. |window| is used to find the nearest display to check if the display - // layout is horizontal and is primary or not. + // In both clamshell and tablet mode, these functions return values based on + // display orientation. |window| is used to find the nearest display to check + // if the display layout is horizontal and is primary or not. static bool IsLayoutHorizontal(aura::Window* window); static bool IsLayoutHorizontal(const display::Display& display); static bool IsLayoutPrimary(aura::Window* window);
diff --git a/ash/wm/splitview/split_view_drag_indicators_unittest.cc b/ash/wm/splitview/split_view_drag_indicators_unittest.cc index 0ebb5e7..ad3b450 100644 --- a/ash/wm/splitview/split_view_drag_indicators_unittest.cc +++ b/ash/wm/splitview/split_view_drag_indicators_unittest.cc
@@ -462,40 +462,26 @@ } // Defines a test fixture to test behavior of SplitViewDragIndicators on -// multi-display in clamshell mode, parameterized to run with the feature -// |chromeos::wm::features::kVerticalSnap| enabled and disabled. +// multi-display in clamshell mode. class ClamshellMultiDisplaySplitViewDragIndicatorsTest - : public SplitViewDragIndicatorsTest, - public ::testing::WithParamInterface<bool> { + : public SplitViewDragIndicatorsTest { public: ClamshellMultiDisplaySplitViewDragIndicatorsTest() = default; ~ClamshellMultiDisplaySplitViewDragIndicatorsTest() override = default; // SplitViewDragIndicatorsTest: void SetUp() override { - if (GetParam()) - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); - else - scoped_feature_list_.InitAndDisableFeature( - chromeos::wm::features::kVerticalSnap); SplitViewDragIndicatorsTest::SetUp(); // Disable tablet mode that is enabled in // `SplitViewDragIndicatorsTest::SetUp()` to test clamshell mode. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(false); base::RunLoop().RunUntilIdle(); } - - bool IsVerticalSnapEnabled() const { return GetParam(); } - - protected: - base::test::ScopedFeatureList scoped_feature_list_; }; // Tests that dragging a window to external portrait display will layout -// split view drag indicators vertically instead of horizontally if -// |chromeos::wm::features::kVerticalSnap| is enabled. -TEST_P(ClamshellMultiDisplaySplitViewDragIndicatorsTest, +// split view drag indicators vertically instead of horizontally. +TEST_F(ClamshellMultiDisplaySplitViewDragIndicatorsTest, IndicatorsLayoutWhileDraggingWindowToPortraitDisplay) { UpdateDisplay("800x600,600x800"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); @@ -558,20 +544,9 @@ // Otherwise, the left indicator should be on the left and its height span // the work area height. left_indicator_bounds = indicators->GetLeftHighlightViewBounds(); - if (IsVerticalSnapEnabled()) { - EXPECT_EQ(left_indicator_bounds.width(), - portrait_display.work_area().width() - - 2 * kHighlightScreenEdgePaddingDp); - } else { - EXPECT_EQ(left_indicator_bounds.height(), - portrait_display.work_area().height() - - 2 * kHighlightScreenEdgePaddingDp); - } + EXPECT_EQ( + left_indicator_bounds.width(), + portrait_display.work_area().width() - 2 * kHighlightScreenEdgePaddingDp); } -// Instantiate the Boolean which is used to toggle the feature -// |chromeos::wm::features::kVerticalSnap| in the parameterized tests. -INSTANTIATE_TEST_SUITE_P(All, - ClamshellMultiDisplaySplitViewDragIndicatorsTest, - ::testing::Bool()); } // namespace ash
diff --git a/ash/wm/tablet_mode/tablet_mode_window_state.cc b/ash/wm/tablet_mode/tablet_mode_window_state.cc index ce487e8..eb28452 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_state.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_state.cc
@@ -229,8 +229,8 @@ // TODO(oshima|sammiequon): consider SplitView scenario. WindowState::ScopedBoundsChangeAnimation bounds_animation( window, entering_tablet_mode && !IsTopWindow(window) - ? WindowState::BoundsChangeAnimationType::STEP_END - : WindowState::BoundsChangeAnimationType::DEFAULT); + ? WindowState::BoundsChangeAnimationType::kAnimateZero + : WindowState::BoundsChangeAnimationType::kAnimate); old_window_bounds_in_screen_ = window->GetBoundsInScreen(); old_state_.reset( state->SetStateObject(std::unique_ptr<State>(this)).release()); @@ -249,11 +249,11 @@ WindowState::BoundsChangeAnimationType animation_type = was_in_overview || window_state->IsSnapped() || IsTopWindow(window_state->window()) - ? WindowState::BoundsChangeAnimationType::DEFAULT - : WindowState::BoundsChangeAnimationType::IMMEDIATE; + ? WindowState::BoundsChangeAnimationType::kAnimate + : WindowState::BoundsChangeAnimationType::kNone; if (old_state_->GetType() == window_state->GetStateType() && !window_state->IsNormalStateType()) { - animation_type = WindowState::BoundsChangeAnimationType::IMMEDIATE; + animation_type = WindowState::BoundsChangeAnimationType::kNone; } // Note: When we return we will destroy ourselves with the |our_reference|. @@ -537,7 +537,7 @@ window_state->SetBoundsDirect(bounds_in_parent); } else { if (window_state->bounds_animation_type() == - WindowState::BoundsChangeAnimationType::STEP_END) { + WindowState::BoundsChangeAnimationType::kAnimateZero) { // Just use the normal bounds animation with ZERO tween with long enough // duration for STEP_END. The animation will be stopped when the to // window's animation ends.
diff --git a/ash/wm/window_positioning_utils.cc b/ash/wm/window_positioning_utils.cc index ccb8b38..c40d016 100644 --- a/ash/wm/window_positioning_utils.cc +++ b/ash/wm/window_positioning_utils.cc
@@ -192,11 +192,9 @@ snap_bounds.set_x(work_area.right() - axis_length); break; case SnapPosition::kTop: - DCHECK(chromeos::wm::features::IsVerticalSnapEnabled()); snap_bounds.set_height(axis_length); break; case SnapPosition::kBottom: - DCHECK(chromeos::wm::features::IsVerticalSnapEnabled()); snap_bounds.set_height(axis_length); // Snap to the bottom. snap_bounds.set_y(work_area.bottom() - axis_length); @@ -210,9 +208,6 @@ chromeos::OrientationType GetSnapDisplayOrientation( const display::Display& display) { - if (!chromeos::wm::features::IsVerticalSnapEnabled()) - return chromeos::OrientationType::kLandscapePrimary; - // This function is used by `GetSnappedWindowBounds()` for clamshell mode // only. Tablet mode uses a different function // `SplitViewController::GetSnappedWindowBoundsInScreen()`.
diff --git a/ash/wm/window_state.h b/ash/wm/window_state.h index c194c62..4b11f0f 100644 --- a/ash/wm/window_state.h +++ b/ash/wm/window_state.h
@@ -61,10 +61,6 @@ // accessing the window using |window()| is cheap. class ASH_EXPORT WindowState : public aura::WindowObserver { public: - // The default duration for an animation between two sets of bounds. - static constexpr base::TimeDelta kBoundsChangeSlideDuration = - base::Milliseconds(120); - // A subclass of State class represents one of the window's states // that corresponds to chromeos::WindowStateType in Ash environment, e.g. // maximized, minimized or side snapped, as subclass. @@ -106,6 +102,25 @@ #endif // DCHECK_IS_ON() }; + // Type of animation type to be applied when changing bounds locally. + // TODO(oshima): Use transform animation for snapping. + enum class BoundsChangeAnimationType { + // No animation (`SetBoundsDirect()`). + kNone, + // Cross fade animation. Copies old layer, and fades it out while fading the + // new layer in. + kCrossFade, + // Bounds animation. + kAnimate, + // Bounds animation with zero tween. Updates the bounds once at the end of + // the animation. + kAnimateZero, + }; + + // The default duration for an animation between two sets of bounds. + static constexpr base::TimeDelta kBoundsChangeSlideDuration = + base::Milliseconds(120); + // Returns the WindowState for |window|. Creates WindowState if it doesn't // exist. The returned value is owned by |window| (you should not delete it). static WindowState* Get(aura::Window* window); @@ -418,11 +433,6 @@ FRIEND_TEST_ALL_PREFIXES(WindowAnimationsTest, CrossFadeToBoundsFromTransform); - // Animation type of updating window bounds. "IMMEDIATE" means update bounds - // directly without animation. "STEP_END" means update bounds at the end of - // the animation. - enum class BoundsChangeAnimationType { DEFAULT, IMMEDIATE, STEP_END }; - // A class can temporarily change the window bounds change animation type. class ScopedBoundsChangeAnimation : public aura::WindowObserver { public: @@ -606,7 +616,7 @@ // The animation type for the bounds change. BoundsChangeAnimationType bounds_animation_type_ = - BoundsChangeAnimationType::DEFAULT; + BoundsChangeAnimationType::kAnimate; // When the current (or last) PIP session started. base::TimeTicks pip_start_time_;
diff --git a/ash/wm/window_state_unittest.cc b/ash/wm/window_state_unittest.cc index ff7ade7..8ffa710 100644 --- a/ash/wm/window_state_unittest.cc +++ b/ash/wm/window_state_unittest.cc
@@ -1416,42 +1416,10 @@ WindowSnapActionSource::kOthers, 1); } -// Test WindowStateTest functionalities with portrait display. This test is -// parameterized to enable vertical layout or horizontal layout snap in -// portrait display. -class PortraitDisplayWindowStateTest - : public AshTestBase, - public ::testing::WithParamInterface<bool> { - public: - PortraitDisplayWindowStateTest() = default; - PortraitDisplayWindowStateTest(const PortraitDisplayWindowStateTest&) = - delete; - PortraitDisplayWindowStateTest& operator=( - const PortraitDisplayWindowStateTest&) = delete; - ~PortraitDisplayWindowStateTest() override = default; - - bool IsVerticalSnapEnabled() const { return GetParam(); } - - // WindowStateTest: - void SetUp() override { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); - } else { - scoped_feature_list_.InitAndDisableFeature( - chromeos::wm::features::kVerticalSnap); - } - AshTestBase::SetUp(); - UpdateDisplay("600x900"); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - // Test how the minimum height specified by the aura::WindowDelegate affects // snapping in portrait display layout. -TEST_P(PortraitDisplayWindowStateTest, SnapWindowMinimumSizePortrait) { +TEST_F(WindowStateTest, SnapWindowMinimumSizePortrait) { + UpdateDisplay("600x900"); const gfx::Rect kWorkAreaBounds = display::Screen::GetScreen()->GetPrimaryDisplay().work_area(); @@ -1463,8 +1431,7 @@ // a half screen width in horizontal snap layout and snap a window with a // minimum height that is longer than a half screen height in vertical snap // layout. - const gfx::Size kMinimumSize = - IsVerticalSnapEnabled() ? gfx::Size(0, 500) : gfx::Size(400, 0); + const gfx::Size kMinimumSize = gfx::Size(0, 500); delegate.set_minimum_size(kMinimumSize); WindowState* window_state = WindowState::Get(window.get()); EXPECT_TRUE(window_state->CanSnap()); @@ -1472,21 +1439,12 @@ window_state->OnWMEvent(&snap_secondary); // Expect right snap for horizontal snap layout with the minimum width and // bottom snap for vertical snap layout with the minimum height. - const gfx::Rect expected_snap = - IsVerticalSnapEnabled() - ? gfx::Rect(kWorkAreaBounds.x(), - kWorkAreaBounds.height() - kMinimumSize.height(), - kWorkAreaBounds.width(), kMinimumSize.height()) - : gfx::Rect(kWorkAreaBounds.width() - kMinimumSize.width(), - kWorkAreaBounds.y(), kMinimumSize.width(), - kWorkAreaBounds.height()); + const gfx::Rect expected_snap = gfx::Rect( + kWorkAreaBounds.x(), kWorkAreaBounds.height() - kMinimumSize.height(), + kWorkAreaBounds.width(), kMinimumSize.height()); EXPECT_EQ(expected_snap, window->GetBoundsInScreen()); } -INSTANTIATE_TEST_SUITE_P(All, - PortraitDisplayWindowStateTest, - ::testing::Bool()); - // TODO(skuhne): Add more unit test to verify the correctness for the restore // operation.
diff --git a/ash/wm/workspace/workspace_window_resizer.cc b/ash/wm/workspace/workspace_window_resizer.cc index 970731e9..9413d3e 100644 --- a/ash/wm/workspace/workspace_window_resizer.cc +++ b/ash/wm/workspace/workspace_window_resizer.cc
@@ -812,8 +812,7 @@ kSnapDragDwellTimeResetThreshold; // If vertical snap state is enabled, update phantom window for top/bottom // snap before setting a timer for maximize phantom to show up. - if (chromeos::wm::features::IsVerticalSnapEnabled() && - !snap_phantom_window_controller_ && + if (!snap_phantom_window_controller_ && snap_type != SnapType::kMaximize) { UpdateSnapPhantomWindow(snap_type); } @@ -825,10 +824,7 @@ // before it turns into maximize phantom window. dwell_countdown_timer_.Start( FROM_HERE, - (chromeos::wm::features::IsVerticalSnapEnabled() && - snap_type != SnapType::kMaximize) - ? kDwellLongTime - : kDwellTime, + snap_type != SnapType::kMaximize ? kDwellLongTime : kDwellTime, base::BindOnce(&WorkspaceWindowResizer::UpdateSnapPhantomWindow, weak_ptr_factory_.GetWeakPtr(), SnapType::kMaximize));
diff --git a/ash/wm/workspace/workspace_window_resizer_unittest.cc b/ash/wm/workspace/workspace_window_resizer_unittest.cc index 6621918b..86ef5c1 100644 --- a/ash/wm/workspace/workspace_window_resizer_unittest.cc +++ b/ash/wm/workspace/workspace_window_resizer_unittest.cc
@@ -2406,17 +2406,12 @@ // WorkspaceWindowResizerTest: void SetUp() override { - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); WorkspaceWindowResizerTest::SetUp(); UpdateDisplay("600x800"); // Make the window snappable. AllowSnap(window_.get()); } - - private: - base::test::ScopedFeatureList scoped_feature_list_; }; // Tests that dragging to an external portrait display updates phantom snap to @@ -2642,44 +2637,18 @@ } } +using MultiOrientationDisplayWorkspaceWindowResizerTest = + WorkspaceWindowResizerTest; + // Test WorkspaceWindowResizer functionalities for two displays with different -// orientation: landscape and portrait. This test is parameterized to enable -// vertical or horizontal snap layout in the portrait display. -class MultiOrientationDisplayWorkspaceWindowResizerTest - : public WorkspaceWindowResizerTest, - public ::testing::WithParamInterface<bool> { - public: - MultiOrientationDisplayWorkspaceWindowResizerTest() = default; - MultiOrientationDisplayWorkspaceWindowResizerTest( - const MultiOrientationDisplayWorkspaceWindowResizerTest&) = delete; - MultiOrientationDisplayWorkspaceWindowResizerTest& operator=( - const MultiOrientationDisplayWorkspaceWindowResizerTest&) = delete; - ~MultiOrientationDisplayWorkspaceWindowResizerTest() override = default; +// orientation: landscape and portrait. Assertions around dragging near the four +// edges of the display. +TEST_F(MultiOrientationDisplayWorkspaceWindowResizerTest, Edge) { + UpdateDisplay("800x600,500x600"); - bool IsVerticalSnapEnabled() const { return GetParam(); } + // Make the window snappable. + AllowSnap(window_.get()); - // WorkspaceWindowResizerTest: - void SetUp() override { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - chromeos::wm::features::kVerticalSnap); - } else { - scoped_feature_list_.InitAndDisableFeature( - chromeos::wm::features::kVerticalSnap); - } - WorkspaceWindowResizerTest::SetUp(); - UpdateDisplay("800x600,500x600"); - - // Make the window snappable. - AllowSnap(window_.get()); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -// Assertions around dragging near the four edges of the display. -TEST_P(MultiOrientationDisplayWorkspaceWindowResizerTest, Edge) { window_->SetBounds(gfx::Rect(20, 30, 400, 60)); WindowState* window_state = WindowState::Get(window_.get()); // Test dragging to another display and snapping there. @@ -2709,12 +2678,8 @@ EXPECT_EQ(root_windows[1], window_->GetRootWindow()); const gfx::Rect secondary_snap_bounds = - IsVerticalSnapEnabled() ? gfx::Rect(0, display2_work_area.height() / 2, - display2_work_area.width(), - display2_work_area.height() / 2) - : gfx::Rect(display2_work_area.width() / 2, 0, - display2_work_area.width() / 2, - display2_work_area.height()); + gfx::Rect(0, display2_work_area.height() / 2, + display2_work_area.width(), display2_work_area.height() / 2); EXPECT_EQ(secondary_snap_bounds, window_->bounds()); EXPECT_EQ(gfx::Rect(820, 30, 400, 60), window_state->GetRestoreBoundsInScreen()); @@ -2740,18 +2705,11 @@ resizer->Drag(CalculateDragPoint(*resizer, 0, -100), 0); resizer->CompleteDrag(); const gfx::Rect primary_snap_bounds = - IsVerticalSnapEnabled() ? gfx::Rect(display2_work_area.width(), - display2_work_area.height() / 2) - : gfx::Rect(display2_work_area.width() / 2, - display2_work_area.height()); + gfx::Rect(display2_work_area.width(), display2_work_area.height() / 2); EXPECT_EQ(primary_snap_bounds, window_->bounds()); EXPECT_EQ(gfx::Rect(820, 30, 400, 60), window_state->GetRestoreBoundsInScreen()); } } -INSTANTIATE_TEST_SUITE_P(All, - MultiOrientationDisplayWorkspaceWindowResizerTest, - ::testing::Bool()); - } // namespace ash
diff --git a/base/compiler_specific.h b/base/compiler_specific.h index bb43ab3..8ef4a32 100644 --- a/base/compiler_specific.h +++ b/base/compiler_specific.h
@@ -170,6 +170,8 @@ #endif // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks. +// Security Note: if you just need to allow calling of dlsym functions use +// DISABLE_CFI_DLSYM. #if !defined(DISABLE_CFI_ICALL) #if BUILDFLAG(IS_WIN) // Windows also needs __declspec(guard(nocf)). @@ -182,6 +184,21 @@ #define DISABLE_CFI_ICALL #endif +// DISABLE_CFI_DLSYM -- applies DISABLE_CFI_ICALL on platforms where dlsym +// functions must be called. Retains CFI checks on platforms where loaded +// modules participate in CFI (e.g. Windows). +#if !defined(DISABLE_CFI_DLSYM) +#if BUILDFLAG(IS_WIN) +// Windows modules register functions when loaded so can be checked by CFG. +#define DISABLE_CFI_DLSYM +#else +#define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL +#endif +#endif +#if !defined(DISABLE_CFI_DLSYM) +#define DISABLE_CFI_DLSYM +#endif + // Macro useful for writing cross-platform function pointers. #if !defined(CDECL) #if BUILDFLAG(IS_WIN)
diff --git a/base/task/thread_pool/task_source.cc b/base/task/thread_pool/task_source.cc index aeddbe5..bdc49ad 100644 --- a/base/task/thread_pool/task_source.cc +++ b/base/task/thread_pool/task_source.cc
@@ -165,5 +165,26 @@ std::move(transaction)); } +TaskSourceAndTransaction::TaskSourceAndTransaction( + TaskSourceAndTransaction&& other) = default; + +TaskSourceAndTransaction::~TaskSourceAndTransaction() = default; + +TaskSourceAndTransaction::TaskSourceAndTransaction( + scoped_refptr<TaskSource> task_source_in, + TaskSource::Transaction transaction_in) + : task_source(std::move(task_source_in)), + transaction(std::move(transaction_in)) { + DCHECK_EQ(task_source.get(), transaction.task_source()); +} + +// static: +TaskSourceAndTransaction TaskSourceAndTransaction::FromTaskSource( + scoped_refptr<TaskSource> task_source_in) { + auto transaction = task_source_in->BeginTransaction(); + return TaskSourceAndTransaction(std::move(task_source_in), + std::move(transaction)); +} + } // namespace internal } // namespace base
diff --git a/base/task/thread_pool/task_source.h b/base/task/thread_pool/task_source.h index a00fd98..a5f653ec 100644 --- a/base/task/thread_pool/task_source.h +++ b/base/task/thread_pool/task_source.h
@@ -321,6 +321,23 @@ TaskSource::Transaction transaction; }; +struct BASE_EXPORT TaskSourceAndTransaction { + public: + TaskSourceAndTransaction(scoped_refptr<TaskSource> task_source_in, + TaskSource::Transaction transaction_in); + + TaskSourceAndTransaction(TaskSourceAndTransaction&& other); + TaskSourceAndTransaction(const TaskSourceAndTransaction&) = delete; + TaskSourceAndTransaction& operator=(const TaskSourceAndTransaction&) = delete; + ~TaskSourceAndTransaction(); + + static TaskSourceAndTransaction FromTaskSource( + scoped_refptr<TaskSource> task_source_in); + + scoped_refptr<TaskSource> task_source; + TaskSource::Transaction transaction; +}; + } // namespace internal } // namespace base
diff --git a/build/android/gyp/javac_output_processor.py b/build/android/gyp/javac_output_processor.py index 20ea5b9a..6c713ba3 100755 --- a/build/android/gyp/javac_output_processor.py +++ b/build/android/gyp/javac_output_processor.py
@@ -40,19 +40,15 @@ r'(?P<full_message> (?P<message>.*))$') self._marker_re = re.compile(r'\s*(?P<marker>\^)\s*$') - # First element in pair is bool which indicates whether the missing - # class/package is part of the error message. self._symbol_not_found_re_list = [ # Example: # error: package org.chromium.components.url_formatter does not exist - (True, - re.compile(fileline_prefix + - r'( error: package [\w.]+ does not exist)$')), + re.compile(fileline_prefix + + r'( error: package [\w.]+ does not exist)$'), # Example: error: cannot find symbol - (False, re.compile(fileline_prefix + r'( error: cannot find symbol)$')), + re.compile(fileline_prefix + r'( error: cannot find symbol)$'), # Example: error: symbol not found org.chromium.url.GURL - (True, - re.compile(fileline_prefix + r'( error: symbol not found [\w.]+)$')), + re.compile(fileline_prefix + r'( error: symbol not found [\w.]+)$'), ] # Example: import org.chromium.url.GURL; @@ -139,40 +135,37 @@ if not import_re_match: return - symbol_missing = False - has_missing_symbol_in_error_msg = False - for symbol_in_error_msg, regex in self._symbol_not_found_re_list: + for regex in self._symbol_not_found_re_list: if regex.match(line): - symbol_missing = True - has_missing_symbol_in_error_msg = symbol_in_error_msg break - - if not symbol_missing: + else: return + if self._class_lookup_index is None: + self._class_lookup_index = lookup_dep.ClassLookupIndex( + pathlib.Path(os.getcwd()), + should_build=False, + ) + class_to_lookup = import_re_match.group('imported_class') - if self._class_lookup_index == None: - self._class_lookup_index = lookup_dep.ClassLookupIndex(pathlib.Path( - os.getcwd()), - should_build=False) suggested_deps = self._class_lookup_index.match(class_to_lookup) - if len(suggested_deps) != 1: - suggested_deps = self._DisambiguateDeps(suggested_deps) + if not suggested_deps: + return - if len(suggested_deps) != 1: - suggested_target = ('one of: ' + ', '.join(s.target - for s in suggested_deps)) - else: - suggested_target = suggested_deps[0].target + suggested_deps = self._DisambiguateDeps(suggested_deps) + suggested_deps_str = ', '.join(s.target for s in suggested_deps) - if not has_missing_symbol_in_error_msg: - line = "{} {}".format(line, class_to_lookup) + if len(suggested_deps) > 1: + suggested_deps_str = 'one of: ' + suggested_deps_str - self._suggested_deps.add(suggested_target) + self._suggested_deps.add(suggested_deps_str) @staticmethod def _DisambiguateDeps(class_entries): + if len(class_entries) == 1: + return class_entries + # android_library_factory() targets set low_classpath_priority=true, and any # target that is the "impl" side of a target that uses jar_excluded_patterns # should use this as well.
diff --git a/build/android/gyp/turbine.py b/build/android/gyp/turbine.py index 2d71b13e..cdf4105a 100755 --- a/build/android/gyp/turbine.py +++ b/build/android/gyp/turbine.py
@@ -7,14 +7,11 @@ import argparse import functools import logging -import os -import shutil import sys import time import javac_output_processor from util import build_utils -from util import server_utils def ProcessJavacOutput(output, target_name):
diff --git a/build/android/gyp/turbine.pydeps b/build/android/gyp/turbine.pydeps index 9e82b0cf..8f20e8b 100644 --- a/build/android/gyp/turbine.pydeps +++ b/build/android/gyp/turbine.pydeps
@@ -24,4 +24,3 @@ turbine.py util/__init__.py util/build_utils.py -util/server_utils.py
diff --git a/build/android/pylib/local/emulator/avd.py b/build/android/pylib/local/emulator/avd.py index 9c1b0929..d81d513 100644 --- a/build/android/pylib/local/emulator/avd.py +++ b/build/android/pylib/local/emulator/avd.py
@@ -90,6 +90,42 @@ return text_format.Merge(avd_proto_file.read(), avd_pb2.Avd()) +def _FindMinSdkFile(apk_dir, min_sdk): + """Finds the apk file associated with the min_sdk file. + + This reads a version.json file located in the apk_dir to find an apk file + that is closest without going over the min_sdk. + + Args: + apk_dir: The directory to look for apk files. + min_sdk: The minimum sdk version supported by the device. + + Returns: + The path to the file that suits the minSdkFile or None + """ + json_file = os.path.join(apk_dir, 'version.json') + if not os.path.exists(json_file): + logging.error('Json version file not found: %s', json_file) + return None + + min_sdk_found = None + curr_min_sdk_version = 0 + with open(json_file) as f: + data = json.loads(f.read()) + # Finds the entry that is closest to min_sdk without going over. + for entry in data: + if (entry['min_sdk'] > curr_min_sdk_version + and entry['min_sdk'] <= min_sdk): + min_sdk_found = entry + curr_min_sdk_version = entry['min_sdk'] + + if not min_sdk_found: + logging.error('No suitable apk file found that suits the minimum sdk.') + return None + + return os.path.join(apk_dir, min_sdk_found['file_name']) + + class _AvdManagerAgent: """Private utility for interacting with avdmanager.""" @@ -270,6 +306,8 @@ self._InstallCipdPackages(packages=[ self._config.emulator_package, self._config.system_image_package, + *self._config.privileged_apk, + *self._config.additional_apk, ]) android_avd_home = self._avd_home @@ -344,13 +382,14 @@ self._config) # Enable debug for snapshot when it is set to True debug_tags = 'init,snapshot' if snapshot else None - # Installing privileged apks requires modifying the system image. - writable_system = bool(privileged_apk_tuples) - instance.Start(ensure_system_settings=False, - read_only=False, - writable_system=writable_system, - gpu_mode=_DEFAULT_GPU_MODE, - debug_tags=debug_tags) + instance.Start( + ensure_system_settings=False, + read_only=False, + # Installing privileged apks requires modifying the system + # image. + writable_system=True, + gpu_mode=_DEFAULT_GPU_MODE, + debug_tags=debug_tags) assert instance.device is not None, '`instance.device` not initialized.' # Android devices with full-disk encryption are encrypted on first boot, @@ -360,11 +399,29 @@ # like M, otherwise the avd may have "Encryption Unsuccessful" error. instance.device.WaitUntilFullyBooted(decrypt=True, timeout=180, retries=0) + if not additional_apks: + additional_apks = [] + for apk_package in self._config.additional_apk: + apk_dir = os.path.join(COMMON_CIPD_ROOT, apk_package.dest_path) + for f in os.listdir(apk_dir): + if os.path.isfile(f) and f.endswith('.apk'): + additional_apks.append(os.path.join(apk_dir, f)) + if additional_apks: - for additional_apk in additional_apks: - instance.device.Install(additional_apk, - allow_downgrade=True, - reinstall=True) + for apk in additional_apks: + instance.device.Install(apk, allow_downgrade=True, reinstall=True) + + if not privileged_apk_tuples: + privileged_apk_tuples = [] + for pkg in self._config.privileged_apk: + apk_dir = os.path.join(COMMON_CIPD_ROOT, pkg.dest_path) + apk_file = _FindMinSdkFile(apk_dir, self._config.min_sdk) + # Some of these files come from chrome internal, so may not be + # available to non-internal permissioned users. + if os.path.exists(apk_file): + logging.info('Adding privilege apk for install: %s', apk_file) + privileged_apk_tuples.append( + (apk_file, self._config.install_privileged_apk_partition)) if privileged_apk_tuples: system_app.InstallPrivilegedApps(instance.device, privileged_apk_tuples) @@ -489,6 +546,8 @@ self._config.avd_package, self._config.emulator_package, self._config.system_image_package, + *self._config.privileged_apk, + *self._config.additional_apk, ] for pkg in packages: # Skip when no version exists to prevent "IsAvailable()" returning False
diff --git a/build/android/pylib/local/emulator/proto/avd.proto b/build/android/pylib/local/emulator/proto/avd.proto index 269c21b8..5f070bcf8 100644 --- a/build/android/pylib/local/emulator/proto/avd.proto +++ b/build/android/pylib/local/emulator/proto/avd.proto
@@ -80,4 +80,16 @@ // How to configure the AVD at creation. AvdSettings avd_settings = 6; + + // min sdk level for emulator. + uint32 min_sdk = 7; + + // The partition to install the privileged apk. + // version 27 and below is /system. After that it can be + // /system, /product, or /vendor + string install_privileged_apk_partition = 8; + + // Needed for gmscore/phonesky support. + repeated CIPDPackage privileged_apk = 9; + repeated CIPDPackage additional_apk = 10; }
diff --git a/build/android/pylib/local/emulator/proto/avd_pb2.py b/build/android/pylib/local/emulator/proto/avd_pb2.py index 79d1653b..e43534c 100644 --- a/build/android/pylib/local/emulator/proto/avd_pb2.py +++ b/build/android/pylib/local/emulator/proto/avd_pb2.py
@@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! -# source: avd.proto +# source: build/android/pylib/local/emulator/proto/avd.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message @@ -14,11 +14,12 @@ DESCRIPTOR = _descriptor.FileDescriptor( - name='avd.proto', + name='build/android/pylib/local/emulator/proto/avd.proto', package='tools.android.avd.proto', syntax='proto3', serialized_options=None, - serialized_pb=b'\n\tavd.proto\x12\x17tools.android.avd.proto\"G\n\x0b\x43IPDPackage\x12\x14\n\x0cpackage_name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x11\n\tdest_path\x18\x03 \x01(\t\"@\n\x0eScreenSettings\x12\x0e\n\x06height\x18\x01 \x01(\r\x12\r\n\x05width\x18\x02 \x01(\r\x12\x0f\n\x07\x64\x65nsity\x18\x03 \x01(\r\"\x1e\n\x0eSdcardSettings\x12\x0c\n\x04size\x18\x01 \x01(\t\"\xa8\x03\n\x0b\x41vdSettings\x12\x37\n\x06screen\x18\x01 \x01(\x0b\x32\'.tools.android.avd.proto.ScreenSettings\x12\x37\n\x06sdcard\x18\x02 \x01(\x0b\x32\'.tools.android.avd.proto.SdcardSettings\x12U\n\x11\x61\x64vanced_features\x18\x03 \x03(\x0b\x32:.tools.android.avd.proto.AvdSettings.AdvancedFeaturesEntry\x12\x10\n\x08ram_size\x18\x04 \x01(\r\x12O\n\x0e\x61vd_properties\x18\x05 \x03(\x0b\x32\x37.tools.android.avd.proto.AvdSettings.AvdPropertiesEntry\x1a\x37\n\x15\x41\x64vancedFeaturesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x34\n\x12\x41vdPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xad\x02\n\x03\x41vd\x12>\n\x10\x65mulator_package\x18\x01 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x42\n\x14system_image_package\x18\x02 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x19\n\x11system_image_name\x18\x03 \x01(\t\x12\x39\n\x0b\x61vd_package\x18\x04 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x10\n\x08\x61vd_name\x18\x05 \x01(\t\x12:\n\x0c\x61vd_settings\x18\x06 \x01(\x0b\x32$.tools.android.avd.proto.AvdSettingsb\x06proto3' + create_key=_descriptor._internal_create_key, + serialized_pb=b'\n2build/android/pylib/local/emulator/proto/avd.proto\x12\x17tools.android.avd.proto\"G\n\x0b\x43IPDPackage\x12\x14\n\x0cpackage_name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x11\n\tdest_path\x18\x03 \x01(\t\"@\n\x0eScreenSettings\x12\x0e\n\x06height\x18\x01 \x01(\r\x12\r\n\x05width\x18\x02 \x01(\r\x12\x0f\n\x07\x64\x65nsity\x18\x03 \x01(\r\"\x1e\n\x0eSdcardSettings\x12\x0c\n\x04size\x18\x01 \x01(\t\"\xa8\x03\n\x0b\x41vdSettings\x12\x37\n\x06screen\x18\x01 \x01(\x0b\x32\'.tools.android.avd.proto.ScreenSettings\x12\x37\n\x06sdcard\x18\x02 \x01(\x0b\x32\'.tools.android.avd.proto.SdcardSettings\x12U\n\x11\x61\x64vanced_features\x18\x03 \x03(\x0b\x32:.tools.android.avd.proto.AvdSettings.AdvancedFeaturesEntry\x12\x10\n\x08ram_size\x18\x04 \x01(\r\x12O\n\x0e\x61vd_properties\x18\x05 \x03(\x0b\x32\x37.tools.android.avd.proto.AvdSettings.AvdPropertiesEntry\x1a\x37\n\x15\x41\x64vancedFeaturesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x34\n\x12\x41vdPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe4\x03\n\x03\x41vd\x12>\n\x10\x65mulator_package\x18\x01 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x42\n\x14system_image_package\x18\x02 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x19\n\x11system_image_name\x18\x03 \x01(\t\x12\x39\n\x0b\x61vd_package\x18\x04 \x01(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12\x10\n\x08\x61vd_name\x18\x05 \x01(\t\x12:\n\x0c\x61vd_settings\x18\x06 \x01(\x0b\x32$.tools.android.avd.proto.AvdSettings\x12\x0f\n\x07min_sdk\x18\x07 \x01(\r\x12(\n install_privileged_apk_partition\x18\x08 \x01(\t\x12<\n\x0eprivileged_apk\x18\t \x03(\x0b\x32$.tools.android.avd.proto.CIPDPackage\x12<\n\x0e\x61\x64\x64itional_apk\x18\n \x03(\x0b\x32$.tools.android.avd.proto.CIPDPackageb\x06proto3' ) @@ -30,6 +31,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='package_name', full_name='tools.android.avd.proto.CIPDPackage.package_name', index=0, @@ -37,21 +39,21 @@ has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='version', full_name='tools.android.avd.proto.CIPDPackage.version', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='dest_path', full_name='tools.android.avd.proto.CIPDPackage.dest_path', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -64,8 +66,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=38, - serialized_end=109, + serialized_start=79, + serialized_end=150, ) @@ -75,6 +77,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='height', full_name='tools.android.avd.proto.ScreenSettings.height', index=0, @@ -82,21 +85,21 @@ has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='width', full_name='tools.android.avd.proto.ScreenSettings.width', index=1, number=2, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='density', full_name='tools.android.avd.proto.ScreenSettings.density', index=2, number=3, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -109,8 +112,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=111, - serialized_end=175, + serialized_start=152, + serialized_end=216, ) @@ -120,6 +123,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='size', full_name='tools.android.avd.proto.SdcardSettings.size', index=0, @@ -127,7 +131,7 @@ has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -140,8 +144,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=177, - serialized_end=207, + serialized_start=218, + serialized_end=248, ) @@ -151,6 +155,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='key', full_name='tools.android.avd.proto.AvdSettings.AdvancedFeaturesEntry.key', index=0, @@ -158,14 +163,14 @@ has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='value', full_name='tools.android.avd.proto.AvdSettings.AdvancedFeaturesEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -178,8 +183,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=525, - serialized_end=580, + serialized_start=566, + serialized_end=621, ) _AVDSETTINGS_AVDPROPERTIESENTRY = _descriptor.Descriptor( @@ -188,6 +193,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='key', full_name='tools.android.avd.proto.AvdSettings.AvdPropertiesEntry.key', index=0, @@ -195,14 +201,14 @@ has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='value', full_name='tools.android.avd.proto.AvdSettings.AvdPropertiesEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -215,8 +221,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=582, - serialized_end=634, + serialized_start=623, + serialized_end=675, ) _AVDSETTINGS = _descriptor.Descriptor( @@ -225,6 +231,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='screen', full_name='tools.android.avd.proto.AvdSettings.screen', index=0, @@ -232,35 +239,35 @@ has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='sdcard', full_name='tools.android.avd.proto.AvdSettings.sdcard', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='advanced_features', full_name='tools.android.avd.proto.AvdSettings.advanced_features', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='ram_size', full_name='tools.android.avd.proto.AvdSettings.ram_size', index=3, number=4, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='avd_properties', full_name='tools.android.avd.proto.AvdSettings.avd_properties', index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -273,8 +280,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=210, - serialized_end=634, + serialized_start=251, + serialized_end=675, ) @@ -284,6 +291,7 @@ filename=None, file=DESCRIPTOR, containing_type=None, + create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='emulator_package', full_name='tools.android.avd.proto.Avd.emulator_package', index=0, @@ -291,42 +299,70 @@ has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='system_image_package', full_name='tools.android.avd.proto.Avd.system_image_package', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='system_image_name', full_name='tools.android.avd.proto.Avd.system_image_name', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='avd_package', full_name='tools.android.avd.proto.Avd.avd_package', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='avd_name', full_name='tools.android.avd.proto.Avd.avd_name', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='avd_settings', full_name='tools.android.avd.proto.Avd.avd_settings', index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='min_sdk', full_name='tools.android.avd.proto.Avd.min_sdk', index=6, + number=7, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='install_privileged_apk_partition', full_name='tools.android.avd.proto.Avd.install_privileged_apk_partition', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='privileged_apk', full_name='tools.android.avd.proto.Avd.privileged_apk', index=8, + number=9, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='additional_apk', full_name='tools.android.avd.proto.Avd.additional_apk', index=9, + number=10, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], @@ -339,8 +375,8 @@ extension_ranges=[], oneofs=[ ], - serialized_start=637, - serialized_end=938, + serialized_start=678, + serialized_end=1162, ) _AVDSETTINGS_ADVANCEDFEATURESENTRY.containing_type = _AVDSETTINGS @@ -353,6 +389,8 @@ _AVD.fields_by_name['system_image_package'].message_type = _CIPDPACKAGE _AVD.fields_by_name['avd_package'].message_type = _CIPDPACKAGE _AVD.fields_by_name['avd_settings'].message_type = _AVDSETTINGS +_AVD.fields_by_name['privileged_apk'].message_type = _CIPDPACKAGE +_AVD.fields_by_name['additional_apk'].message_type = _CIPDPACKAGE DESCRIPTOR.message_types_by_name['CIPDPackage'] = _CIPDPACKAGE DESCRIPTOR.message_types_by_name['ScreenSettings'] = _SCREENSETTINGS DESCRIPTOR.message_types_by_name['SdcardSettings'] = _SDCARDSETTINGS @@ -362,21 +400,21 @@ CIPDPackage = _reflection.GeneratedProtocolMessageType('CIPDPackage', (_message.Message,), { 'DESCRIPTOR' : _CIPDPACKAGE, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.CIPDPackage) }) _sym_db.RegisterMessage(CIPDPackage) ScreenSettings = _reflection.GeneratedProtocolMessageType('ScreenSettings', (_message.Message,), { 'DESCRIPTOR' : _SCREENSETTINGS, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.ScreenSettings) }) _sym_db.RegisterMessage(ScreenSettings) SdcardSettings = _reflection.GeneratedProtocolMessageType('SdcardSettings', (_message.Message,), { 'DESCRIPTOR' : _SDCARDSETTINGS, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.SdcardSettings) }) _sym_db.RegisterMessage(SdcardSettings) @@ -385,19 +423,19 @@ 'AdvancedFeaturesEntry' : _reflection.GeneratedProtocolMessageType('AdvancedFeaturesEntry', (_message.Message,), { 'DESCRIPTOR' : _AVDSETTINGS_ADVANCEDFEATURESENTRY, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.AvdSettings.AdvancedFeaturesEntry) }) , 'AvdPropertiesEntry' : _reflection.GeneratedProtocolMessageType('AvdPropertiesEntry', (_message.Message,), { 'DESCRIPTOR' : _AVDSETTINGS_AVDPROPERTIESENTRY, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.AvdSettings.AvdPropertiesEntry) }) , 'DESCRIPTOR' : _AVDSETTINGS, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.AvdSettings) }) _sym_db.RegisterMessage(AvdSettings) @@ -406,7 +444,7 @@ Avd = _reflection.GeneratedProtocolMessageType('Avd', (_message.Message,), { 'DESCRIPTOR' : _AVD, - '__module__' : 'avd_pb2' + '__module__' : 'build.android.pylib.local.emulator.proto.avd_pb2' # @@protoc_insertion_point(class_scope:tools.android.avd.proto.Avd) }) _sym_db.RegisterMessage(Avd)
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 437e8b94..9fbd5db 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -1536,20 +1536,16 @@ ] if (!is_nacl) { - # TODO(https://crbug.com/1300731) Clean up and enable. - cflags += [ "-Wno-unqualified-std-cast-call" ] + cflags += [ + # TODO(https://crbug.com/1300731) Clean up and enable. + "-Wno-unqualified-std-cast-call", - # Do not set the below flags if it's nacl as nacl-clang doesn't have the - # patches that require these flags. - if (llvm_force_head_revision) { - cflags += [ - # TODO(crbug.com/1343303) Evaluate and possibly enable. - "-Wno-array-parameter", + # TODO(crbug.com/1343303) Evaluate and possibly enable. + "-Wno-array-parameter", - # TODO(crbug.com/1343975) Evaluate and possibly enable. - "-Wno-deprecated-builtins", - ] - } + # TODO(crbug.com/1343975) Evaluate and possibly enable. + "-Wno-deprecated-builtins", + ] } if (is_fuchsia) {
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index 9c240c5..4833a61 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -9.20220725.1.1 +9.20220725.3.1
diff --git a/build/nocompile.gni b/build/nocompile.gni index a7d3ba0..04c9875 100644 --- a/build/nocompile.gni +++ b/build/nocompile.gni
@@ -128,7 +128,7 @@ ] } - if (llvm_force_head_revision && !is_nacl) { + if (!is_nacl) { args += [ # TODO(crbug.com/1343975) Evaluate and possibly enable. "-Wno-deprecated-builtins",
diff --git a/build/toolchain/concurrent_links.gni b/build/toolchain/concurrent_links.gni index 1efd820..0835ef1 100644 --- a/build/toolchain/concurrent_links.gni +++ b/build/toolchain/concurrent_links.gni
@@ -73,6 +73,16 @@ _args = [ "--mem_per_link_gb=3" ] } else if (current_os == "zos") { _args = [ "--mem_per_link_gb=1" ] + } else if (is_fuchsia) { + # TODO(crbug.com/1347159): This was defaulting to 8GB. The number of + # linker instances to run in parallel is calculated by diviging + # the available memory by this value. On a 32GB machine with + # roughly 29GB of available memory, this would cause three instances + # to run. This started running out of memory and thrashing. This change + # addresses that issue to get the SDk rollers running again but + # could be optimized (maybe to 12GB or for different configs like + # component build). + _args = [ "--mem_per_link_gb=16" ] } else { _args = [] }
diff --git a/chrome/VERSION b/chrome/VERSION index 3e91115..438b5ec 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=106 MINOR=0 -BUILD=5202 +BUILD=5203 PATCH=0
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 67e0a81..587b647 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -789,7 +789,7 @@ <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT3" desc="The name of the Lens Region Search command in the content area context menu"> Search inside image with <ph name="VISUAL_SEARCH_PROVIDER">$1<ex>Google Lens</ex></ph> </message> - <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4" desc="The name of the Lens Region Search command in the content area context menu"> + <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH" desc="The name of the Lens Region Search command in the content area context menu"> Search images with <ph name="VISUAL_SEARCH_PROVIDER">$1<ex>Google Lens</ex></ph> </message> <message name="IDS_CONTENT_CONTEXT_GOTOURL" desc="The name of the Go to 'url' command in the content area context menu"> @@ -1059,7 +1059,7 @@ <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT3" desc="In Title Case: The name of the Lens Region Search command in the content area context menu"> Search inside Image with <ph name="VISUAL_SEARCH_PROVIDER">$1<ex>Google Lens</ex></ph> </message> - <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4" desc="In Title Case: The name of the Lens Region Search command in the content area context menu"> + <message name="IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH" desc="In Title Case: The name of the Lens Region Search command in the content area context menu"> Search Images with <ph name="VISUAL_SEARCH_PROVIDER">$1<ex>Google Lens</ex></ph> </message> <message name="IDS_CONTENT_CONTEXT_GOTOURL" desc="In Title Case: The name of the Go to url for 'string' command in the content area context menu">
diff --git a/chrome/app/generated_resources_grd/IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4.png.sha1 b/chrome/app/generated_resources_grd/IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4.png.sha1 rename to chrome/app/generated_resources_grd/IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH.png.sha1
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 2c108169..ccac2dbd 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -4042,6 +4042,10 @@ "performance_manager/user_tuning/profile_discard_opt_out_list_helper.h", "permissions/attestation_permission_request.cc", "permissions/attestation_permission_request.h", + "policy/browsing_history_policy_handler.cc", + "policy/browsing_history_policy_handler.h", + "policy/developer_tools_policy_handler.cc", + "policy/developer_tools_policy_handler.h", "policy/device_account_initializer.cc", "policy/device_account_initializer.h", "policy/managed_account_policy_handler.cc", @@ -4070,6 +4074,8 @@ "profile_resetter/triggered_profile_resetter.h", "profile_resetter/triggered_profile_resetter_factory.cc", "profile_resetter/triggered_profile_resetter_factory.h", + "profiles/guest_mode_policy_handler.cc", + "profiles/guest_mode_policy_handler.h", "profiles/guest_profile_creation_logger.cc", "profiles/guest_profile_creation_logger.h", "profiles/profile_shortcut_manager.cc", @@ -4510,6 +4516,8 @@ "apps/app_service/app_service_proxy_desktop.h", "external_protocol/auto_launch_protocols_policy_handler.cc", "external_protocol/auto_launch_protocols_policy_handler.h", + "net/disk_cache_dir_policy_handler.cc", + "net/disk_cache_dir_policy_handler.h", "policy/file_selection_dialogs_policy_handler.cc", "policy/file_selection_dialogs_policy_handler.h", "themes/theme_color_policy_handler.cc", @@ -4622,19 +4630,6 @@ sources += [ "task_manager/sampling/shared_sampler_stub.cc" ] } - if (!is_ios) { - sources += [ - "net/disk_cache_dir_policy_handler.cc", - "net/disk_cache_dir_policy_handler.h", - "policy/browsing_history_policy_handler.cc", - "policy/browsing_history_policy_handler.h", - "policy/developer_tools_policy_handler.cc", - "policy/developer_tools_policy_handler.h", - "profiles/guest_mode_policy_handler.cc", - "profiles/guest_mode_policy_handler.h", - ] - } - if (is_chrome_branded) { deps += [ "//chrome/browser/lens/region_search" ] } @@ -5297,8 +5292,6 @@ "enterprise/reporting/cloud_profile_reporting_service_factory.cc", "enterprise/reporting/cloud_profile_reporting_service_factory.h", "fullscreen.h", - "policy/browser_signin_policy_handler.cc", - "policy/browser_signin_policy_handler.h", "policy/cloud/user_policy_signin_service_factory.cc", "policy/cloud/user_policy_signin_service_factory.h", "policy/cloud/user_policy_signin_service_util.cc", @@ -6524,6 +6517,13 @@ ] } + if (!is_chromeos) { + sources += [ + "policy/browser_signin_policy_handler.cc", + "policy/browser_signin_policy_handler.h", + ] + } + if (is_posix && !is_mac) { # TODO(crbug.com/1226159): Complete crash reporting integration on Fuchsia. sources += [
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index ba3bd65..9f70c8b 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3538,9 +3538,6 @@ flag_descriptions::kUseHDRTransferFunctionName, flag_descriptions::kUseHDRTransferFunctionDescription, kOsCrOS, FEATURE_VALUE_TYPE(display::features::kUseHDRTransferFunction)}, - {"vertical-snap", flag_descriptions::kVerticalSnapName, - flag_descriptions::kVerticalSnapDescription, kOsCrOS, - FEATURE_VALUE_TYPE(chromeos::wm::features::kVerticalSnap)}, {"adaptive-charging", flag_descriptions::kAdaptiveChargingName, flag_descriptions::kAdaptiveChargingDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kAdaptiveCharging)}, @@ -6988,6 +6985,9 @@ kOsCrOS, FEATURE_VALUE_TYPE( chromeos::features::kReleaseNotesNotificationAllChannels)}, + {"release-track-ui", flag_descriptions::kReleaseTrackUiName, + flag_descriptions::kReleaseTrackUiDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kReleaseTrackUi)}, {"use-stork-smds-server-address", flag_descriptions::kUseStorkSmdsServerAddressName, flag_descriptions::kUseStorkSmdsServerAddressDescription, kOsCrOS, @@ -7321,6 +7321,10 @@ {"compact-bubble-launcher", flag_descriptions::kCompactBubbleLauncherName, flag_descriptions::kCompactBubbleLauncherDescription, kOsCrOS, FEATURE_VALUE_TYPE(app_list_features::kCompactBubbleLauncher)}, + {"shelf-auto-hide-separation", + flag_descriptions::kShelfAutoHideSeparationName, + flag_descriptions::kShelfAutoHideSeparationDescription, kOsCrOS, + FEATURE_VALUE_TYPE(ash::features::kShelfAutoHideSeparation)}, {"shelf-drag-to-pin", flag_descriptions::kShelfDragToPinName, flag_descriptions::kShelfDragToPinDescription, kOsCrOS, FEATURE_VALUE_TYPE(ash::features::kDragUnpinnedAppToPin)},
diff --git a/chrome/browser/apps/app_service/app_service_proxy_base.cc b/chrome/browser/apps/app_service/app_service_proxy_base.cc index e7c15601..c4eeb08b 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_base.cc +++ b/chrome/browser/apps/app_service/app_service_proxy_base.cc
@@ -68,7 +68,7 @@ } absl::optional<IconKey> icon_key; - host_->app_registry_cache_.ForApp( + host_->app_registry_cache_.ForOneApp( app_id, [&icon_key](const AppUpdate& update) { icon_key = update.IconKey(); }); return icon_key; @@ -364,6 +364,51 @@ void AppServiceProxyBase::LaunchAppWithIntent( const std::string& app_id, int32_t event_flags, + IntentPtr intent, + LaunchSource launch_source, + WindowInfoPtr window_info, + base::OnceCallback<void(bool)> callback) { + CHECK(intent); + app_registry_cache_.ForOneApp( + app_id, + [this, event_flags, &intent, launch_source, &window_info, + callback = std::move(callback)](const AppUpdate& update) mutable { + auto* publisher = GetPublisher(update.AppType()); + if (!publisher) { + if (callback) { + std::move(callback).Run(/*success=*/false); + } + return; + } + + if (MaybeShowLaunchPreventionDialog(update)) { + if (callback) { + std::move(callback).Run(/*success=*/false); + } + return; + } + + // TODO(crbug/1117655): File manager records metrics for apps it + // launched. So we only record launches from other places. We should + // eventually move those metrics here, after AppService supports all + // app types launched by file manager. + if (launch_source != LaunchSource::kFromFileManager) { + RecordAppLaunch(update.AppId(), launch_source); + } + RecordAppPlatformMetrics(profile_, update, launch_source, + LaunchContainer::kLaunchContainerNone); + + publisher->LaunchAppWithIntent( + update.AppId(), event_flags, std::move(intent), launch_source, + std::move(window_info), std::move(callback)); + + PerformPostLaunchTasks(launch_source); + }); +} + +void AppServiceProxyBase::LaunchAppWithIntent( + const std::string& app_id, + int32_t event_flags, apps::mojom::IntentPtr intent, apps::mojom::LaunchSource mojom_launch_source, apps::mojom::WindowInfoPtr window_info,
diff --git a/chrome/browser/apps/app_service/app_service_proxy_base.h b/chrome/browser/apps/app_service/app_service_proxy_base.h index 05c87a5..e9e62fe 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_base.h +++ b/chrome/browser/apps/app_service/app_service_proxy_base.h
@@ -162,6 +162,14 @@ // app (e.g. a middle click indicating opening a background tab). // |launch_source| is the possible app launch sources. |window_info| is the // window information to launch an app, e.g. display_id, window bounds. + void LaunchAppWithIntent(const std::string& app_id, + int32_t event_flags, + IntentPtr intent, + LaunchSource launch_source, + WindowInfoPtr window_info = nullptr, + base::OnceCallback<void(bool)> callback = {}); + // TODO(crbug.com/1253250): Will be removed soon. Please use the non mojom + // interface. void LaunchAppWithIntent( const std::string& app_id, int32_t event_flags,
diff --git a/chrome/browser/apps/app_service/app_service_proxy_lacros.cc b/chrome/browser/apps/app_service/app_service_proxy_lacros.cc index db26cde8..aa759c3 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_lacros.cc +++ b/chrome/browser/apps/app_service/app_service_proxy_lacros.cc
@@ -172,6 +172,34 @@ remote_crosapi_app_service_proxy_->Launch(std::move(params)); } +void AppServiceProxyLacros::LaunchAppWithIntent(const std::string& app_id, + int32_t event_flags, + IntentPtr intent, + LaunchSource launch_source, + WindowInfoPtr window_info) { + CHECK(intent); + + if (!remote_crosapi_app_service_proxy_) { + return; + } + + if (crosapi_app_service_proxy_version_ < + int{crosapi::mojom::AppServiceProxy::MethodMinVersions:: + kLaunchMinVersion}) { + LOG(WARNING) << "Ash AppServiceProxy version " + << crosapi_app_service_proxy_version_ + << " does not support Launch()."; + return; + } + + auto params = CreateCrosapiLaunchParamsWithEventFlags( + this, app_id, event_flags, launch_source, + window_info ? window_info->display_id : display::kInvalidDisplayId); + params->intent = + apps_util::ConvertAppServiceToCrosapiIntent(intent, profile_); + remote_crosapi_app_service_proxy_->Launch(std::move(params)); +} + void AppServiceProxyLacros::LaunchAppWithIntent( const std::string& app_id, int32_t event_flags, @@ -448,7 +476,7 @@ } absl::optional<IconKey> icon_key; - host_->app_registry_cache_.ForApp( + host_->app_registry_cache_.ForOneApp( app_id, [&icon_key](const AppUpdate& update) { icon_key = update.IconKey(); }); return icon_key;
diff --git a/chrome/browser/apps/app_service/app_service_proxy_lacros.h b/chrome/browser/apps/app_service/app_service_proxy_lacros.h index dfb0c18e..9029cb3 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_lacros.h +++ b/chrome/browser/apps/app_service/app_service_proxy_lacros.h
@@ -19,6 +19,7 @@ #include "chromeos/crosapi/mojom/app_service.mojom.h" #include "components/keyed_service/core/keyed_service.h" #include "components/services/app_service/public/cpp/app_capability_access_cache.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/icon_cache.h" @@ -139,6 +140,13 @@ // window information to launch an app, e.g. display_id, window bounds. void LaunchAppWithIntent(const std::string& app_id, int32_t event_flags, + IntentPtr intent, + LaunchSource launch_source, + WindowInfoPtr window_info = nullptr); + // TODO(crbug.com/1253250): Will be removed soon. Please use the non mojom + // interface. + void LaunchAppWithIntent(const std::string& app_id, + int32_t event_flags, apps::mojom::IntentPtr intent, apps::mojom::LaunchSource launch_source, apps::mojom::WindowInfoPtr window_info = nullptr);
diff --git a/chrome/browser/apps/app_service/metrics/app_service_metrics.cc b/chrome/browser/apps/app_service/metrics/app_service_metrics.cc index f7fe5fd..abbffab 100644 --- a/chrome/browser/apps/app_service/metrics/app_service_metrics.cc +++ b/chrome/browser/apps/app_service/metrics/app_service_metrics.cc
@@ -210,10 +210,6 @@ RecordDefaultAppLaunch(DefaultAppName::kCalculatorChromeApp, launch_source); } else if (app_id == extension_misc::kTextEditorAppId) { RecordDefaultAppLaunch(DefaultAppName::kText, launch_source); -#if BUILDFLAG(IS_CHROMEOS_ASH) - } else if (app_id == file_manager::kAudioPlayerAppId) { - RecordDefaultAppLaunch(DefaultAppName::kAudioPlayer, launch_source); -#endif // BUILDFLAG(IS_CHROMEOS_ASH) } else if (app_id == web_app::kCalculatorAppId) { RecordDefaultAppLaunch(DefaultAppName::kCalculator, launch_source); } else if (app_id == web_app::kCanvasAppId) {
diff --git a/chrome/browser/apps/app_service/notifications_browsertest.cc b/chrome/browser/apps/app_service/notifications_browsertest.cc index 271e11e..f35c2acf 100644 --- a/chrome/browser/apps/app_service/notifications_browsertest.cc +++ b/chrome/browser/apps/app_service/notifications_browsertest.cc
@@ -94,27 +94,13 @@ } absl::optional<bool> HasBadge(Profile* profile, const std::string& app_id) { - absl::optional<bool> mojom_has_badge; auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); - proxy->FlushMojoCallsForTesting(); - proxy->AppRegistryCache().ForOneApp( - app_id, [&mojom_has_badge](const apps::AppUpdate& update) { - mojom_has_badge = update.HasBadge(); - }); - absl::optional<bool> has_badge; - proxy->AppRegistryCache().ForApp(app_id, - [&has_badge](const apps::AppUpdate& update) { - has_badge = update.HasBadge(); - }); - - if (has_badge.has_value() && has_badge == mojom_has_badge) { - if (has_badge.value()) - return true; - if (!has_badge.value()) - return false; - } - return absl::nullopt; + proxy->AppRegistryCache().ForOneApp( + app_id, [&has_badge](const apps::AppUpdate& update) { + has_badge = update.HasBadge(); + }); + return has_badge; } void RemoveNotification(Profile* profile, const std::string& notification_id) {
diff --git a/chrome/browser/apps/app_service/publishers/arc_apps_unittest.cc b/chrome/browser/apps/app_service/publishers/arc_apps_unittest.cc index 3f629008..5b7d6f6 100644 --- a/chrome/browser/apps/app_service/publishers/arc_apps_unittest.cc +++ b/chrome/browser/apps/app_service/publishers/arc_apps_unittest.cc
@@ -168,7 +168,7 @@ apps::IntentFilters target; apps::AppServiceProxyFactory::GetForProfile(profile()) ->AppRegistryCache() - .ForApp(app_id, [&target](const apps::AppUpdate& update) { + .ForOneApp(app_id, [&target](const apps::AppUpdate& update) { target = update.IntentFilters(); });
diff --git a/chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc b/chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc index acd39843..48e4c3e5 100644 --- a/chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc +++ b/chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc
@@ -790,12 +790,11 @@ App& app) { ExtensionAppsBase::SetShowInFields(extension, app); - // Explicitly mark AudioPlayer and QuickOffice as being able to handle - // intents even though they are otherwise hidden from the user. Otherwise, - // extensions are only published if they have file_browser_handlers, which - // means they need to handle intents. - if (extension->id() == file_manager::kAudioPlayerAppId || - extension_misc::IsQuickOfficeExtension(extension->id()) || + // Explicitly mark QuickOffice as being able to handle intents even though it + // is otherwise hidden from the user. Otherwise, extensions are only published + // if they have file_browser_handlers, which means they need to handle + // intents. + if (extension_misc::IsQuickOfficeExtension(extension->id()) || extension->is_extension()) { app.handles_intents = true; } @@ -806,10 +805,9 @@ const extensions::Extension* extension) { ExtensionAppsBase::SetShowInFields(app, extension); - // Explicitly mark these apps as being able to handle intents even though they - // are otherwise hidden from the user. - if (extension->id() == file_manager::kAudioPlayerAppId || - extension_misc::IsQuickOfficeExtension(extension->id())) { + // Explicitly mark QuickOffice as being able to handle intents even though it + // is otherwise hidden from the user. + if (extension_misc::IsQuickOfficeExtension(extension->id())) { app->handles_intents = apps::mojom::OptionalBool::kTrue; }
diff --git a/chrome/browser/apps/app_service/publishers/publisher_unittest.cc b/chrome/browser/apps/app_service/publishers/publisher_unittest.cc index 53225aa..9416216 100644 --- a/chrome/browser/apps/app_service/publishers/publisher_unittest.cc +++ b/chrome/browser/apps/app_service/publishers/publisher_unittest.cc
@@ -389,7 +389,7 @@ apps::IntentFilters target; apps::AppServiceProxyFactory::GetForProfile(profile()) ->AppRegistryCache() - .ForApp(app_id, [&target](const apps::AppUpdate& update) { + .ForOneApp(app_id, [&target](const apps::AppUpdate& update) { target = update.IntentFilters(); });
diff --git a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc index f9df3fd8..c1f5ece 100644 --- a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc +++ b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc
@@ -51,7 +51,6 @@ #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/user_manager/user_names.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -567,23 +566,13 @@ app->readiness = apps::Readiness::kReady; app->paused = true; - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app)); - apps::AppServiceProxyFactory::GetForProfile( - AccessibilityManager::Get()->profile()) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kBuiltIn, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(app)); - apps::AppServiceProxyFactory::GetForProfile( - AccessibilityManager::Get()->profile()) - ->AppRegistryCache() - .OnApps(std::move(mojom_apps), apps::mojom::AppType::kBuiltIn, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app)); + apps::AppServiceProxyFactory::GetForProfile( + AccessibilityManager::Get()->profile()) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kBuiltIn, + false /* should_notify_initialized */); // Create and add a test app to the shelf model. ShelfItem item; @@ -627,23 +616,13 @@ apps::AppPtr app = std::make_unique<apps::App>(apps::AppType::kBuiltIn, app_id); app->readiness = apps::Readiness::kDisabledByPolicy; - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app)); - apps::AppServiceProxyFactory::GetForProfile( - AccessibilityManager::Get()->profile()) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kBuiltIn, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(app)); - apps::AppServiceProxyFactory::GetForProfile( - AccessibilityManager::Get()->profile()) - ->AppRegistryCache() - .OnApps(std::move(mojom_apps), apps::mojom::AppType::kBuiltIn, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app)); + apps::AppServiceProxyFactory::GetForProfile( + AccessibilityManager::Get()->profile()) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kBuiltIn, + false /* should_notify_initialized */); // Create and add a test app to the shelf model. ShelfItem item;
diff --git a/chrome/browser/ash/app_restore/arc_app_launch_handler.cc b/chrome/browser/ash/app_restore/arc_app_launch_handler.cc index 4f8711c..e3258a8 100644 --- a/chrome/browser/ash/app_restore/arc_app_launch_handler.cc +++ b/chrome/browser/ash/app_restore/arc_app_launch_handler.cc
@@ -638,11 +638,18 @@ } if (data_it->second->intent) { - proxy->LaunchAppWithIntent( - app_id, data_it->second->event_flag.value(), - apps::ConvertIntentToMojomIntent(data_it->second->intent), - apps::mojom::LaunchSource::kFromFullRestore, - ConvertWindowInfoToMojomWindowInfo(window_info)); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + proxy->LaunchAppWithIntent(app_id, data_it->second->event_flag.value(), + data_it->second->intent->Clone(), + apps::LaunchSource::kFromFullRestore, + std::move(window_info)); + } else { + proxy->LaunchAppWithIntent( + app_id, data_it->second->event_flag.value(), + apps::ConvertIntentToMojomIntent(data_it->second->intent), + apps::mojom::LaunchSource::kFromFullRestore, + ConvertWindowInfoToMojomWindowInfo(window_info)); + } } else { if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { proxy->Launch(app_id, data_it->second->event_flag.value(),
diff --git a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc index 0560167..17f4144 100644 --- a/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc +++ b/chrome/browser/ash/app_restore/full_restore_app_launch_handler_browsertest.cc
@@ -68,7 +68,6 @@ #include "components/prefs/pref_registry_simple.h" #include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/strings/grit/components_strings.h" #include "content/public/test/browser_test.h" @@ -2307,19 +2306,10 @@ app->readiness = readiness; auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile()); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> deltas; - deltas.push_back(std::move(app)); - proxy->AppRegistryCache().OnApps(std::move(deltas), apps::AppType::kArc, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kArc, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> deltas; + deltas.push_back(std::move(app)); + proxy->AppRegistryCache().OnApps(std::move(deltas), apps::AppType::kArc, + false /* should_notify_initialized */); } void RemoveApp(const std::string& app_id) { @@ -2327,19 +2317,10 @@ app->readiness = apps::Readiness::kUninstalledByUser; auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile()); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> deltas; - deltas.push_back(std::move(app)); - proxy->AppRegistryCache().OnApps(std::move(deltas), apps::AppType::kArc, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kArc, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> deltas; + deltas.push_back(std::move(app)); + proxy->AppRegistryCache().OnApps(std::move(deltas), apps::AppType::kArc, + false /* should_notify_initialized */); } bool HasRestoreData() { @@ -2813,19 +2794,10 @@ app_type, *GetManager().GetAppIdForSystemApp(ash::SystemWebAppType::HELP)); app->readiness = readiness; - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> deltas; - deltas.push_back(std::move(app)); - cache.OnApps(std::move(deltas), app_type, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - cache.OnApps(std::move(mojom_deltas), - apps::ConvertAppTypeToMojomAppType(app_type), - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> deltas; + deltas.push_back(std::move(app)); + cache.OnApps(std::move(deltas), app_type, + false /* should_notify_initialized */); } void SetShouldRestore(FullRestoreAppLaunchHandler* app_launch_handler) {
diff --git a/chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc b/chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc index 1f91de2..aa98f91f 100644 --- a/chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc +++ b/chrome/browser/ash/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc
@@ -21,7 +21,6 @@ #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/session_manager/fake_session_manager_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/user_manager/scoped_user_manager.h" #include "content/public/test/browser_task_environment.h" @@ -35,9 +34,6 @@ public: ArcBootPhaseMonitorBridgeTest() : scoped_user_manager_(std::make_unique<ash::FakeChromeUserManager>()) { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); ash::SessionManagerClient::InitializeFakeInMemory(); @@ -73,7 +69,6 @@ arc_service_manager_.reset(); ash::SessionManagerClient::Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } protected:
diff --git a/chrome/browser/ash/arc/instance_throttle/arc_boot_phase_throttle_observer_unittest.cc b/chrome/browser/ash/arc/instance_throttle/arc_boot_phase_throttle_observer_unittest.cc index bbad3b6..85f91479 100644 --- a/chrome/browser/ash/arc/instance_throttle/arc_boot_phase_throttle_observer_unittest.cc +++ b/chrome/browser/ash/arc/instance_throttle/arc_boot_phase_throttle_observer_unittest.cc
@@ -24,7 +24,6 @@ #include "chrome/browser/ash/login/users/fake_chrome_user_manager.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/arc/test/fake_intent_helper_host.h" #include "components/arc/test/fake_intent_helper_instance.h" #include "components/sync_preferences/testing_pref_service_syncable.h" @@ -39,9 +38,6 @@ public: ArcBootPhaseThrottleObserverTest() : scoped_user_manager_(std::make_unique<ash::FakeChromeUserManager>()) { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); arc_session_manager_ = CreateTestArcSessionManager(std::make_unique<ArcSessionRunner>( @@ -83,7 +79,6 @@ testing_profile_.reset(); arc_session_manager_.reset(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } protected:
diff --git a/chrome/browser/ash/arc/instance_throttle/arc_instance_throttle_unittest.cc b/chrome/browser/ash/arc/instance_throttle/arc_instance_throttle_unittest.cc index b8d331f..ff3534a 100644 --- a/chrome/browser/ash/arc/instance_throttle/arc_instance_throttle_unittest.cc +++ b/chrome/browser/ash/arc/instance_throttle/arc_instance_throttle_unittest.cc
@@ -32,7 +32,6 @@ #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/concierge/fake_concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "components/arc/test/fake_intent_helper_host.h" #include "components/arc/test/fake_intent_helper_instance.h" @@ -53,9 +52,6 @@ void SetUp() override { chromeos::PowerManagerClient::InitializeFake(); - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); arc_service_manager_ = std::make_unique<ArcServiceManager>(); arc_session_manager_ = @@ -100,7 +96,6 @@ arc_session_manager_.reset(); arc_service_manager_.reset(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); chromeos::PowerManagerClient::Shutdown(); } @@ -385,9 +380,6 @@ run_loop_ = std::make_unique<base::RunLoop>(); - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); chromeos::ConciergeClient::InitializeFake(); DCHECK(GetConciergeClient()); @@ -408,7 +400,6 @@ testing_profile_.reset(); arc_session_manager_.reset(); arc_service_manager_.reset(); - chromeos::DBusThreadManager::Shutdown(); } protected:
diff --git a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc index c940cb2..5bec8c0 100644 --- a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc +++ b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/ash/arc/test/test_arc_session_manager.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -44,9 +43,6 @@ void SetUp() override { chromeos::PowerManagerClient::InitializeFake(); - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); service_manager_ = std::make_unique<ArcServiceManager>(); session_manager_ = @@ -66,7 +62,6 @@ testing_profile_.reset(); session_manager_.reset(); service_manager_.reset(); - chromeos::DBusThreadManager::Shutdown(); chromeos::PowerManagerClient::Shutdown(); }
diff --git a/chrome/browser/ash/arc/notification/arc_provision_notification_service_unittest.cc b/chrome/browser/ash/arc/notification/arc_provision_notification_service_unittest.cc index bc1947c..609f4e82 100644 --- a/chrome/browser/ash/arc/notification/arc_provision_notification_service_unittest.cc +++ b/chrome/browser/ash/arc/notification/arc_provision_notification_service_unittest.cc
@@ -27,7 +27,6 @@ #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "components/sync_preferences/testing_pref_service_syncable.h" @@ -56,9 +55,6 @@ } void SetUpInternal(bool should_create_session_manager) { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); SetArcAvailableCommandLineForTesting( @@ -107,7 +103,6 @@ arc_service_manager_.reset(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } ash::FakeChromeUserManager* GetFakeUserManager() {
diff --git a/chrome/browser/ash/arc/session/arc_disk_space_monitor_unittest.cc b/chrome/browser/ash/arc/session/arc_disk_space_monitor_unittest.cc index 659db128..c07a3b9 100644 --- a/chrome/browser/ash/arc/session/arc_disk_space_monitor_unittest.cc +++ b/chrome/browser/ash/arc/session/arc_disk_space_monitor_unittest.cc
@@ -14,7 +14,6 @@ #include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/spaced/fake_spaced_client.h" #include "chromeos/ash/components/dbus/spaced/spaced_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/user_manager.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -31,10 +30,6 @@ ArcDiskSpaceMonitorTest& operator=(const ArcDiskSpaceMonitorTest&) = delete; void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); - // Initialize fake clients. ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); ash::SpacedClient::InitializeFake(); @@ -79,7 +74,6 @@ testing_profile_.reset(); ash::SpacedClient::Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } ArcSessionManager* arc_session_manager() const {
diff --git a/chrome/browser/ash/arc/session/arc_play_store_enabled_preference_handler_unittest.cc b/chrome/browser/ash/arc/session/arc_play_store_enabled_preference_handler_unittest.cc index 89bd3d47..f8487596 100644 --- a/chrome/browser/ash/arc/session/arc_play_store_enabled_preference_handler_unittest.cc +++ b/chrome/browser/ash/arc/session/arc_play_store_enabled_preference_handler_unittest.cc
@@ -31,7 +31,6 @@ #include "chromeos/ash/components/dbus/concierge/concierge_client.h" #include "chromeos/ash/components/dbus/session_manager/session_manager_client.h" #include "chromeos/ash/components/dbus/upstart/upstart_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/consent_auditor/fake_consent_auditor.h" #include "components/signin/public/base/consent_level.h" #include "components/signin/public/identity_manager/identity_manager.h" @@ -64,9 +63,6 @@ const ArcPlayStoreEnabledPreferenceHandlerTest&) = delete; void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); ash::SessionManagerClient::InitializeFakeInMemory(); ash::UpstartClient::InitializeFake(); @@ -115,7 +111,6 @@ ash::UpstartClient::Shutdown(); ash::SessionManagerClient::Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } TestingProfile* profile() const { return profile_.get(); }
diff --git a/chrome/browser/ash/arc/session/arc_session_manager.cc b/chrome/browser/ash/arc/session/arc_session_manager.cc index 132f78a4..d2c5724d 100644 --- a/chrome/browser/ash/arc/session/arc_session_manager.cc +++ b/chrome/browser/ash/arc/session/arc_session_manager.cc
@@ -647,7 +647,7 @@ prefs->GetBoolean(prefs::kArcProvisioningInitiatedFromOobe))) { playstore_launcher_ = std::make_unique<ArcAppLauncher>( profile_, kPlayStoreAppId, - apps_util::CreateIntentForActivity( + apps_util::MakeIntentForActivity( kPlayStoreActivity, kInitialStartParam, kCategoryLauncher), false /* deferred_launch_allowed */, display::kInvalidDisplayId, apps::LaunchSource::kFromChromeInternal);
diff --git a/chrome/browser/ash/arc/session/arc_session_manager_unittest.cc b/chrome/browser/ash/arc/session/arc_session_manager_unittest.cc index 350fb42..286d3ee 100644 --- a/chrome/browser/ash/arc/session/arc_session_manager_unittest.cc +++ b/chrome/browser/ash/arc/session/arc_session_manager_unittest.cc
@@ -57,7 +57,6 @@ #include "chromeos/ash/components/dbus/session_manager/session_manager_client.h" #include "chromeos/ash/components/dbus/upstart/upstart_client.h" #include "chromeos/ash/components/dbus/userdataauth/fake_cryptohome_misc_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "components/account_id/account_id.h" #include "components/policy/proto/chrome_device_policy.pb.h" @@ -158,9 +157,6 @@ public: ArcSessionManagerInLoginScreenTest() : user_manager_enabler_(std::make_unique<ash::FakeChromeUserManager>()) { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); ash::SessionManagerClient::InitializeFakeInMemory(); @@ -184,7 +180,6 @@ arc_service_manager_.reset(); ash::SessionManagerClient::Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } protected: @@ -274,7 +269,6 @@ ~ArcSessionManagerTestBase() override = default; void SetUp() override { - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); chromeos::PowerManagerClient::InitializeFake(); ash::SessionManagerClient::InitializeFakeInMemory(); @@ -310,7 +304,6 @@ ash::SessionManagerClient::Shutdown(); chromeos::PowerManagerClient::Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } ash::FakeChromeUserManager* GetFakeUserManager() const {
diff --git a/chrome/browser/ash/child_accounts/family_user_app_metrics_unittest.cc b/chrome/browser/ash/child_accounts/family_user_app_metrics_unittest.cc index a984017..7f010ee4 100644 --- a/chrome/browser/ash/child_accounts/family_user_app_metrics_unittest.cc +++ b/chrome/browser/ash/child_accounts/family_user_app_metrics_unittest.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/instance.h" #include "components/services/app_service/public/cpp/instance_registry.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -190,18 +189,8 @@ deltas.push_back(MakeApp(/*app_id=*/"s", /*app_name=*/"systemweb", /*last_launch_time=*/base::Time::Now(), apps::AppType::kSystemWeb)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - cache.OnApps(std::move(deltas), apps::AppType::kUnknown, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - for (const auto& delta : deltas) { - mojom_deltas.push_back(apps::ConvertAppToMojomApp(delta)); - } - cache.OnApps(std::move(mojom_deltas), apps::mojom::AppType::kUnknown, - false /* should_notify_initialized */); - } + cache.OnApps(std::move(deltas), apps::AppType::kUnknown, + false /* should_notify_initialized */); apps::InstanceRegistry& instance_registry = apps::AppServiceProxyFactory::GetForProfile(profile())
diff --git a/chrome/browser/ash/crosapi/BUILD.gn b/chrome/browser/ash/crosapi/BUILD.gn index 584926f..1b704ed 100644 --- a/chrome/browser/ash/crosapi/BUILD.gn +++ b/chrome/browser/ash/crosapi/BUILD.gn
@@ -223,6 +223,8 @@ "printing_metrics_ash.cc", "printing_metrics_ash.h", ] + } else { + sources += [ "fake_printing_metrics_ash.h" ] } deps = [
diff --git a/chrome/browser/ash/crosapi/browser_manager.cc b/chrome/browser/ash/crosapi/browser_manager.cc index 486b04d..b813c84 100644 --- a/chrome/browser/ash/crosapi/browser_manager.cc +++ b/chrome/browser/ash/crosapi/browser_manager.cc
@@ -996,11 +996,6 @@ SetState(State::CREATING_LOG_FILE); - // TODO(ythjkt): After M92 cherry-pick, clean up the following code by moving - // the data wipe check logic from `BrowserDataMigrator` to browser_util. - const std::string user_id_hash = ash::ProfileHelper::GetUserIdHashFromProfile( - ProfileManager::GetPrimaryUserProfile()); - base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce(&DoLacrosBackgroundWorkPreLaunch, lacros_path_,
diff --git a/chrome/browser/ash/crosapi/browser_manager.h b/chrome/browser/ash/crosapi/browser_manager.h index f907ab7..a649167 100644 --- a/chrome/browser/ash/crosapi/browser_manager.h +++ b/chrome/browser/ash/crosapi/browser_manager.h
@@ -52,6 +52,10 @@ class ApkWebAppService; } +namespace extensions { +class AutotestPrivateGetLacrosInfoFunction; +} + namespace policy { class CloudPolicyCore; } @@ -294,6 +298,8 @@ }; protected: + // NOTE: You may have to update tests if you make changes to State, as state_ + // is exposed via autotest_private. enum class State { // Lacros is not initialized yet. // Lacros-chrome loading depends on user type, so it needs to wait @@ -350,6 +356,8 @@ // installation when lacros-chrome starts at arbitrary points of time, so it // needs to be kept alive. friend class ash::ApkWebAppService; + // Only for exposing state_ to Tast tests. + friend class extensions::AutotestPrivateGetLacrosInfoFunction; // Holds the data for restoring a window from the desk template. // The request to restore a window may come when the browser service is not @@ -538,6 +546,7 @@ // Creates windows from template data. void RestoreWindowsFromTemplate(); + // NOTE: The state is exposed to tests via autotest_private. State state_ = State::NOT_INITIALIZED; std::unique_ptr<crosapi::BrowserLoader> browser_loader_;
diff --git a/chrome/browser/ash/crosapi/crosapi_ash.cc b/chrome/browser/ash/crosapi/crosapi_ash.cc index 9fec393..adc6a9e2 100644 --- a/chrome/browser/ash/crosapi/crosapi_ash.cc +++ b/chrome/browser/ash/crosapi/crosapi_ash.cc
@@ -133,6 +133,8 @@ #if defined(USE_CUPS) #include "chrome/browser/ash/crosapi/printing_metrics_ash.h" +#else +#include "chrome/browser/ash/crosapi/fake_printing_metrics_ash.h" #endif // defined(USE_CUPS) namespace crosapi {
diff --git a/chrome/browser/ash/crosapi/crosapi_ash.h b/chrome/browser/ash/crosapi/crosapi_ash.h index 26995ea9..35a99573 100644 --- a/chrome/browser/ash/crosapi/crosapi_ash.h +++ b/chrome/browser/ash/crosapi/crosapi_ash.h
@@ -340,11 +340,9 @@ return chrome_app_kiosk_service_ash_.get(); } -#if defined(USE_CUPS) PrintingMetricsAsh* printing_metrics_ash() { return printing_metrics_ash_.get(); } -#endif // defined(USE_CUPS) SearchProviderAsh* search_provider_ash() { return search_provider_ash_.get(); @@ -470,9 +468,7 @@ std::unique_ptr<PolicyServiceAsh> policy_service_ash_; std::unique_ptr<PowerAsh> power_ash_; std::unique_ptr<PrefsAsh> prefs_ash_; -#if defined(USE_CUPS) std::unique_ptr<PrintingMetricsAsh> printing_metrics_ash_; -#endif // defined(USE_CUPS) std::unique_ptr<RemotingAsh> remoting_ash_; std::unique_ptr<ResourceManagerAsh> resource_manager_ash_; std::unique_ptr<ScreenManagerAsh> screen_manager_ash_;
diff --git a/chrome/browser/ash/crosapi/fake_printing_metrics_ash.h b/chrome/browser/ash/crosapi/fake_printing_metrics_ash.h new file mode 100644 index 0000000..3fbf6b59 --- /dev/null +++ b/chrome/browser/ash/crosapi/fake_printing_metrics_ash.h
@@ -0,0 +1,25 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ASH_CROSAPI_FAKE_PRINTING_METRICS_ASH_H_ +#define CHROME_BROWSER_ASH_CROSAPI_FAKE_PRINTING_METRICS_ASH_H_ + +#include "printing/buildflags/buildflags.h" + +#if defined(USE_CUPS) +#error Fake PrintingMetricsAsh cannot be used with the USE_CUPS flag. +#endif + +namespace crosapi { + +// This class is a dummy counterpart for the real +// PrintingMetricsAsh declared in printing_metrics_ash.h to make +// std::unique_ptr<PrintingMetricsAsh> member in CrosapiAsh +// destructible even when USE_CUPS flag is not defined and the +// header printing_metrics_ash.h is not included. +class PrintingMetricsAsh {}; + +} // namespace crosapi + +#endif // CHROME_BROWSER_ASH_CROSAPI_FAKE_PRINTING_METRICS_ASH_H_
diff --git a/chrome/browser/ash/crosapi/printing_metrics_ash.h b/chrome/browser/ash/crosapi/printing_metrics_ash.h index 7a73b2e5..12c1ac8 100644 --- a/chrome/browser/ash/crosapi/printing_metrics_ash.h +++ b/chrome/browser/ash/crosapi/printing_metrics_ash.h
@@ -14,9 +14,13 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/unique_receiver_set.h" +#include "printing/buildflags/buildflags.h" + +#if !defined(USE_CUPS) +#error PrintingMetricsAsh must be used with the USE_CUPS flag. +#endif namespace crosapi { - // Ash implementation of crosapi::mojom::PrintingMetricsForProfile. // This class communicates with ash::PrintJobHistory service for the given // profile -- queries print jobs and listens to finished events.
diff --git a/chrome/browser/ash/eche_app/eche_app_manager_factory.cc b/chrome/browser/ash/eche_app/eche_app_manager_factory.cc index 539dd54d..76d38da7 100644 --- a/chrome/browser/ash/eche_app/eche_app_manager_factory.cc +++ b/chrome/browser/ash/eche_app/eche_app_manager_factory.cc
@@ -297,6 +297,7 @@ .SetDeviceName(device_name) .SetBoardName(board_name) .SetGaiaId(gaia_id) + .SetDeviceType(base::UTF16ToUTF8(device_type)) .Build(); }
diff --git a/chrome/browser/ash/file_manager/app_id.h b/chrome/browser/ash/file_manager/app_id.h index ec7f887d..8ca965c 100644 --- a/chrome/browser/ash/file_manager/app_id.h +++ b/chrome/browser/ash/file_manager/app_id.h
@@ -16,9 +16,6 @@ // The app ID generated by the System Web App framework. const char kFileManagerSwaAppId[] = "fkiggjmkendpmbegkagpmagjepfkpmeb"; -// The audio player's app ID. -const char kAudioPlayerAppId[] = "cjbfomnbifhcdnihkgipgfcihmgjfhbf"; - // The text editor's app ID. const char kTextEditorAppId[] = "mmfbcljfglbokpmkimbfghdkjmjhdgbg";
diff --git a/chrome/browser/ash/file_manager/app_service_file_tasks.cc b/chrome/browser/ash/file_manager/app_service_file_tasks.cc index 63418f4..2be99588 100644 --- a/chrome/browser/ash/file_manager/app_service_file_tasks.cc +++ b/chrome/browser/ash/file_manager/app_service_file_tasks.cc
@@ -32,7 +32,9 @@ #include "chrome/browser/web_applications/web_app_id_constants.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/extensions/api/file_manager_private.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" +#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/services/app_service/public/mojom/types.mojom-shared.h" @@ -244,17 +246,15 @@ } } - constexpr auto launch_source = apps::mojom::LaunchSource::kFromFileManager; - std::vector<GURL> file_urls; - std::vector<apps::mojom::IntentFilePtr> intent_files; + std::vector<apps::IntentFilePtr> intent_files; file_urls.reserve(file_system_urls.size()); intent_files.reserve(file_system_urls.size()); for (size_t i = 0; i < file_system_urls.size(); i++) { file_urls.push_back(file_system_urls[i].ToGURL()); - auto file = apps::mojom::IntentFile::New(); - file->url = file_system_urls[i].ToGURL(); + auto file = + std::make_unique<apps::IntentFile>(file_system_urls[i].ToGURL()); file->mime_type = mime_types.at(i); intent_files.push_back(std::move(file)); } @@ -267,33 +267,61 @@ DCHECK(task.task_type == TASK_TYPE_WEB_APP || task.task_type == TASK_TYPE_FILE_HANDLER); } - apps::mojom::IntentPtr intent = - apps_util::CreateViewIntentFromFiles(std::move(intent_files)); - + apps::IntentPtr intent = std::make_unique<apps::Intent>( + apps_util::kIntentActionView, std::move(intent_files)); intent->activity_name = task.action_id; - apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( - task.app_id, ui::EF_NONE, std::move(intent), launch_source, - apps::MakeWindowInfo(display::kDefaultDisplayId), - base::BindOnce( - [](FileTaskFinishedCallback done, TaskType task_type, bool success) { - if (!success) { - std::move(done).Run( - extensions::api::file_manager_private::TASK_RESULT_FAILED, - ""); - } else if (task_type == TASK_TYPE_WEB_APP) { - // TODO(benwells): return the correct code here, depending on how - // the app will be opened in multiprofile. - std::move(done).Run( - extensions::api::file_manager_private::TASK_RESULT_OPENED, - ""); - } else { - std::move(done).Run(extensions::api::file_manager_private:: - TASK_RESULT_MESSAGE_SENT, - ""); - } - }, - std::move(done), task.task_type)); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + task.app_id, ui::EF_NONE, std::move(intent), + apps::LaunchSource::kFromFileManager, + std::make_unique<apps::WindowInfo>(display::kDefaultDisplayId), + base::BindOnce( + [](FileTaskFinishedCallback done, TaskType task_type, + bool success) { + if (!success) { + std::move(done).Run( + extensions::api::file_manager_private::TASK_RESULT_FAILED, + ""); + } else if (task_type == TASK_TYPE_WEB_APP) { + // TODO(benwells): return the correct code here, depending on + // how the app will be opened in multiprofile. + std::move(done).Run( + extensions::api::file_manager_private::TASK_RESULT_OPENED, + ""); + } else { + std::move(done).Run(extensions::api::file_manager_private:: + TASK_RESULT_MESSAGE_SENT, + ""); + } + }, + std::move(done), task.task_type)); + } else { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + task.app_id, ui::EF_NONE, apps::ConvertIntentToMojomIntent(intent), + apps::mojom::LaunchSource::kFromFileManager, + apps::MakeWindowInfo(display::kDefaultDisplayId), + base::BindOnce( + [](FileTaskFinishedCallback done, TaskType task_type, + bool success) { + if (!success) { + std::move(done).Run( + extensions::api::file_manager_private::TASK_RESULT_FAILED, + ""); + } else if (task_type == TASK_TYPE_WEB_APP) { + // TODO(benwells): return the correct code here, depending on + // how the app will be opened in multiprofile. + std::move(done).Run( + extensions::api::file_manager_private::TASK_RESULT_OPENED, + ""); + } else { + std::move(done).Run(extensions::api::file_manager_private:: + TASK_RESULT_MESSAGE_SENT, + ""); + } + }, + std::move(done), task.task_type)); + } } } // namespace file_tasks
diff --git a/chrome/browser/ash/file_manager/app_service_file_tasks_unittest.cc b/chrome/browser/ash/file_manager/app_service_file_tasks_unittest.cc index 8697bdd..08efb58 100644 --- a/chrome/browser/ash/file_manager/app_service_file_tasks_unittest.cc +++ b/chrome/browser/ash/file_manager/app_service_file_tasks_unittest.cc
@@ -19,7 +19,6 @@ #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/test/base/testing_profile.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/intent_filter.h" #include "components/services/app_service/public/cpp/intent_test_util.h" #include "components/services/app_service/public/cpp/intent_util.h" @@ -121,18 +120,8 @@ app->readiness = apps::Readiness::kReady; app->intent_filters = std::move(intent_filters); apps.push_back(std::move(app)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - app_service_proxy_->AppRegistryCache().OnApps( - std::move(apps), app_type, false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(apps[0])); - app_service_proxy_->AppRegistryCache().OnApps( - std::move(mojom_apps), apps::ConvertAppTypeToMojomAppType(app_type), - /*should_notify_initialized=*/false); - app_service_test_.WaitForAppService(); - } + app_service_proxy_->AppRegistryCache().OnApps( + std::move(apps), app_type, false /* should_notify_initialized */); } void AddFakeWebApp(const std::string& app_id,
diff --git a/chrome/browser/ash/file_manager/file_manager_string_util.cc b/chrome/browser/ash/file_manager/file_manager_string_util.cc index 545af78..5740b06 100644 --- a/chrome/browser/ash/file_manager/file_manager_string_util.cc +++ b/chrome/browser/ash/file_manager/file_manager_string_util.cc
@@ -241,22 +241,6 @@ IDS_MEDIA_PLAYER_VOLUME_SLIDER_LABEL); } -void AddStringsForAudioPlayer(base::Value::Dict* dict) { - SET_STRING("AUDIO_ERROR", IDS_FILE_BROWSER_AUDIO_ERROR); - SET_STRING("AUDIO_OFFLINE", IDS_FILE_BROWSER_AUDIO_OFFLINE); - SET_STRING("AUDIO_PLAYER_DEFAULT_ARTIST", - IDS_FILE_BROWSER_AUDIO_PLAYER_DEFAULT_ARTIST); - SET_STRING("AUDIO_PLAYER_TITLE", IDS_FILE_BROWSER_AUDIO_PLAYER_TITLE); - SET_STRING("AUDIO_PLAYER_SHUFFLE_BUTTON_LABEL", - IDS_AUDIO_PLAYER_SHUFFLE_BUTTON_LABEL); - SET_STRING("AUDIO_PLAYER_REPEAT_BUTTON_LABEL", - IDS_AUDIO_PLAYER_REPEAT_BUTTON_LABEL); - SET_STRING("AUDIO_PLAYER_OPEN_PLAY_LIST_BUTTON_LABEL", - IDS_AUDIO_PLAYER_OPEN_PLAY_LIST_BUTTON_LABEL); - SET_STRING("AUDIO_PLAYER_ARTWORK_EXPAND_BUTTON_LABEL", - IDS_AUDIO_PLAYER_ARTWORK_EXPAND_BUTTON_LABEL); -} - void AddStringsForCloudImport(base::Value::Dict* dict) { SET_STRING("CLOUD_IMPORT_TITLE", IDS_FILE_BROWSER_CLOUD_IMPORT_TITLE); SET_STRING("CLOUD_IMPORT_DESTINATION_FOLDER", @@ -950,7 +934,6 @@ AddStringsForMediaView(&dict); AddStringsForFileTypes(&dict); AddStringsForMediaPlayer(&dict); - AddStringsForAudioPlayer(&dict); AddStringsForCloudImport(&dict); AddStringsForCrUiMenuItemShortcuts(&dict); AddStringsForFileErrors(&dict);
diff --git a/chrome/browser/ash/file_manager/file_tasks.cc b/chrome/browser/ash/file_manager/file_tasks.cc index 9e11565aa..223f66b 100644 --- a/chrome/browser/ash/file_manager/file_tasks.cc +++ b/chrome/browser/ash/file_manager/file_tasks.cc
@@ -267,7 +267,6 @@ kFileManagerAppId, kFileManagerSwaAppId, kTextEditorAppId, - kAudioPlayerAppId, extension_misc::kQuickOfficeComponentExtensionId, extension_misc::kQuickOfficeInternalExtensionId, extension_misc::kQuickOfficeExtensionId};
diff --git a/chrome/browser/ash/input_method/input_method_engine.cc b/chrome/browser/ash/input_method/input_method_engine.cc index bf4abc2..65f5b1f9 100644 --- a/chrome/browser/ash/input_method/input_method_engine.cc +++ b/chrome/browser/ash/input_method/input_method_engine.cc
@@ -10,6 +10,7 @@ #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "base/check.h" +#include "base/i18n/char_iterator.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" @@ -55,6 +56,15 @@ return 0 <= i && i <= std::numeric_limits<uint32_t>::max(); } +int GetUtf16Size(std::u16string& text) { + int utf16_size = 0; + for (base::i18n::UTF16CharIterator char_iterator(text); !char_iterator.end(); + char_iterator.Advance()) { + ++utf16_size; + } + return utf16_size; +} + } // namespace InputMethodEngine::Candidate::Candidate() = default; @@ -252,6 +262,7 @@ *error = kErrorNotActive; return false; } + if (context_id != context_id_ || context_id_ == -1) { *error = base::StringPrintf( "%s request context id = %d, current context id = %d", @@ -259,8 +270,25 @@ return false; } + if (selection_start < 0 || selection_end < 0 || cursor < 0) { + *error = base::StringPrintf( + "%s request selection start = %d, selection end = %d, cursor = %d", + "At least 1 arg is negative, which is invalid.", selection_start, + selection_end, cursor); + return false; + } + ui::CompositionText composition_text; composition_text.text = base::UTF8ToUTF16(text); + // Check the length of the text. + uint32_t utf16_length = GetUtf16Size(composition_text.text); + if (selection_start > utf16_length || selection_end > utf16_length) { + *error = base::StringPrintf( + "%s request selection start = %d, selection end = %d, cursor = %d", + "At least 1 length is above the length of the text, which is invalid.", + selection_start, selection_end, cursor); + return false; + } composition_text.selection.set_start(selection_start); composition_text.selection.set_end(selection_end);
diff --git a/chrome/browser/ash/input_method/input_method_engine.h b/chrome/browser/ash/input_method/input_method_engine.h index 06e555e..76157b5 100644 --- a/chrome/browser/ash/input_method/input_method_engine.h +++ b/chrome/browser/ash/input_method/input_method_engine.h
@@ -157,6 +157,10 @@ std::string* error); // Set the current composition and associated properties. + // Note: The cursor is used to index into a UTF16 version + // of the input text. Ideally, we should check the + // UTF16 version of the input text and make sure the + // selection start and end falls within that range. bool SetComposition(int context_id, const char* text, int selection_start,
diff --git a/chrome/browser/ash/input_method/input_method_engine_unittest.cc b/chrome/browser/ash/input_method/input_method_engine_unittest.cc index 09e3b87..7c36be10 100644 --- a/chrome/browser/ash/input_method/input_method_engine_unittest.cc +++ b/chrome/browser/ash/input_method/input_method_engine_unittest.cc
@@ -320,6 +320,35 @@ histograms.ExpectBucketCount("InputMethod.CommitLength", 3, 1); } +TEST_F(InputMethodEngineTest, TestInvalidCompositionReturnsFalse) { + CreateEngine(true); + std::string error; + FocusIn(ui::TEXT_INPUT_TYPE_TEXT); + engine_->Enable(kTestImeComponentId); + std::vector<InputMethodEngine::SegmentInfo> segments; + int context = engine_->GetContextIdForTesting(); + EXPECT_EQ(engine_->SetComposition(context, "test", 0, 0, 0, segments, &error), + true); + EXPECT_EQ( + engine_->SetComposition(context, "test", -1, 0, 0, segments, &error), + false); + EXPECT_EQ( + engine_->SetComposition(context, "test", 0, -1, 0, segments, &error), + false); + EXPECT_EQ( + engine_->SetComposition(context, "test", 0, 0, -1, segments, &error), + false); + // Still return false if multiple values set as negative + EXPECT_EQ( + engine_->SetComposition(context, "test", -12, 0, -1, segments, &error), + false); + EXPECT_EQ( + engine_->SetComposition(context, "test", -1, -1, -1, segments, &error), + false); + EXPECT_EQ(engine_->SetComposition(context, "test", 0, 6, 0, segments, &error), + false); +} + TEST_F(InputMethodEngineTest, TestCompositionBoundsChanged) { CreateEngine(true); // Enable/disable with focus. @@ -329,8 +358,8 @@ TEST_F(InputMethodEngineTest, TestSetSelectionRange) { CreateEngine(true); - const int context = engine_->GetContextIdForTesting(); std::string error; + int context = engine_->GetContextIdForTesting(); engine_->InputMethodEngine::SetSelectionRange(context, /* start */ 0, /* end */ 0, &error); EXPECT_EQ(kErrorNotActive, error); @@ -338,7 +367,9 @@ mock_ime_input_context_handler_->set_selection_range_call_count()); error = ""; + FocusIn(ui::TEXT_INPUT_TYPE_TEXT); engine_->Enable(kTestImeComponentId); + context = engine_->GetContextIdForTesting(); engine_->InputMethodEngine::SetSelectionRange(context, /* start */ 0, /* end */ 0, &error); EXPECT_EQ("", error);
diff --git a/chrome/browser/ash/input_method/ui/candidate_window_view.cc b/chrome/browser/ash/input_method/ui/candidate_window_view.cc index e1dc568..b462a9c 100644 --- a/chrome/browser/ash/input_method/ui/candidate_window_view.cc +++ b/chrome/browser/ash/input_method/ui/candidate_window_view.cc
@@ -277,7 +277,7 @@ // If the new layout is vertical, the aux text should appear at the // bottom. If horizontal, it should appear between preedit and candidates. if (new_candidate_window.orientation() == ui::CandidateWindow::VERTICAL) { - ReorderChildView(auxiliary_text_, -1); + ReorderChildView(auxiliary_text_, children().size()); auxiliary_text_->SetAlignment(gfx::ALIGN_RIGHT); auxiliary_text_->SetBorderFromPosition(InformationTextArea::TOP); candidate_area_->SetLayoutManager(std::make_unique<views::BoxLayout>(
diff --git a/chrome/browser/ash/lock_screen_apps/app_manager_impl_unittest.cc b/chrome/browser/ash/lock_screen_apps/app_manager_impl_unittest.cc index e20797a..da2d006 100644 --- a/chrome/browser/ash/lock_screen_apps/app_manager_impl_unittest.cc +++ b/chrome/browser/ash/lock_screen_apps/app_manager_impl_unittest.cc
@@ -37,7 +37,6 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/scoped_user_manager.h" #include "content/public/test/browser_task_environment.h" #include "extensions/browser/disable_reason.h" @@ -152,9 +151,6 @@ ~LockScreenAppManagerImplTest() override = default; void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); // Initialize command line so `ash::NoteTakingHelper` thinks note taking @@ -196,7 +192,6 @@ extensions::ExtensionSystem::Get(profile())->Shutdown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } void InitExtensionSystem(Profile* profile) {
diff --git a/chrome/browser/ash/lock_screen_apps/lock_screen_profile_creator_impl_unittest.cc b/chrome/browser/ash/lock_screen_apps/lock_screen_profile_creator_impl_unittest.cc index 9355412..8ab12546 100644 --- a/chrome/browser/ash/lock_screen_apps/lock_screen_profile_creator_impl_unittest.cc +++ b/chrome/browser/ash/lock_screen_apps/lock_screen_profile_creator_impl_unittest.cc
@@ -36,7 +36,6 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/crx_file/id_util.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/core/common/safe_browsing_prefs.h" @@ -225,9 +224,6 @@ ~LockScreenProfileCreatorImplTest() override {} void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( @@ -263,7 +259,6 @@ TestingBrowserProcess::GetGlobal()->SetProfileManager(nullptr); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } UnittestProfileManager* profile_manager() { return profile_manager_; }
diff --git a/chrome/browser/ash/lock_screen_apps/state_controller_unittest.cc b/chrome/browser/ash/lock_screen_apps/state_controller_unittest.cc index 4084a86d..e8757f6 100644 --- a/chrome/browser/ash/lock_screen_apps/state_controller_unittest.cc +++ b/chrome/browser/ash/lock_screen_apps/state_controller_unittest.cc
@@ -41,7 +41,6 @@ #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/fake_power_manager_client.h" #include "chromeos/dbus/power_manager/suspend.pb.h" #include "components/user_manager/scoped_user_manager.h" @@ -394,9 +393,6 @@ ~LockScreenAppStateTest() override = default; void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); command_line_ = std::make_unique<base::test::ScopedCommandLine>(); @@ -462,7 +458,6 @@ BrowserWithTestWindowTest::TearDown(); command_line_.reset(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } TestingProfile* CreateProfile() override {
diff --git a/chrome/browser/ash/login/demo_mode/demo_resources.cc b/chrome/browser/ash/login/demo_mode/demo_resources.cc index 0c3abd9..4de7cce 100644 --- a/chrome/browser/ash/login/demo_mode/demo_resources.cc +++ b/chrome/browser/ash/login/demo_mode/demo_resources.cc
@@ -93,13 +93,6 @@ // CrOSComponentManager. DCHECK(cros_component_manager); - if (ash::features::IsDemoModeSWAEnabled()) { - // Skip the load of Chrome Apps when SWA enabled and mark them as loaded. - InstalledComponentLoaded( - component_updater::CrOSComponentManager::Error::NONE, base::FilePath()); - return; - } - cros_component_manager->Load( kDemoModeResourcesComponentName, component_updater::CrOSComponentManager::MountPolicy::kMount,
diff --git a/chrome/browser/ash/note_taking_helper.cc b/chrome/browser/ash/note_taking_helper.cc index 33a9ff4..8fd390ba 100644 --- a/chrome/browser/ash/note_taking_helper.cc +++ b/chrome/browser/ash/note_taking_helper.cc
@@ -54,6 +54,7 @@ #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" #include "components/services/app_service/public/cpp/features.h" +#include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_filter.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/services/app_service/public/cpp/types_util.h" @@ -214,10 +215,16 @@ // Apps in 'kDefaultAllowedAppIds' might not have a note-taking intent filter. // They can just launch without the intent. if (has_note_taking_intent_filter) { - apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( - app_id, ui::EF_NONE, - ConvertIntentToMojomIntent(apps_util::CreateCreateNoteIntent()), - apps::mojom::LaunchSource::kFromShelf); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + app_id, ui::EF_NONE, apps_util::CreateCreateNoteIntent(), + apps::LaunchSource::kFromShelf); + } else { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + app_id, ui::EF_NONE, + apps::ConvertIntentToMojomIntent(apps_util::CreateCreateNoteIntent()), + apps::mojom::LaunchSource::kFromShelf); + } } else { if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { apps::AppServiceProxyFactory::GetForProfile(profile)->Launch(
diff --git a/chrome/browser/ash/policy/status_collector/app_info_generator_unittest.cc b/chrome/browser/ash/policy/status_collector/app_info_generator_unittest.cc index 63d4fb4..8ef3e57 100644 --- a/chrome/browser/ash/policy/status_collector/app_info_generator_unittest.cc +++ b/chrome/browser/ash/policy/status_collector/app_info_generator_unittest.cc
@@ -28,7 +28,6 @@ #include "chrome/test/base/testing_profile.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/session_manager/core/session_manager.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/user_manager/scoped_user_manager.h" @@ -143,19 +142,10 @@ protected: void PushApp(apps::AppPtr app) { apps::AppType app_type = app->app_type; - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> deltas; - deltas.push_back(std::move(app)); - GetCache().OnApps(std::move(deltas), app_type, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - GetCache().OnApps(std::move(mojom_deltas), - apps::ConvertAppTypeToMojomAppType(app_type), - /*should_notify_initialized=*/true); - } + std::vector<apps::AppPtr> deltas; + deltas.push_back(std::move(app)); + GetCache().OnApps(std::move(deltas), app_type, + /*should_notify_initialized=*/false); } void PushApp(const std::string& app_id,
diff --git a/chrome/browser/ash/policy/status_collector/device_status_collector.cc b/chrome/browser/ash/policy/status_collector/device_status_collector.cc index bb985ec..50fe34e 100644 --- a/chrome/browser/ash/policy/status_collector/device_status_collector.cc +++ b/chrome/browser/ash/policy/status_collector/device_status_collector.cc
@@ -1235,71 +1235,6 @@ } } - // Process SystemResult. - const auto& system_result = probe_result->system_result; - if (!system_result.is_null()) { - switch (system_result->which()) { - case cros_healthd::SystemResult::Tag::kError: { - LOG(ERROR) << "cros_healthd: Error getting system info: " - << system_result->get_error()->msg; - break; - } - - case cros_healthd::SystemResult::Tag::kSystemInfo: { - const auto& system_info = system_result->get_system_info(); - em::SystemStatus* const system_status_out = - response_params_.device_status->mutable_system_status(); - if (report_vpd_info) { - if (system_info->first_power_date.has_value()) { - system_status_out->set_first_power_date( - system_info->first_power_date.value()); - SetDeviceStatusReported(); - } - if (system_info->manufacture_date.has_value()) { - system_status_out->set_manufacture_date( - system_info->manufacture_date.value()); - SetDeviceStatusReported(); - } - if (system_info->product_sku_number.has_value()) { - system_status_out->set_vpd_sku_number( - system_info->product_sku_number.value()); - SetDeviceStatusReported(); - } - if (system_info->product_serial_number.has_value()) { - system_status_out->set_vpd_serial_number( - system_info->product_serial_number.value()); - SetDeviceStatusReported(); - } - } - if (report_system_info) { - system_status_out->set_marketing_name(system_info->marketing_name); - if (system_info->bios_version.has_value()) { - system_status_out->set_bios_version( - system_info->bios_version.value()); - } - if (system_info->board_name.has_value()) { - system_status_out->set_board_name( - system_info->board_name.value()); - } - if (system_info->board_version.has_value()) { - system_status_out->set_board_version( - system_info->board_version.value()); - } - if (system_info->chassis_type) { - system_status_out->set_chassis_type( - system_info->chassis_type->value); - } - if (system_info->product_name.has_value()) { - system_status_out->set_product_name( - system_info->product_name.value()); - } - SetDeviceStatusReported(); - } - break; - } - } - } - // Process SystemResultV2. const auto& system_result_v2 = probe_result->system_result_v2; if (!system_result_v2.is_null()) { @@ -1316,6 +1251,69 @@ // info below. case cros_healthd::SystemResultV2::Tag::kSystemInfoV2: { const auto& system_info_v2 = system_result_v2->get_system_info_v2(); + + if (report_vpd_info || report_system_info) { + em::SystemStatus* const system_status_out = + response_params_.device_status->mutable_system_status(); + if (report_vpd_info && !system_info_v2->vpd_info.is_null()) { + const auto& vpd_info = system_info_v2->vpd_info; + if (vpd_info->activate_date.has_value()) { + system_status_out->set_first_power_date( + vpd_info->activate_date.value()); + SetDeviceStatusReported(); + } + if (vpd_info->mfg_date.has_value()) { + system_status_out->set_manufacture_date( + vpd_info->mfg_date.value()); + SetDeviceStatusReported(); + } + if (vpd_info->sku_number.has_value()) { + system_status_out->set_vpd_sku_number( + vpd_info->sku_number.value()); + SetDeviceStatusReported(); + } + if (vpd_info->serial_number.has_value()) { + system_status_out->set_vpd_serial_number( + vpd_info->serial_number.value()); + SetDeviceStatusReported(); + } + } + if (report_system_info) { + if (!system_info_v2->dmi_info.is_null()) { + const auto& dmi_info = system_info_v2->dmi_info; + if (dmi_info->bios_version.has_value()) { + system_status_out->set_bios_version( + dmi_info->bios_version.value()); + SetDeviceStatusReported(); + } + if (dmi_info->board_name.has_value()) { + system_status_out->set_board_name( + dmi_info->board_name.value()); + SetDeviceStatusReported(); + } + if (dmi_info->board_version.has_value()) { + system_status_out->set_board_version( + dmi_info->board_version.value()); + SetDeviceStatusReported(); + } + if (dmi_info->chassis_type) { + system_status_out->set_chassis_type( + dmi_info->chassis_type->value); + SetDeviceStatusReported(); + } + } + if (!system_info_v2->os_info.is_null()) { + const auto& os_info = system_info_v2->os_info; + if (os_info->marketing_name.has_value()) { + system_status_out->set_marketing_name( + os_info->marketing_name.value()); + } + system_status_out->set_product_name(os_info->code_name); + SetDeviceStatusReported(); + } + } + } + em::SmbiosInfo* const smbios_info_out = response_params_.device_status->mutable_smbios_info(); if (!system_info_v2->dmi_info.is_null()) { @@ -2684,12 +2682,9 @@ std::vector<ProbeCategoryEnum> probe_categories; - // Always probe System2 to get device vendor, product name, and product + // Always probe System to get device vendor, product name, and product // version - probe_categories.push_back(ProbeCategoryEnum::kSystem2); - - if (report_vpd_info_ || report_system_info_) - probe_categories.push_back(ProbeCategoryEnum::kSystem); + probe_categories.push_back(ProbeCategoryEnum::kSystem); if (report_timezone_info_) probe_categories.push_back(ProbeCategoryEnum::kTimezone); @@ -2953,8 +2948,8 @@ return report_power_status_ || report_storage_status_ || report_audio_status_ || report_board_status_ || report_memory_info_ || report_cpu_info_ || report_backlight_info_ || report_bluetooth_info_ || - report_fan_info_ || report_vpd_info_ || report_system_info_ || report_boot_mode_ || - report_version_info_; + report_fan_info_ || report_vpd_info_ || report_system_info_ || + report_boot_mode_ || report_version_info_; } bool DeviceStatusCollector::IsReportingUsers() const { // For more details, see comment in
diff --git a/chrome/browser/ash/policy/status_collector/device_status_collector_browsertest.cc b/chrome/browser/ash/policy/status_collector/device_status_collector_browsertest.cc index 28a9e7f..2ed73f8 100644 --- a/chrome/browser/ash/policy/status_collector/device_status_collector_browsertest.cc +++ b/chrome/browser/ash/policy/status_collector/device_status_collector_browsertest.cc
@@ -98,7 +98,6 @@ #include "components/prefs/testing_pref_service.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/session_manager/core/session_manager.h" #include "components/upload_list/upload_list.h" #include "components/user_manager/scoped_user_manager.h" @@ -160,41 +159,35 @@ constexpr char kFakeBatteryTechnology[] = "fake_battery_technology"; constexpr char kFakeBatteryStatus[] = "fake_battery_status"; // System test values: -const char kFakeFirstPowerDate[] = "2020-40"; -const char kFakeManufactureDate[] = "2019-01-01"; -const char kFakeSkuNumber[] = "ABCD&^A"; -const char kFakeSerialNumber[] = "8607G03EDF"; -constexpr char kFakeSystemModelName[] = "XX ModelName 007 XY"; -constexpr char kFakeMarketingName[] = "Latitude 1234 Chromebook Enterprise"; -constexpr char kFakeBiosVersion[] = "Google_BoardName.12200.68.0"; -constexpr char kFakeBoardName[] = "BoardName"; -constexpr char kFakeBoardVersion[] = "rev1234"; -constexpr uint64_t kFakeChassisType = 9; -constexpr char kFakeProductName[] = "ProductName"; -constexpr char kFakeVersionMilestone[] = "87"; -constexpr char kFakeVersionBuildNumber[] = "13544"; -constexpr char kFakeVersionPatchNumber[] = "59.0"; -constexpr char kFakeVersionReleaseChannel[] = "stable-channel"; -// System V2 test values: -constexpr char kFakeOsInfoCodeName[] = "OsInfo Code Name"; -constexpr char kFakeOSInfoMarketingName[] = "OsInfo Marketing Name"; -constexpr char kFakeOSInfoOemName[] = "OsInfo OEM Name"; -constexpr cros_healthd::BootMode kFakeOsInfoBootMode = - cros_healthd::BootMode::kCrosSecure; -constexpr em::BootInfo::BootMethod kFakeOsInfoBootMethod = - em::BootInfo::CROS_SECURE; -constexpr char kFakeVpdInfoRegion[] = "VpdInfo Region"; constexpr char kFakeDmiInfoBiosVendor[] = "DMI Bios Vendor"; -constexpr char kFakeDmiInfoBiosVersion[] = "DMI Bios Version"; +constexpr char kFakeDmiInfoBiosVersion[] = "Google_BoardName.12200.68.0"; constexpr char kFakeDmiInfoBoardName[] = "DMI Board Name"; constexpr char kFakeDmiInfoBoardVendor[] = "DMI Board Vendor"; -constexpr char kFakeDmiInfoBoardVersion[] = "DMI Board Version"; -constexpr char kFakeDmiInfoChassisVendor[] = "DMI Chassis Vendor"; +constexpr char kFakeDmiInfoBoardVersion[] = "rev1234"; constexpr uint64_t kFakeDmiInfoChassisType = 9; +constexpr char kFakeDmiInfoChassisVendor[] = "DMI Chassis Vendor"; constexpr char kFakeDmiInfoProductFamily[] = "DMI Product Family"; -constexpr char kFakeDmiInfoSysVendor[] = "DMI System Vendor"; constexpr char kFakeDmiInfoProductName[] = "DMI Product Name"; constexpr char kFakeDmiInfoProductVersion[] = "DMI Product Version"; +constexpr char kFakeDmiInfoSysVendor[] = "DMI System Vendor"; +constexpr em::BootInfo::BootMethod kFakeOsInfoBootMethod = + em::BootInfo::CROS_SECURE; +constexpr cros_healthd::BootMode kFakeOsInfoBootMode = + cros_healthd::BootMode::kCrosSecure; +constexpr char kFakeOsInfoMarketingName[] = + "Latitude 1234 Chromebook Enterprise"; +constexpr char kFakeOsInfoOemName[] = "OsInfo OEM Name"; +constexpr char kFakeOsInfoProductName[] = "OsInfo Code Name"; +constexpr char kFakeOsVersionBuildNumber[] = "13544"; +constexpr char kFakeOsVersionMilestone[] = "87"; +constexpr char kFakeOsVersionPatchNumber[] = "59.0"; +constexpr char kFakeOsVersionReleaseChannel[] = "stable-channel"; +constexpr char kFakeVpdInfoFirstPowerDate[] = "2020-40"; +constexpr char kFakeVpdInfoManufactureDate[] = "2019-01-01"; +constexpr char kFakeVpdInfoRegion[] = "VpdInfo Region"; +constexpr char kFakeVpdInfoSerialNumber[] = "8607G03EDF"; +constexpr char kFakeVpdInfoSkuNumber[] = "ABCD&^A"; +constexpr char kFakeVpdInfoSystemModelName[] = "XX ModelName 007 XY"; // CPU test values: constexpr uint32_t kFakeNumTotalThreads = 8; constexpr char kFakeModelName[] = "fake_cpu_model_name"; @@ -570,30 +563,19 @@ std::move(storage_vector)); } -cros_healthd::SystemResultPtr CreateSystemResult() { - return cros_healthd::SystemResult::NewSystemInfo( - cros_healthd::SystemInfo::New( - kFakeFirstPowerDate, kFakeManufactureDate, kFakeSkuNumber, - kFakeSerialNumber, kFakeSystemModelName, kFakeMarketingName, - kFakeBiosVersion, kFakeBoardName, kFakeBoardVersion, - cros_healthd::NullableUint64::New(kFakeChassisType), kFakeProductName, - cros_healthd::OsVersion::New( - kFakeVersionMilestone, kFakeVersionBuildNumber, - kFakeVersionPatchNumber, kFakeVersionReleaseChannel))); -} - cros_healthd::SystemResultV2Ptr CreateSystemResultV2() { return cros_healthd::SystemResultV2::NewSystemInfoV2( cros_healthd::SystemInfoV2::New( cros_healthd::OsInfo::New( - kFakeOsInfoCodeName, kFakeOSInfoMarketingName, + kFakeOsInfoProductName, kFakeOsInfoMarketingName, cros_healthd::OsVersion::New( - kFakeVersionMilestone, kFakeVersionBuildNumber, - kFakeVersionPatchNumber, kFakeVersionReleaseChannel), - kFakeOsInfoBootMode, kFakeOSInfoOemName), - cros_healthd::VpdInfo::New(kFakeSerialNumber, kFakeVpdInfoRegion, - kFakeManufactureDate, kFakeFirstPowerDate, - kFakeSkuNumber, kFakeModelName), + kFakeOsVersionMilestone, kFakeOsVersionBuildNumber, + kFakeOsVersionPatchNumber, kFakeOsVersionReleaseChannel), + kFakeOsInfoBootMode, kFakeOsInfoOemName), + cros_healthd::VpdInfo::New( + kFakeVpdInfoSerialNumber, kFakeVpdInfoRegion, + kFakeVpdInfoManufactureDate, kFakeVpdInfoFirstPowerDate, + kFakeVpdInfoSkuNumber, kFakeVpdInfoSystemModelName), cros_healthd::DmiInfo::New( kFakeDmiInfoBiosVendor, kFakeDmiInfoBiosVersion, kFakeDmiInfoBoardName, kFakeDmiInfoBoardVendor, @@ -769,9 +751,6 @@ telemetry_info->battery_result = CreateBatteryResult(); if (SettingEnabled(ash::kReportDeviceStorageStatus)) telemetry_info->block_device_result = CreateBlockDeviceResult(); - if (SettingEnabled(ash::kReportDeviceSystemInfo) || - SettingEnabled(ash::kReportDeviceVpdInfo)) - telemetry_info->system_result = CreateSystemResult(); if (SettingEnabled(ash::kReportDeviceCpuInfo)) telemetry_info->cpu_result = CreateCpuResult(); if (SettingEnabled(ash::kReportDeviceTimezoneInfo)) @@ -3649,12 +3628,13 @@ // Verify the only vpd info is populated. ASSERT_TRUE(device_status_.has_system_status()); EXPECT_EQ(device_status_.system_status().first_power_date(), - kFakeFirstPowerDate); + kFakeVpdInfoFirstPowerDate); EXPECT_EQ(device_status_.system_status().manufacture_date(), - kFakeManufactureDate); - EXPECT_EQ(device_status_.system_status().vpd_sku_number(), kFakeSkuNumber); + kFakeVpdInfoManufactureDate); + EXPECT_EQ(device_status_.system_status().vpd_sku_number(), + kFakeVpdInfoSkuNumber); EXPECT_EQ(device_status_.system_status().vpd_serial_number(), - kFakeSerialNumber); + kFakeVpdInfoSerialNumber); ASSERT_FALSE(device_status_.system_status().has_marketing_name()); ASSERT_FALSE(device_status_.system_status().has_bios_version()); ASSERT_FALSE(device_status_.system_status().has_board_name()); @@ -3687,12 +3667,16 @@ ASSERT_FALSE(device_status_.system_status().has_manufacture_date()); ASSERT_FALSE(device_status_.system_status().has_vpd_sku_number()); EXPECT_EQ(device_status_.system_status().marketing_name(), - kFakeMarketingName); - EXPECT_EQ(device_status_.system_status().bios_version(), kFakeBiosVersion); - EXPECT_EQ(device_status_.system_status().board_name(), kFakeBoardName); - EXPECT_EQ(device_status_.system_status().board_version(), kFakeBoardVersion); - EXPECT_EQ(device_status_.system_status().chassis_type(), kFakeChassisType); - EXPECT_EQ(device_status_.system_status().product_name(), kFakeProductName); + kFakeOsInfoMarketingName); + EXPECT_EQ(device_status_.system_status().bios_version(), + kFakeDmiInfoBiosVersion); + EXPECT_EQ(device_status_.system_status().board_name(), kFakeDmiInfoBoardName); + EXPECT_EQ(device_status_.system_status().board_version(), + kFakeDmiInfoBoardVersion); + EXPECT_EQ(device_status_.system_status().chassis_type(), + kFakeDmiInfoChassisType); + EXPECT_EQ(device_status_.system_status().product_name(), + kFakeOsInfoProductName); // Verify system info V2 exists too. ASSERT_TRUE(device_status_.has_smbios_info()); @@ -3732,21 +3716,11 @@ apps::AppServiceProxyFactory::GetForProfile(testing_profile_.get()); auto app1 = std::make_unique<apps::App>(apps::AppType::kChromeApp, "id"); auto app2 = std::make_unique<apps::App>(apps::AppType::kChromeApp, "id2"); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app1)); - apps.push_back(std::move(app2)); - app_proxy->AppRegistryCache().OnApps(std::move(apps), - apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app1)); - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app2)); - app_proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app1)); + apps.push_back(std::move(app2)); + app_proxy->AppRegistryCache().OnApps(std::move(apps), apps::AppType::kUnknown, + /*should_notify_initialized=*/false); // Start app instance base::Time start_time;
diff --git a/chrome/browser/ash/policy/status_collector/legacy_device_status_collector.cc b/chrome/browser/ash/policy/status_collector/legacy_device_status_collector.cc index 84be8c34..cb147f42 100644 --- a/chrome/browser/ash/policy/status_collector/legacy_device_status_collector.cc +++ b/chrome/browser/ash/policy/status_collector/legacy_device_status_collector.cc
@@ -1232,71 +1232,6 @@ } } - // Process SystemResult. - const auto& system_result = probe_result->system_result; - if (!system_result.is_null()) { - switch (system_result->which()) { - case cros_healthd::SystemResult::Tag::kError: { - LOG(ERROR) << "cros_healthd: Error getting system info: " - << system_result->get_error()->msg; - break; - } - - case cros_healthd::SystemResult::Tag::kSystemInfo: { - const auto& system_info = system_result->get_system_info(); - em::SystemStatus* const system_status_out = - response_params_.device_status->mutable_system_status(); - if (report_vpd_info) { - if (system_info->first_power_date.has_value()) { - system_status_out->set_first_power_date( - system_info->first_power_date.value()); - SetDeviceStatusReported(); - } - if (system_info->manufacture_date.has_value()) { - system_status_out->set_manufacture_date( - system_info->manufacture_date.value()); - SetDeviceStatusReported(); - } - if (system_info->product_sku_number.has_value()) { - system_status_out->set_vpd_sku_number( - system_info->product_sku_number.value()); - SetDeviceStatusReported(); - } - if (system_info->product_serial_number.has_value()) { - system_status_out->set_vpd_serial_number( - system_info->product_serial_number.value()); - SetDeviceStatusReported(); - } - } - if (report_system_info) { - system_status_out->set_marketing_name(system_info->marketing_name); - if (system_info->bios_version.has_value()) { - system_status_out->set_bios_version( - system_info->bios_version.value()); - } - if (system_info->board_name.has_value()) { - system_status_out->set_board_name( - system_info->board_name.value()); - } - if (system_info->board_version.has_value()) { - system_status_out->set_board_version( - system_info->board_version.value()); - } - if (system_info->chassis_type) { - system_status_out->set_chassis_type( - system_info->chassis_type->value); - } - if (system_info->product_name.has_value()) { - system_status_out->set_product_name( - system_info->product_name.value()); - } - SetDeviceStatusReported(); - } - break; - } - } - } - // Process SystemResultV2. const auto& system_result_v2 = probe_result->system_result_v2; if (!system_result_v2.is_null()) { @@ -1309,6 +1244,66 @@ case cros_healthd::SystemResultV2::Tag::kSystemInfoV2: { const auto& system_info_v2 = system_result_v2->get_system_info_v2(); + + em::SystemStatus* const system_status_out = + response_params_.device_status->mutable_system_status(); + if (report_vpd_info && !system_info_v2->vpd_info.is_null()) { + const auto& vpd_info = system_info_v2->vpd_info; + if (vpd_info->activate_date.has_value()) { + system_status_out->set_first_power_date( + vpd_info->activate_date.value()); + SetDeviceStatusReported(); + } + if (vpd_info->mfg_date.has_value()) { + system_status_out->set_manufacture_date( + vpd_info->mfg_date.value()); + SetDeviceStatusReported(); + } + if (vpd_info->sku_number.has_value()) { + system_status_out->set_vpd_sku_number( + vpd_info->sku_number.value()); + SetDeviceStatusReported(); + } + if (vpd_info->serial_number.has_value()) { + system_status_out->set_vpd_serial_number( + vpd_info->serial_number.value()); + SetDeviceStatusReported(); + } + } + if (report_system_info) { + if (!system_info_v2->dmi_info.is_null()) { + const auto& dmi_info = system_info_v2->dmi_info; + if (dmi_info->bios_version.has_value()) { + system_status_out->set_bios_version( + dmi_info->bios_version.value()); + SetDeviceStatusReported(); + } + if (dmi_info->board_name.has_value()) { + system_status_out->set_board_name(dmi_info->board_name.value()); + SetDeviceStatusReported(); + } + if (dmi_info->board_version.has_value()) { + system_status_out->set_board_version( + dmi_info->board_version.value()); + SetDeviceStatusReported(); + } + if (dmi_info->chassis_type) { + system_status_out->set_chassis_type( + dmi_info->chassis_type->value); + SetDeviceStatusReported(); + } + } + if (!system_info_v2->os_info.is_null()) { + const auto& os_info = system_info_v2->os_info; + if (os_info->marketing_name.has_value()) { + system_status_out->set_marketing_name( + os_info->marketing_name.value()); + } + system_status_out->set_product_name(os_info->code_name); + SetDeviceStatusReported(); + } + } + em::SmbiosInfo* const smbios_info_out = response_params_.device_status->mutable_smbios_info(); em::BootInfo* const boot_info_out = @@ -2005,7 +2000,6 @@ case CrosHealthdCollectionMode::kFull: { if (report_vpd_info_ || report_system_info_) { categories_to_probe.push_back(ProbeCategoryEnum::kSystem); - categories_to_probe.push_back(ProbeCategoryEnum::kSystem2); } if (report_storage_status_) { categories_to_probe.push_back(
diff --git a/chrome/browser/ash/policy/status_collector/legacy_device_status_collector_browsertest.cc b/chrome/browser/ash/policy/status_collector/legacy_device_status_collector_browsertest.cc index 7da3561..82366ac 100644 --- a/chrome/browser/ash/policy/status_collector/legacy_device_status_collector_browsertest.cc +++ b/chrome/browser/ash/policy/status_collector/legacy_device_status_collector_browsertest.cc
@@ -94,7 +94,6 @@ #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_service.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/session_manager/core/session_manager.h" #include "components/upload_list/upload_list.h" #include "components/user_manager/scoped_user_manager.h" @@ -155,41 +154,35 @@ constexpr char kFakeBatteryTechnology[] = "fake_battery_technology"; constexpr char kFakeBatteryStatus[] = "fake_battery_status"; // System test values: -const char kFakeFirstPowerDate[] = "2020-40"; -const char kFakeManufactureDate[] = "2019-01-01"; -const char kFakeSkuNumber[] = "ABCD&^A"; -const char kFakeSerialNumber[] = "8607G03EDF"; -constexpr char kFakeSystemModelName[] = "XX ModelName 007 XY"; -constexpr char kFakeMarketingName[] = "Latitude 1234 Chromebook Enterprise"; -constexpr char kFakeBiosVersion[] = "Google_BoardName.12200.68.0"; -constexpr char kFakeBoardName[] = "BoardName"; -constexpr char kFakeBoardVersion[] = "rev1234"; -constexpr uint64_t kFakeChassisType = 9; -constexpr char kFakeProductName[] = "ProductName"; -constexpr char kFakeVersionMilestone[] = "87"; -constexpr char kFakeVersionBuildNumber[] = "13544"; -constexpr char kFakeVersionPatchNumber[] = "59.0"; -constexpr char kFakeVersionReleaseChannel[] = "stable-channel"; -// System V2 test values: -constexpr char kFakeOsInfoCodeName[] = "OsInfo Code Name"; -constexpr char kFakeOSInfoMarketingName[] = "OsInfo Marketing Name"; -constexpr char kFakeOSInfoOemName[] = "OsInfo OEM Name"; -constexpr cros_healthd::BootMode kFakeOsInfoBootMode = - cros_healthd::BootMode::kCrosSecure; -constexpr em::BootInfo::BootMethod kFakeOsInfoBootMethod = - em::BootInfo::CROS_SECURE; -constexpr char kFakeVpdInfoRegion[] = "VpdInfo Region"; constexpr char kFakeDmiInfoBiosVendor[] = "DMI Bios Vendor"; -constexpr char kFakeDmiInfoBiosVersion[] = "DMI Bios Version"; +constexpr char kFakeDmiInfoBiosVersion[] = "Google_BoardName.12200.68.0"; constexpr char kFakeDmiInfoBoardName[] = "DMI Board Name"; constexpr char kFakeDmiInfoBoardVendor[] = "DMI Board Vendor"; -constexpr char kFakeDmiInfoBoardVersion[] = "DMI Board Version"; -constexpr char kFakeDmiInfoChassisVendor[] = "DMI Chassis Vendor"; +constexpr char kFakeDmiInfoBoardVersion[] = "rev1234"; constexpr uint64_t kFakeDmiInfoChassisType = 9; +constexpr char kFakeDmiInfoChassisVendor[] = "DMI Chassis Vendor"; constexpr char kFakeDmiInfoProductFamily[] = "DMI Product Family"; -constexpr char kFakeDmiInfoSysVendor[] = "DMI System Vendor"; constexpr char kFakeDmiInfoProductName[] = "DMI Product Name"; constexpr char kFakeDmiInfoProductVersion[] = "DMI Product Version"; +constexpr char kFakeDmiInfoSysVendor[] = "DMI System Vendor"; +constexpr em::BootInfo::BootMethod kFakeOsInfoBootMethod = + em::BootInfo::CROS_SECURE; +constexpr cros_healthd::BootMode kFakeOsInfoBootMode = + cros_healthd::BootMode::kCrosSecure; +constexpr char kFakeOsInfoMarketingName[] = + "Latitude 1234 Chromebook Enterprise"; +constexpr char kFakeOsInfoOemName[] = "OsInfo OEM Name"; +constexpr char kFakeOsInfoProductName[] = "OsInfo Code Name"; +constexpr char kFakeOsVersionBuildNumber[] = "13544"; +constexpr char kFakeOsVersionMilestone[] = "87"; +constexpr char kFakeOsVersionPatchNumber[] = "59.0"; +constexpr char kFakeOsVersionReleaseChannel[] = "stable-channel"; +constexpr char kFakeVpdInfoFirstPowerDate[] = "2020-40"; +constexpr char kFakeVpdInfoManufactureDate[] = "2019-01-01"; +constexpr char kFakeVpdInfoRegion[] = "VpdInfo Region"; +constexpr char kFakeVpdInfoSerialNumber[] = "8607G03EDF"; +constexpr char kFakeVpdInfoSkuNumber[] = "ABCD&^A"; +constexpr char kFakeVpdInfoSystemModelName[] = "XX ModelName 007 XY"; // CPU test values: constexpr uint32_t kFakeNumTotalThreads = 8; constexpr char kFakeModelName[] = "fake_cpu_model_name"; @@ -551,30 +544,19 @@ std::move(storage_vector)); } -cros_healthd::SystemResultPtr CreateSystemResult() { - return cros_healthd::SystemResult::NewSystemInfo( - cros_healthd::SystemInfo::New( - kFakeFirstPowerDate, kFakeManufactureDate, kFakeSkuNumber, - kFakeSerialNumber, kFakeSystemModelName, kFakeMarketingName, - kFakeBiosVersion, kFakeBoardName, kFakeBoardVersion, - cros_healthd::NullableUint64::New(kFakeChassisType), kFakeProductName, - cros_healthd::OsVersion::New( - kFakeVersionMilestone, kFakeVersionBuildNumber, - kFakeVersionPatchNumber, kFakeVersionReleaseChannel))); -} - cros_healthd::SystemResultV2Ptr CreateSystemResultV2() { return cros_healthd::SystemResultV2::NewSystemInfoV2( cros_healthd::SystemInfoV2::New( cros_healthd::OsInfo::New( - kFakeOsInfoCodeName, kFakeOSInfoMarketingName, + kFakeOsInfoProductName, kFakeOsInfoMarketingName, cros_healthd::OsVersion::New( - kFakeVersionMilestone, kFakeVersionBuildNumber, - kFakeVersionPatchNumber, kFakeVersionReleaseChannel), - kFakeOsInfoBootMode, kFakeOSInfoOemName), - cros_healthd::VpdInfo::New(kFakeSerialNumber, kFakeVpdInfoRegion, - kFakeManufactureDate, kFakeFirstPowerDate, - kFakeSkuNumber, kFakeModelName), + kFakeOsVersionMilestone, kFakeOsVersionBuildNumber, + kFakeOsVersionPatchNumber, kFakeOsVersionReleaseChannel), + kFakeOsInfoBootMode, kFakeOsInfoOemName), + cros_healthd::VpdInfo::New( + kFakeVpdInfoSerialNumber, kFakeVpdInfoRegion, + kFakeVpdInfoManufactureDate, kFakeVpdInfoFirstPowerDate, + kFakeVpdInfoSkuNumber, kFakeVpdInfoSystemModelName), cros_healthd::DmiInfo::New( kFakeDmiInfoBiosVendor, kFakeDmiInfoBiosVersion, kFakeDmiInfoBoardName, kFakeDmiInfoBoardVendor, @@ -721,7 +703,6 @@ cros_healthd::TelemetryInfo fake_info; fake_info.battery_result = CreateBatteryResult(); fake_info.block_device_result = CreateBlockDeviceResult(); - fake_info.system_result = CreateSystemResult(); fake_info.system_result_v2 = CreateSystemResultV2(); fake_info.cpu_result = CreateCpuResult(); fake_info.timezone_result = CreateTimezoneResult(); @@ -3447,19 +3428,24 @@ // Verify the system info. ASSERT_TRUE(device_status_.has_system_status()); EXPECT_EQ(device_status_.system_status().first_power_date(), - kFakeFirstPowerDate); + kFakeVpdInfoFirstPowerDate); EXPECT_EQ(device_status_.system_status().manufacture_date(), - kFakeManufactureDate); - EXPECT_EQ(device_status_.system_status().vpd_sku_number(), kFakeSkuNumber); + kFakeVpdInfoManufactureDate); + EXPECT_EQ(device_status_.system_status().vpd_sku_number(), + kFakeVpdInfoSkuNumber); EXPECT_EQ(device_status_.system_status().vpd_serial_number(), - kFakeSerialNumber); + kFakeVpdInfoSerialNumber); EXPECT_EQ(device_status_.system_status().marketing_name(), - kFakeMarketingName); - EXPECT_EQ(device_status_.system_status().bios_version(), kFakeBiosVersion); - EXPECT_EQ(device_status_.system_status().board_name(), kFakeBoardName); - EXPECT_EQ(device_status_.system_status().board_version(), kFakeBoardVersion); - EXPECT_EQ(device_status_.system_status().chassis_type(), kFakeChassisType); - EXPECT_EQ(device_status_.system_status().product_name(), kFakeProductName); + kFakeOsInfoMarketingName); + EXPECT_EQ(device_status_.system_status().bios_version(), + kFakeDmiInfoBiosVersion); + EXPECT_EQ(device_status_.system_status().board_name(), kFakeDmiInfoBoardName); + EXPECT_EQ(device_status_.system_status().board_version(), + kFakeDmiInfoBoardVersion); + EXPECT_EQ(device_status_.system_status().chassis_type(), + kFakeDmiInfoChassisType); + EXPECT_EQ(device_status_.system_status().product_name(), + kFakeOsInfoProductName); // Verify the system v2 info. ASSERT_TRUE(device_status_.has_smbios_info()); @@ -3656,12 +3642,13 @@ // Verify the only vpd info is populated. ASSERT_TRUE(device_status_.has_system_status()); EXPECT_EQ(device_status_.system_status().first_power_date(), - kFakeFirstPowerDate); + kFakeVpdInfoFirstPowerDate); EXPECT_EQ(device_status_.system_status().manufacture_date(), - kFakeManufactureDate); - EXPECT_EQ(device_status_.system_status().vpd_sku_number(), kFakeSkuNumber); + kFakeVpdInfoManufactureDate); + EXPECT_EQ(device_status_.system_status().vpd_sku_number(), + kFakeVpdInfoSkuNumber); EXPECT_EQ(device_status_.system_status().vpd_serial_number(), - kFakeSerialNumber); + kFakeVpdInfoSerialNumber); ASSERT_FALSE(device_status_.system_status().has_marketing_name()); ASSERT_FALSE(device_status_.system_status().has_bios_version()); ASSERT_FALSE(device_status_.system_status().has_board_name()); @@ -3693,12 +3680,16 @@ ASSERT_FALSE(device_status_.system_status().has_manufacture_date()); ASSERT_FALSE(device_status_.system_status().has_vpd_sku_number()); EXPECT_EQ(device_status_.system_status().marketing_name(), - kFakeMarketingName); - EXPECT_EQ(device_status_.system_status().bios_version(), kFakeBiosVersion); - EXPECT_EQ(device_status_.system_status().board_name(), kFakeBoardName); - EXPECT_EQ(device_status_.system_status().board_version(), kFakeBoardVersion); - EXPECT_EQ(device_status_.system_status().chassis_type(), kFakeChassisType); - EXPECT_EQ(device_status_.system_status().product_name(), kFakeProductName); + kFakeOsInfoMarketingName); + EXPECT_EQ(device_status_.system_status().bios_version(), + kFakeDmiInfoBiosVersion); + EXPECT_EQ(device_status_.system_status().board_name(), kFakeDmiInfoBoardName); + EXPECT_EQ(device_status_.system_status().board_version(), + kFakeDmiInfoBoardVersion); + EXPECT_EQ(device_status_.system_status().chassis_type(), + kFakeDmiInfoChassisType); + EXPECT_EQ(device_status_.system_status().product_name(), + kFakeOsInfoProductName); // Verify system info V2 exists too. ASSERT_TRUE(device_status_.has_smbios_info()); @@ -3724,21 +3715,11 @@ apps::AppServiceProxyFactory::GetForProfile(testing_profile_.get()); auto app1 = std::make_unique<apps::App>(apps::AppType::kChromeApp, "id"); auto app2 = std::make_unique<apps::App>(apps::AppType::kChromeApp, "id2"); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app1)); - apps.push_back(std::move(app2)); - app_proxy->AppRegistryCache().OnApps(std::move(apps), - apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app1)); - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app2)); - app_proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app1)); + apps.push_back(std::move(app2)); + app_proxy->AppRegistryCache().OnApps(std::move(apps), apps::AppType::kUnknown, + /*should_notify_initialized=*/false); // Start app instance base::Time start_time;
diff --git a/chrome/browser/ash/web_applications/media_app/chrome_media_app_ui_delegate.cc b/chrome/browser/ash/web_applications/media_app/chrome_media_app_ui_delegate.cc index 96a2814..8f0a5984 100644 --- a/chrome/browser/ash/web_applications/media_app/chrome_media_app_ui_delegate.cc +++ b/chrome/browser/ash/web_applications/media_app/chrome_media_app_ui_delegate.cc
@@ -23,6 +23,9 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/channel_info.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" +#include "components/services/app_service/public/cpp/features.h" +#include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/version_info/channel.h" #include "content/public/browser/web_contents.h" @@ -152,21 +155,38 @@ proxy->profile(), url->path(), GURL(ash::kChromeUIMediaAppURL), &filesystem_url); - auto intent = apps_util::CreateEditIntentFromFile(filesystem_url, mime_type); + auto intent = apps_util::MakeEditIntent(filesystem_url, mime_type); intent->extras = { std::make_pair(kPhotosKeepOpenExtraName, kPhotosKeepOpenExtraValue)}; - proxy->LaunchAppWithIntent( - arc::kGooglePhotosAppId, ui::EF_NONE, std::move(intent), - apps::mojom::LaunchSource::kFromOtherApp, nullptr, - base::BindOnce( - [](base::OnceCallback<void()> callback, - base::WeakPtr<content::WebContents> web_contents, - bool launch_success) { - if (launch_success && web_contents) { - web_contents->Close(); - } - std::move(callback).Run(); - }, - std::move(edit_in_photos_callback), web_contents->GetWeakPtr())); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + proxy->LaunchAppWithIntent( + arc::kGooglePhotosAppId, ui::EF_NONE, std::move(intent), + apps::LaunchSource::kFromOtherApp, nullptr, + base::BindOnce( + [](base::OnceCallback<void()> callback, + base::WeakPtr<content::WebContents> web_contents, + bool launch_success) { + if (launch_success && web_contents) { + web_contents->Close(); + } + std::move(callback).Run(); + }, + std::move(edit_in_photos_callback), web_contents->GetWeakPtr())); + } else { + proxy->LaunchAppWithIntent( + arc::kGooglePhotosAppId, ui::EF_NONE, + apps::ConvertIntentToMojomIntent(intent), + apps::mojom::LaunchSource::kFromOtherApp, nullptr, + base::BindOnce( + [](base::OnceCallback<void()> callback, + base::WeakPtr<content::WebContents> web_contents, + bool launch_success) { + if (launch_success && web_contents) { + web_contents->Close(); + } + std::move(callback).Run(); + }, + std::move(edit_in_photos_callback), web_contents->GetWeakPtr())); + } }
diff --git a/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc b/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc index 4eb6d322..f10b08e 100644 --- a/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc +++ b/chrome/browser/ash/web_applications/media_app/media_app_integration_browsertest.cc
@@ -208,20 +208,11 @@ void InstallPhotosApp(Profile* profile) { auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> registry_deltas; - registry_deltas.push_back(MakePhotosApp()); - proxy->AppRegistryCache().OnApps(std::move(registry_deltas), - apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(MakePhotosApp())); - proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + std::vector<apps::AppPtr> registry_deltas; + registry_deltas.push_back(MakePhotosApp()); + proxy->AppRegistryCache().OnApps(std::move(registry_deltas), + apps::AppType::kUnknown, + /*should_notify_initialized=*/false); } bool GetFlagInApp(content::WebContents* web_ui, const char* flag) {
diff --git a/chrome/browser/autofill/form_structure_browsertest.cc b/chrome/browser/autofill/form_structure_browsertest.cc index 47e230f..36b47d3 100644 --- a/chrome/browser/autofill/form_structure_browsertest.cc +++ b/chrome/browser/autofill/form_structure_browsertest.cc
@@ -194,14 +194,12 @@ // TODO(crbug.com/1150895) Remove once launched. features::kAutofillParsingPatternProvider, features::kAutofillPageLanguageDetection, - // TODO(crbug.com/1165780): Remove once shared labels are launched. + // TODO(crbug/1165780): Remove once shared labels are launched. features::kAutofillEnableSupportForParsingWithSharedLabels, // TODO(crbug.com/1277480): Remove once launched. features::kAutofillEnableNameSurenameParsing, - // TODO(crbug.com/1190334): Remove once launched. - features::kAutofillParseMerchantPromoCodeFields, - // TODO(crbug.com/1335549): Remove once launched. - features::kAutofillParseIbanFields}, + // TODO(crbug/1190334): Remove once launched. + features::kAutofillParseMerchantPromoCodeFields}, // Disabled {}); }
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index ad50b4ce..7d305ff 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -229,6 +229,7 @@ "//chrome/browser/profiles:profile", "//chrome/browser/resource_coordinator:tab_metrics_event_proto", "//chrome/browser/resources/chromeos:app_icon_resources", + "//chrome/browser/resources/chromeos/cloud_upload:resources_grit", "//chrome/browser/resources/settings:resources_grit", "//chrome/browser/supervised_user/supervised_user_features", "//chrome/browser/ui/ash/system_web_apps",
diff --git a/chrome/browser/chromeos/arc/start_smart_selection_action_menu.cc b/chrome/browser/chromeos/arc/start_smart_selection_action_menu.cc index 29fcce1..fd8618f 100644 --- a/chrome/browser/chromeos/arc/start_smart_selection_action_menu.cc +++ b/chrome/browser/chromeos/arc/start_smart_selection_action_menu.cc
@@ -23,6 +23,9 @@ #include "chrome/grit/generated_resources.h" #include "components/arc/common/intent_helper/arc_intent_helper_package.h" #include "components/renderer_context_menu/render_view_context_menu_proxy.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" +#include "components/services/app_service/public/cpp/features.h" +#include "components/services/app_service/public/cpp/intent.h" #include "content/public/browser/context_menu_params.h" #include "ui/base/layout.h" #include "ui/base/models/image_model.h" @@ -40,18 +43,17 @@ namespace { -apps::mojom::IntentPtr CreateIntent( +apps::IntentPtr CreateIntent( arc::ArcIntentHelperMojoDelegate::IntentInfo arc_intent, arc::ArcIntentHelperMojoDelegate::ActivityName activity) { - auto intent = apps::mojom::Intent::New(); - intent->action = std::move(arc_intent.action); + auto intent = std::make_unique<apps::Intent>(arc_intent.action); intent->data = std::move(arc_intent.data); intent->mime_type = std::move(arc_intent.type); - intent->categories = std::move(arc_intent.categories); - intent->ui_bypassed = arc_intent.ui_bypassed - ? apps::mojom::OptionalBool::kTrue - : apps::mojom::OptionalBool::kFalse; - intent->extras = std::move(arc_intent.extras); + if (arc_intent.categories.has_value()) + intent->categories = std::move(arc_intent.categories.value()); + intent->ui_bypassed = arc_intent.ui_bypassed; + if (arc_intent.extras.has_value()) + intent->extras = std::move(arc_intent.extras.value()); intent->activity_name = std::move(activity.activity_name); @@ -161,12 +163,22 @@ return; } // The app that this intent points to is able to handle it, launch it. - apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( - actions_[index].app_id, ui::EF_NONE, - CreateIntent(std::move(actions_[index].action_intent), - std::move(actions_[index].activity)), - apps::mojom::LaunchSource::kFromSmartTextContextMenu, - apps::MakeWindowInfo(display.id())); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + actions_[index].app_id, ui::EF_NONE, + CreateIntent(std::move(actions_[index].action_intent), + std::move(actions_[index].activity)), + apps::LaunchSource::kFromSmartTextContextMenu, + std::make_unique<apps::WindowInfo>(display.id())); + } else { + apps::AppServiceProxyFactory::GetForProfile(profile)->LaunchAppWithIntent( + actions_[index].app_id, ui::EF_NONE, + apps::ConvertIntentToMojomIntent( + CreateIntent(std::move(actions_[index].action_intent), + std::move(actions_[index].activity))), + apps::mojom::LaunchSource::kFromSmartTextContextMenu, + apps::MakeWindowInfo(display.id())); + } } void StartSmartSelectionActionMenu::HandleTextSelectionActions(
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index e27e9c6..456ef137 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -1948,11 +1948,37 @@ AutotestPrivateGetLacrosInfoFunction::~AutotestPrivateGetLacrosInfoFunction() = default; +// static +api::autotest_private::LacrosState +AutotestPrivateGetLacrosInfoFunction::ToLacrosState( + crosapi::BrowserManager::State state) { + switch (state) { + case crosapi::BrowserManager::State::NOT_INITIALIZED: + return api::autotest_private::LACROS_STATE_NOTINITIALIZED; + case crosapi::BrowserManager::State::MOUNTING: + return api::autotest_private::LACROS_STATE_MOUNTING; + case crosapi::BrowserManager::State::UNAVAILABLE: + return api::autotest_private::LACROS_STATE_UNAVAILABLE; + case crosapi::BrowserManager::State::STOPPED: + return api::autotest_private::LACROS_STATE_STOPPED; + case crosapi::BrowserManager::State::CREATING_LOG_FILE: + return api::autotest_private::LACROS_STATE_CREATINGLOGFILE; + case crosapi::BrowserManager::State::STARTING: + return api::autotest_private::LACROS_STATE_STARTING; + case crosapi::BrowserManager::State::RUNNING: + return api::autotest_private::LACROS_STATE_RUNNING; + case crosapi::BrowserManager::State::TERMINATING: + return api::autotest_private::LACROS_STATE_TERMINATING; + } +} + ExtensionFunction::ResponseAction AutotestPrivateGetLacrosInfoFunction::Run() { DVLOG(1) << "AutotestPrivateGetLacrosInfoFunction"; auto* browser_manager = crosapi::BrowserManager::Get(); auto result = std::make_unique<base::DictionaryValue>(); result->SetBoolKey("isRunning", browser_manager->IsRunning()); + result->SetStringKey("state", api::autotest_private::ToString( + ToLacrosState(browser_manager->state_))); result->SetBoolKey("isKeepAlive", browser_manager->IsKeepAliveEnabled()); result->SetStringKey("lacrosPath", browser_manager->lacros_path().MaybeAsASCII());
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h index a23cce0..bb3dbdd 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -15,9 +15,11 @@ #include "ash/rotator/screen_rotation_animator_observer.h" #include "base/scoped_observation.h" #include "base/timer/timer.h" +#include "chrome/browser/ash/crosapi/browser_manager.h" #include "chrome/browser/ash/printing/cups_printers_manager.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/web_applications/web_app_id.h" +#include "chrome/common/extensions/api/autotest_private.h" #include "chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom-forward.h" #include "chromeos/services/machine_learning/public/mojom/model.mojom.h" #include "chromeos/ui/base/window_state_type.h" @@ -332,6 +334,8 @@ private: ~AutotestPrivateGetLacrosInfoFunction() override; ResponseAction Run() override; + static api::autotest_private::LacrosState ToLacrosState( + crosapi::BrowserManager::State state); }; class AutotestPrivateGetArcAppFunction : public ExtensionFunction {
diff --git a/chrome/browser/devtools/protocol/devtools_printtopdf_browsertest.cc b/chrome/browser/devtools/protocol/devtools_printtopdf_browsertest.cc index 0d8d6cd..d85c2920 100644 --- a/chrome/browser/devtools/protocol/devtools_printtopdf_browsertest.cc +++ b/chrome/browser/devtools/protocol/devtools_printtopdf_browsertest.cc
@@ -2,13 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "build/build_config.h" - -// Native headless is currently available only on Linux platform. More -// platforms will be added soon, so avoid function level clutter by -// ifdefing the entire file. -#if BUILDFLAG(IS_LINUX) - #include <string> #include <vector> @@ -44,8 +37,6 @@ static constexpr int kDpi = 300; void SetUpCommandLine(base::CommandLine* command_line) override { - // TODO(crbug.com/1240796): Page.printToPdf is currently available only when - // Chrome is running in headless mode. DevToolsProtocolTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII("headless", "chrome"); } @@ -455,5 +446,3 @@ } } // namespace - -#endif // BUILDFLAG(IS_LINUX)
diff --git a/chrome/browser/download/bubble/download_bubble_controller.cc b/chrome/browser/download/bubble/download_bubble_controller.cc index 4c70ae4..8fe6e4e 100644 --- a/chrome/browser/download/bubble/download_bubble_controller.cc +++ b/chrome/browser/download/bubble/download_bubble_controller.cc
@@ -114,6 +114,10 @@ DownloadBubbleUIController::~DownloadBubbleUIController() = default; +void DownloadBubbleUIController::HideDownloadUi() { + display_controller_->HideToolbarButton(); +} + bool DownloadBubbleUIController::MaybeAddOfflineItem(const OfflineItem& item, bool is_new) { if (profile_->IsOffTheRecord() != item.is_off_the_record)
diff --git a/chrome/browser/download/bubble/download_bubble_controller.h b/chrome/browser/download/bubble/download_bubble_controller.h index e563f747..1dec973 100644 --- a/chrome/browser/download/bubble/download_bubble_controller.h +++ b/chrome/browser/download/bubble/download_bubble_controller.h
@@ -89,6 +89,12 @@ // on when the scheduled time arrives. void ScheduleCancelForEphemeralWarning(const std::string& guid); + // Force the controller to hide the download UI entirely, including the bubble + // and the toolbar icon. This function should only be called if the event is + // triggered outside of normal download events that are not listened by + // observers. + void HideDownloadUi(); + // Returns the DownloadDisplayController. Should always return a valid // controller. DownloadDisplayController* GetDownloadDisplayController() {
diff --git a/chrome/browser/download/bubble/download_bubble_prefs.cc b/chrome/browser/download/bubble/download_bubble_prefs.cc index a6e56b7..e90d611 100644 --- a/chrome/browser/download/bubble/download_bubble_prefs.cc +++ b/chrome/browser/download/bubble/download_bubble_prefs.cc
@@ -6,13 +6,12 @@ #include "base/feature_list.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/download/download_core_service.h" +#include "chrome/browser/download/download_core_service_factory.h" #include "chrome/browser/enterprise/connectors/connectors_service.h" -#include "chrome/browser/safe_browsing/advanced_protection_status_manager.h" -#include "chrome/browser/safe_browsing/advanced_protection_status_manager_factory.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/core/common/features.h" -#include "components/safe_browsing/core/common/safe_browsing_prefs.h" namespace download { @@ -44,6 +43,14 @@ base::FeatureList::IsEnabled(safe_browsing::kDownloadBubbleV2); } +bool ShouldShowDownloadBubble(Profile* profile) { + // If the download UI is disabled by at least one extension, do not show the + // bubble and the toolbar icon. + return DownloadCoreServiceFactory::GetForBrowserContext( + profile->GetOriginalProfile()) + ->IsDownloadUiEnabled(); +} + bool IsDownloadConnectorEnabled(Profile* profile) { auto* connector_service = enterprise_connectors::ConnectorsServiceFactory::GetForBrowserContext(
diff --git a/chrome/browser/download/bubble/download_bubble_prefs.h b/chrome/browser/download/bubble/download_bubble_prefs.h index ff759be..923bf5f 100644 --- a/chrome/browser/download/bubble/download_bubble_prefs.h +++ b/chrome/browser/download/bubble/download_bubble_prefs.h
@@ -9,11 +9,15 @@ namespace download { +// Called when deciding whether to show the bubble or the old download shelf UI. bool IsDownloadBubbleEnabled(Profile* profile); // V2 is only eligible to be enabled if V1 is also enabled. bool IsDownloadBubbleV2Enabled(Profile* profile); +// Called when deciding whether to show or hide the bubble. +bool ShouldShowDownloadBubble(Profile* profile); + bool IsDownloadConnectorEnabled(Profile* profile); } // namespace download
diff --git a/chrome/browser/download/bubble/download_display_controller.cc b/chrome/browser/download/bubble/download_display_controller.cc index 8a25d6f..8de8a39 100644 --- a/chrome/browser/download/bubble/download_display_controller.cc +++ b/chrome/browser/download/bubble/download_display_controller.cc
@@ -7,6 +7,7 @@ #include "base/time/time.h" #include "base/timer/timer.h" #include "chrome/browser/download/bubble/download_bubble_controller.h" +#include "chrome/browser/download/bubble/download_bubble_prefs.h" #include "chrome/browser/download/bubble/download_display.h" #include "chrome/browser/download/bubble/download_icon_state.h" #include "chrome/browser/download/download_item_model.h" @@ -90,6 +91,10 @@ DownloadDisplayController::~DownloadDisplayController() = default; void DownloadDisplayController::OnNewItem(bool show_details) { + if (!download::ShouldShowDownloadBubble(browser_->profile())) { + return; + } + std::vector<std::unique_ptr<DownloadUIModel>> all_models = bubble_controller_->GetAllItemsToDisplay(); UpdateToolbarButtonState(all_models); @@ -109,6 +114,9 @@ void DownloadDisplayController::OnUpdatedItem(bool is_done, bool show_details_if_done) { + if (!download::ShouldShowDownloadBubble(browser_->profile())) { + return; + } if (is_done) { ScheduleToolbarDisappearance(kToolbarIconVisibilityTimeInterval); if (show_details_if_done) { @@ -125,6 +133,9 @@ } void DownloadDisplayController::OnRemovedItem(const ContentId& id) { + if (!download::ShouldShowDownloadBubble(browser_->profile())) { + return; + } std::vector<std::unique_ptr<DownloadUIModel>> all_models = bubble_controller_->GetAllItemsToDisplay(); // Hide the button if there is only one download item left and that item is @@ -259,6 +270,9 @@ } void DownloadDisplayController::MaybeShowButtonWhenCreated() { + if (!download::ShouldShowDownloadBubble(browser_->profile())) { + return; + } base::Time last_complete_time = GetLastCompleteTime(bubble_controller_->GetOfflineItems()); if (!HasRecentCompleteDownload(kToolbarIconVisibilityTimeInterval,
diff --git a/chrome/browser/download/bubble/download_display_controller.h b/chrome/browser/download/bubble/download_display_controller.h index 0bc2e50..36ec649 100644 --- a/chrome/browser/download/bubble/download_display_controller.h +++ b/chrome/browser/download/bubble/download_display_controller.h
@@ -82,6 +82,9 @@ // Called from bubble controller when an item is deleted. virtual void OnRemovedItem(const ContentId& id); + // Asks `display_` to hide the toolbar button. Does nothing if the toolbar + // button is already hidden. + void HideToolbarButton(); // Asks `display_` to hide the toolbar button details. Does nothing if the // details are already hidden. void HideBubble(); @@ -118,9 +121,6 @@ // Asks `display_` to show the toolbar button. Does nothing if the toolbar // button is already showing. void ShowToolbarButton(); - // Asks `display_` to hide the toolbar button. Does nothing if the toolbar - // button is already hidden. - void HideToolbarButton(); // Based on the information from `download_manager_`, updates the icon state // of the `display_`.
diff --git a/chrome/browser/download/download_core_service.h b/chrome/browser/download/download_core_service.h index 9453c04..79c2065 100644 --- a/chrome/browser/download/download_core_service.h +++ b/chrome/browser/download/download_core_service.h
@@ -74,9 +74,9 @@ virtual void SetDownloadHistoryForTesting( std::unique_ptr<DownloadHistory> download_history) {} - // Returns false if at least one extension has disabled the shelf, true + // Returns false if at least one extension has disabled the UI, true // otherwise. - virtual bool IsShelfEnabled() = 0; + virtual bool IsDownloadUiEnabled() = 0; }; #endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_CORE_SERVICE_H_
diff --git a/chrome/browser/download/download_core_service_impl.cc b/chrome/browser/download/download_core_service_impl.cc index 3eb0cc1..5cbb8bb6 100644 --- a/chrome/browser/download/download_core_service_impl.cc +++ b/chrome/browser/download/download_core_service_impl.cc
@@ -149,11 +149,11 @@ download_history_ = std::move(download_history); } -bool DownloadCoreServiceImpl::IsShelfEnabled() { +bool DownloadCoreServiceImpl::IsDownloadUiEnabled() { #if BUILDFLAG(IS_ANDROID) return true; #else - return !extension_event_router_ || extension_event_router_->IsShelfEnabled(); + return !extension_event_router_ || extension_event_router_->IsUiEnabled(); #endif }
diff --git a/chrome/browser/download/download_core_service_impl.h b/chrome/browser/download/download_core_service_impl.h index f837621..46214d6 100644 --- a/chrome/browser/download/download_core_service_impl.h +++ b/chrome/browser/download/download_core_service_impl.h
@@ -52,7 +52,7 @@ void CancelDownloads() override; void SetDownloadManagerDelegateForTesting( std::unique_ptr<ChromeDownloadManagerDelegate> delegate) override; - bool IsShelfEnabled() override; + bool IsDownloadUiEnabled() override; void SetDownloadHistoryForTesting( std::unique_ptr<DownloadHistory> download_history) override;
diff --git a/chrome/browser/download/download_item_model_unittest.cc b/chrome/browser/download/download_item_model_unittest.cc index 83a1f8a1..58af6478 100644 --- a/chrome/browser/download/download_item_model_unittest.cc +++ b/chrome/browser/download/download_item_model_unittest.cc
@@ -792,12 +792,8 @@ base::UTF16ToUTF8(bubble_ui_info.warning_summary)); EXPECT_EQ(test_case.expected_icon_model_override, bubble_ui_info.icon_model_override); - if (!test_case.expected_primary_button_command.has_value()) { - EXPECT_FALSE(bubble_ui_info.has_primary_button); - } else { - EXPECT_EQ(test_case.expected_primary_button_command.value(), - bubble_ui_info.primary_button_command); - } + EXPECT_EQ(test_case.expected_primary_button_command, + bubble_ui_info.primary_button_command); EXPECT_EQ(ui::kColorAlertHighSeverity, bubble_ui_info.secondary_color); EXPECT_FALSE(bubble_ui_info.has_progress_bar); } @@ -846,12 +842,8 @@ base::UTF16ToUTF8(bubble_ui_info.warning_summary)); EXPECT_EQ(test_case.expected_icon_model_override, bubble_ui_info.icon_model_override); - if (!test_case.expected_primary_button_command.has_value()) { - EXPECT_FALSE(bubble_ui_info.has_primary_button); - } else { - EXPECT_EQ(test_case.expected_primary_button_command.value(), - bubble_ui_info.primary_button_command); - } + EXPECT_EQ(test_case.expected_primary_button_command, + bubble_ui_info.primary_button_command); EXPECT_EQ(ui::kColorAlertHighSeverity, bubble_ui_info.secondary_color); EXPECT_FALSE(bubble_ui_info.has_progress_bar); }
diff --git a/chrome/browser/download/download_shelf.cc b/chrome/browser/download/download_shelf.cc index 7a24c4d2..6320d184 100644 --- a/chrome/browser/download/download_shelf.cc +++ b/chrome/browser/download/download_shelf.cc
@@ -98,7 +98,7 @@ return; if (!DownloadCoreServiceFactory::GetForBrowserContext(download->profile()) - ->IsShelfEnabled()) + ->IsDownloadUiEnabled()) return; Unhide();
diff --git a/chrome/browser/download/download_ui_model.cc b/chrome/browser/download/download_ui_model.cc index 8142bb0..ee114c0 100644 --- a/chrome/browser/download/download_ui_model.cc +++ b/chrome/browser/download/download_ui_model.cc
@@ -706,7 +706,6 @@ } DownloadUIModel::BubbleUIInfo& DownloadUIModel::BubbleUIInfo::AddPrimaryButton( DownloadCommands::Command command) { - has_primary_button = true; primary_button_command = command; return *this; }
diff --git a/chrome/browser/download/download_ui_model.h b/chrome/browser/download/download_ui_model.h index 900b7798..5ce35e885 100644 --- a/chrome/browser/download/download_ui_model.h +++ b/chrome/browser/download/download_ui_model.h
@@ -125,9 +125,8 @@ bool has_checkbox = false; std::u16string checkbox_label; - // Label and commands for the primary button - bool has_primary_button = false; - DownloadCommands::Command primary_button_command; + // The command for the primary button + absl::optional<DownloadCommands::Command> primary_button_command; // List of quick actions std::vector<QuickAction> quick_actions;
diff --git a/chrome/browser/extensions/api/downloads/downloads_api.cc b/chrome/browser/extensions/api/downloads/downloads_api.cc index bcb2992..ff80caea 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api.cc
@@ -33,6 +33,8 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/download/bubble/download_bubble_controller.h" +#include "chrome/browser/download/bubble/download_bubble_prefs.h" #include "chrome/browser/download/download_core_service.h" #include "chrome/browser/download/download_core_service_factory.h" #include "chrome/browser/download/download_danger_prompt.h" @@ -484,16 +486,16 @@ } } -void MaybeSetShelfEnabled(DownloadCoreService* service, - DownloadCoreService* incognito_service, - const Extension* extension, - bool enabled) { +void MaybeSetUiEnabled(DownloadCoreService* service, + DownloadCoreService* incognito_service, + const Extension* extension, + bool enabled) { if (service) { - service->GetExtensionEventRouter()->SetShelfEnabled(extension, enabled); + service->GetExtensionEventRouter()->SetUiEnabled(extension, enabled); } if (incognito_service) { - incognito_service->GetExtensionEventRouter()->SetShelfEnabled(extension, - enabled); + incognito_service->GetExtensionEventRouter()->SetUiEnabled(extension, + enabled); } } @@ -1506,26 +1508,39 @@ GetDownloadCoreServices(browser_context(), include_incognito_information(), &service, &incognito_service); - MaybeSetShelfEnabled(service, incognito_service, extension(), - params->enabled); + MaybeSetUiEnabled(service, incognito_service, extension(), params->enabled); + + bool is_bubble_enabled = download::IsDownloadBubbleEnabled( + Profile::FromBrowserContext(browser_context())); BrowserList* browsers = BrowserList::GetInstance(); if (browsers) { - for (auto iter = browsers->begin(); iter != browsers->end(); ++iter) { - const Browser* browser = *iter; + for (auto* browser : *browsers) { DownloadCoreService* current_service = DownloadCoreServiceFactory::GetForBrowserContext(browser->profile()); - if (((current_service == service) || - (current_service == incognito_service)) && - browser->window()->IsDownloadShelfVisible() && - !current_service->IsShelfEnabled()) + // The following code is to hide the download UI explicitly if the UI is + // set to disabled. + bool match_current_service = (current_service == service) || + (current_service == incognito_service); + if (!match_current_service || current_service->IsDownloadUiEnabled()) { + continue; + } + // Calling this API affects the download bubble as well, so extensions + // using this API is still compatible with the new download bubble. This + // API will eventually be deprecated (replaced by the SetUiOptions API + // below). + if (is_bubble_enabled && + browser->window()->GetDownloadBubbleUIController()) { + browser->window()->GetDownloadBubbleUIController()->HideDownloadUi(); + } else if (browser->window()->IsDownloadShelfVisible()) { browser->window()->GetDownloadShelf()->Close(); + } } } if (params->enabled && - ((service && !service->IsShelfEnabled()) || - (incognito_service && !incognito_service->IsShelfEnabled()))) { + ((service && !service->IsDownloadUiEnabled()) || + (incognito_service && !incognito_service->IsDownloadUiEnabled()))) { return RespondNow(Error(download_extension_errors::kShelfDisabled)); } @@ -1552,26 +1567,35 @@ GetDownloadCoreServices(browser_context(), include_incognito_information(), &service, &incognito_service); - MaybeSetShelfEnabled(service, incognito_service, extension(), - options.enabled); + MaybeSetUiEnabled(service, incognito_service, extension(), options.enabled); + + bool is_bubble_enabled = download::IsDownloadBubbleEnabled( + Profile::FromBrowserContext(browser_context())); BrowserList* browsers = BrowserList::GetInstance(); if (browsers) { for (auto* browser : *browsers) { DownloadCoreService* current_service = DownloadCoreServiceFactory::GetForBrowserContext(browser->profile()); - if (((current_service == service) || - (current_service == incognito_service)) && - browser->window()->IsDownloadShelfVisible() && - !current_service->IsShelfEnabled()) { + // The following code is to hide the download UI explicitly if the UI is + // set to disabled. + bool match_current_service = (current_service == service) || + (current_service == incognito_service); + if (!match_current_service || current_service->IsDownloadUiEnabled()) { + continue; + } + if (is_bubble_enabled && + browser->window()->GetDownloadBubbleUIController()) { + browser->window()->GetDownloadBubbleUIController()->HideDownloadUi(); + } else if (browser->window()->IsDownloadShelfVisible()) { browser->window()->GetDownloadShelf()->Close(); } } } if (options.enabled && - ((service && !service->IsShelfEnabled()) || - (incognito_service && !incognito_service->IsShelfEnabled()))) { + ((service && !service->IsDownloadUiEnabled()) || + (incognito_service && !incognito_service->IsDownloadUiEnabled()))) { return RespondNow(Error(download_extension_errors::kUiDisabled)); } @@ -1657,19 +1681,19 @@ SetDetermineFilenameTimeoutSecondsForTesting(s); } -void ExtensionDownloadsEventRouter::SetShelfEnabled(const Extension* extension, - bool enabled) { - auto iter = shelf_disabling_extensions_.find(extension); - if (iter == shelf_disabling_extensions_.end()) { +void ExtensionDownloadsEventRouter::SetUiEnabled(const Extension* extension, + bool enabled) { + auto iter = ui_disabling_extensions_.find(extension); + if (iter == ui_disabling_extensions_.end()) { if (!enabled) - shelf_disabling_extensions_.insert(extension); + ui_disabling_extensions_.insert(extension); } else if (enabled) { - shelf_disabling_extensions_.erase(extension); + ui_disabling_extensions_.erase(extension); } } -bool ExtensionDownloadsEventRouter::IsShelfEnabled() const { - return shelf_disabling_extensions_.empty(); +bool ExtensionDownloadsEventRouter::IsUiEnabled() const { + return ui_disabling_extensions_.empty(); } // The method by which extensions hook into the filename determination process @@ -2010,9 +2034,9 @@ const Extension* extension, UnloadedExtensionReason reason) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - auto iter = shelf_disabling_extensions_.find(extension); - if (iter != shelf_disabling_extensions_.end()) - shelf_disabling_extensions_.erase(iter); + auto iter = ui_disabling_extensions_.find(extension); + if (iter != ui_disabling_extensions_.end()) + ui_disabling_extensions_.erase(iter); } void ExtensionDownloadsEventRouter::CheckForHistoryFilesRemoval() {
diff --git a/chrome/browser/extensions/api/downloads/downloads_api.h b/chrome/browser/extensions/api/downloads/downloads_api.h index e5d2eac..fabb6603 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chrome/browser/extensions/api/downloads/downloads_api.h
@@ -388,8 +388,8 @@ ~ExtensionDownloadsEventRouter() override; - void SetShelfEnabled(const extensions::Extension* extension, bool enabled); - bool IsShelfEnabled() const; + void SetUiEnabled(const extensions::Extension* extension, bool enabled); + bool IsUiEnabled() const; // Called by ChromeDownloadManagerDelegate during the filename determination // process, allows extensions to change the item's target filename. If no @@ -430,7 +430,7 @@ raw_ptr<Profile> profile_; download::AllDownloadItemNotifier notifier_; - std::set<const extensions::Extension*> shelf_disabling_extensions_; + std::set<const extensions::Extension*> ui_disabling_extensions_; base::Time last_checked_removal_;
diff --git a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index 7f2546a..02a3b85 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -28,6 +28,9 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" +#include "chrome/browser/download/bubble/download_bubble_controller.h" +#include "chrome/browser/download/bubble/download_display.h" +#include "chrome/browser/download/bubble/download_display_controller.h" #include "chrome/browser/download/download_core_service.h" #include "chrome/browser/download/download_core_service_factory.h" #include "chrome/browser/download/download_file_icon_extractor.h" @@ -41,6 +44,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/extension_action_test_helper.h" #include "chrome/common/extensions/api/downloads.h" #include "chrome/common/pref_names.h" @@ -49,6 +53,7 @@ #include "components/download/public/common/download_item.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/content/common/file_type_policies_test_util.h" +#include "components/safe_browsing/core/common/features.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -4580,11 +4585,11 @@ EXPECT_TRUE(RunFunction(new DownloadsSetShelfEnabledFunction(), "[false]")); EXPECT_FALSE(DownloadCoreServiceFactory::GetForBrowserContext( current_browser()->profile()) - ->IsShelfEnabled()); + ->IsDownloadUiEnabled()); EXPECT_TRUE(RunFunction(new DownloadsSetShelfEnabledFunction(), "[true]")); EXPECT_TRUE(DownloadCoreServiceFactory::GetForBrowserContext( current_browser()->profile()) - ->IsShelfEnabled()); + ->IsDownloadUiEnabled()); // TODO(benjhayden) Test that existing shelves are hidden. // TODO(benjhayden) Test multiple extensions. // TODO(benjhayden) Test disabling extensions. @@ -4606,12 +4611,12 @@ R"([{"enabled": false}])")); EXPECT_FALSE(DownloadCoreServiceFactory::GetForBrowserContext( current_browser()->profile()) - ->IsShelfEnabled()); + ->IsDownloadUiEnabled()); EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), R"([{"enabled": true}])")); EXPECT_TRUE(DownloadCoreServiceFactory::GetForBrowserContext( current_browser()->profile()) - ->IsShelfEnabled()); + ->IsDownloadUiEnabled()); } void OnDangerPromptCreated(DownloadDangerPrompt* prompt) { @@ -4721,6 +4726,84 @@ result_id))); } +// The DownloadExtensionBubbleEnabledTest relies on the download surface, which +// ChromeOS_ASH doesn't use (see crbug.com/1323505). +#if !BUILDFLAG(IS_CHROMEOS_ASH) +class DownloadExtensionBubbleEnabledTest : public DownloadExtensionTest { + public: + DownloadExtensionBubbleEnabledTest() { + feature_list_.InitAndEnableFeature(safe_browsing::kDownloadBubble); + } + + bool IsDownloadToolbarButtonShowing() { + return current_browser() + ->window() + ->GetDownloadBubbleUIController() + ->GetDownloadDisplayController() + ->download_display_for_testing() + ->IsShowing(); + } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +IN_PROC_BROWSER_TEST_F(DownloadExtensionBubbleEnabledTest, + DownloadExtensionBubbleEnabledTest_SetUiOptions) { + DownloadManager::DownloadVector items; + CreateTwoDownloads(&items); + ScopedItemVectorCanceller delete_items(&items); + LoadExtension("downloads_split"); + + EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), + R"([{"enabled": true}])")); + EXPECT_TRUE(IsDownloadToolbarButtonShowing()); + + EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), + R"([{"enabled": false}])")); + EXPECT_FALSE(IsDownloadToolbarButtonShowing()); + + items[0]->Cancel(true); + // Remain hidden on download updates. + EXPECT_FALSE(IsDownloadToolbarButtonShowing()); +} + +IN_PROC_BROWSER_TEST_F( + DownloadExtensionBubbleEnabledTest, + DownloadExtensionBubbleEnabledTest_SetUiOptionsBeforeDownloadStart) { + LoadExtension("downloads_split"); + EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), + R"([{"enabled": false}])")); + DownloadManager::DownloadVector items; + CreateTwoDownloads(&items); + ScopedItemVectorCanceller delete_items(&items); + EXPECT_FALSE(IsDownloadToolbarButtonShowing()); +} + +IN_PROC_BROWSER_TEST_F( + DownloadExtensionBubbleEnabledTest, + DownloadExtensionBubbleEnabledTest_SetUiOptionsOffTheRecord) { + LoadExtension("downloads_split"); + EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), + R"([{"enabled": false}])")); + DownloadManager::DownloadVector items; + CreateTwoDownloads(&items); + ScopedItemVectorCanceller delete_items(&items); + EXPECT_FALSE(IsDownloadToolbarButtonShowing()); + + GoOffTheRecord(); + EXPECT_FALSE(IsDownloadToolbarButtonShowing()); + + EXPECT_TRUE(RunFunction(new DownloadsSetUiOptionsFunction(), + R"([{"enabled": true}])")); + items[0]->Cancel(true); + EXPECT_TRUE(IsDownloadToolbarButtonShowing()); + + GoOnTheRecord(); + EXPECT_TRUE(IsDownloadToolbarButtonShowing()); +} +#endif // !BUILDFLAG(IS_CHROMEOS_ASH) + class DownloadsApiTest : public ExtensionApiTest { public: DownloadsApiTest() {}
diff --git a/chrome/browser/extensions/api/file_system/consent_provider.cc b/chrome/browser/extensions/api/file_system/consent_provider.cc index 6e47c41..3d5760075b 100644 --- a/chrome/browser/extensions/api/file_system/consent_provider.cc +++ b/chrome/browser/extensions/api/file_system/consent_provider.cc
@@ -32,8 +32,7 @@ // List of allowlisted component apps and extensions by their ids for // chrome.fileSystem.requestFileSystem. const char* const kRequestFileSystemComponentAllowlist[] = { - file_manager::kFileManagerAppId, file_manager::kAudioPlayerAppId, - file_manager::kImageLoaderExtensionId, + file_manager::kFileManagerAppId, file_manager::kImageLoaderExtensionId, // TODO(henryhsu,b/110126438): Remove this extension id, and add it only // for tests. "pkplfbidichfdicaijlchgnapepdginl" // Testing extensions.
diff --git a/chrome/browser/extensions/component_extensions_allowlist/allowlist.cc b/chrome/browser/extensions/component_extensions_allowlist/allowlist.cc index 4e91bdb..ac44715 100644 --- a/chrome/browser/extensions/component_extensions_allowlist/allowlist.cc +++ b/chrome/browser/extensions/component_extensions_allowlist/allowlist.cc
@@ -78,7 +78,6 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) // Separate ChromeOS list, as it is quite large. case IDR_ARC_SUPPORT_MANIFEST: - case IDR_AUDIO_PLAYER_MANIFEST: case IDR_CHROME_APP_MANIFEST: case IDR_FILEMANAGER_MANIFEST: case IDR_IMAGE_LOADER_MANIFEST:
diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index 6939f10..b8289914 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc
@@ -385,17 +385,6 @@ } } -void ComponentLoader::AddAudioPlayerExtension() { - // TODO(b/189172062): Delete this entirely around M106 when it has has a - // chance to be cleaned up. - if (extensions::ExtensionPrefs::Get(profile_) - ->ShouldInstallObsoleteComponentExtension( - file_manager::kAudioPlayerAppId)) { - Add(IDR_AUDIO_PLAYER_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("audio_player"))); - } -} - void ComponentLoader::AddImageLoaderExtension() { Add(IDR_IMAGE_LOADER_MANIFEST, base::FilePath(FILE_PATH_LITERAL("image_loader"))); @@ -537,7 +526,6 @@ switches::kLoadGuestModeTestExtension)); AddGuestModeTestExtension(path); } - AddAudioPlayerExtension(); AddFileManagerExtension(); AddImageLoaderExtension();
diff --git a/chrome/browser/extensions/component_loader.h b/chrome/browser/extensions/component_loader.h index 0ba2893..ea0492a 100644 --- a/chrome/browser/extensions/component_loader.h +++ b/chrome/browser/extensions/component_loader.h
@@ -191,7 +191,6 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) void AddChromeApp(); void AddFileManagerExtension(); - void AddAudioPlayerExtension(); void AddGalleryExtension(); void AddImageLoaderExtension(); void AddGuestModeTestExtension(const base::FilePath& path);
diff --git a/chrome/browser/extensions/extension_keeplist_chromeos.cc b/chrome/browser/extensions/extension_keeplist_chromeos.cc index 96fddbe..8068016 100644 --- a/chrome/browser/extensions/extension_keeplist_chromeos.cc +++ b/chrome/browser/extensions/extension_keeplist_chromeos.cc
@@ -62,7 +62,6 @@ static base::NoDestructor<std::set<base::StringPiece>> keep_list({ #if BUILDFLAG(IS_CHROMEOS_ASH) arc::kPlayStoreAppId, extension_misc::kFilesManagerAppId, - file_manager::kAudioPlayerAppId, #endif extension_misc::kGoogleKeepAppId, extension_misc::kCalculatorAppId,
diff --git a/chrome/browser/extensions/extension_prefs_unittest.cc b/chrome/browser/extensions/extension_prefs_unittest.cc index 049c4f36..7470df6 100644 --- a/chrome/browser/extensions/extension_prefs_unittest.cc +++ b/chrome/browser/extensions/extension_prefs_unittest.cc
@@ -114,28 +114,6 @@ }; TEST_F(ExtensionPrefsLastPingDay, LastPingDay) {} -// Tests the GetToolbarOrder/SetToolbarOrder functions. -class ExtensionPrefsToolbarOrder : public ExtensionPrefsTest { - public: - void Initialize() override { - list_.push_back(prefs_.AddExtensionAndReturnId("1")); - list_.push_back(prefs_.AddExtensionAndReturnId("2")); - list_.push_back(prefs_.AddExtensionAndReturnId("3")); - ExtensionIdList before_list = prefs()->GetToolbarOrder(); - EXPECT_TRUE(before_list.empty()); - prefs()->SetToolbarOrder(list_); - } - - void Verify() override { - ExtensionIdList result = prefs()->GetToolbarOrder(); - ASSERT_EQ(list_, result); - } - - private: - ExtensionIdList list_; -}; -TEST_F(ExtensionPrefsToolbarOrder, ToolbarOrder) {} - // Tests the IsExtensionDisabled/SetExtensionState functions. class ExtensionPrefsExtensionState : public ExtensionPrefsTest { public:
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 40e72e9..1b163a3 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -144,10 +144,6 @@ // The Video Player chrome app became obsolete in m93, but is preserved for // continued test coverage. "jcgeabjmjgoblfofpppfkcoakmfobdko", // Video Player - // The Audio Player chrome app became obsolete in m97. This entry can be - // removed after references to kAudioPlayerAppId in component_loader.cc - // are removed. - "cjbfomnbifhcdnihkgipgfcihmgjfhbf" // Audio Player }; } // namespace
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 2c604be..edc94ffb 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -413,12 +413,12 @@ { "name": "autofill-always-return-cloud-tokenized-card", "owners": [ "aneeshali@google.com", "jsaul@google.com", "siyua" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-auto-trigger-manual-fallback-for-cards", "owners": ["siashah", "siyua"], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-center-aligned-suggestions", @@ -438,7 +438,7 @@ { "name": "autofill-enable-manual-fallback-for-virtual-cards", "owners": [ "siashah", "siyua" ], - "expiry_milestone": 106 + "expiry_milestone": 112 }, { "name": "autofill-enable-new-card-unmask-prompt-view", @@ -448,12 +448,12 @@ { "name": "autofill-enable-offer-notification-for-promo-codes", "owners": [ "jsaul@google.com", "siyua" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-enable-offers-in-clank-keyboard-accessory", "owners": [ "siyua", "siashah@google.com" ], - "expiry_milestone": 106 + "expiry_milestone": 112 }, { "name": "autofill-enable-ranking-formula", @@ -471,37 +471,37 @@ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 108 }, { "name": "autofill-enable-sticky-manual-fallback-for-cards", "owners": [ "siashah","siyua" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-enable-toolbar-status-chip", "owners": [ "siyua" ], - "expiry_milestone": 106 + "expiry_milestone": 109 }, { "name": "autofill-enable-unmask-card-request-set-instrument-id", "owners": [ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 109 }, { "name": "autofill-enable-update-virtual-card-enrollment", "owners": [ "siyua", "jsaul@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-enable-upstream-save-card-offer-ui-experiment", "owners": [ "koulvipul@google.com", "payments-autofill-team@google.com"], - "expiry_milestone": 108 + "expiry_milestone": 112 }, { "name": "autofill-enable-virtual-card", "owners": [ "siyua", "jsaul@google.com", "aneeshali@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-enable-virtual-card-fido-enrollment", @@ -511,7 +511,7 @@ { "name": "autofill-enable-virtual-card-management-in-desktop-settings-page", "owners": [ "siyua", "jsaul@google.com"], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-enable-virtual-card-metadata", @@ -521,12 +521,12 @@ { "name": "autofill-enforce-delays-in-strike-database", "owners": [ "siyua"], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-fill-merchant-promo-code-fields", "owners": [ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-highlight-only-changed-value-in-preview-mode", @@ -551,7 +551,7 @@ { "name": "autofill-parse-merchant-promo-code-fields", "owners": [ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-prevent-overriding-prefilled-values", @@ -561,7 +561,7 @@ { "name": "autofill-remove-card-expiry-from-downstream-suggestion", "owners": [ "siyua", "siashah" ], - "expiry_milestone": 105 + "expiry_milestone": 112 }, { "name": "autofill-save-card-dismiss-on-navigation", @@ -581,12 +581,12 @@ { "name": "autofill-upstream-allow-additional-email-domains", "owners": [ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 109 + "expiry_milestone": 112 }, { "name": "autofill-upstream-allow-all-email-domains", "owners": [ "jsaul@google.com", "payments-autofill-team@google.com" ], - "expiry_milestone": 109 + "expiry_milestone": 112 }, { "name": "autofill-use-consistent-popup-settings-icons", @@ -3491,7 +3491,7 @@ { "name": "files-web-drive-office", "owners": [ "jboulic", "petermarshall", "simmonsjosh@google.com" ], - "expiry_milestone": 105 + "expiry_milestone": 120 }, { "name": "fill-on-account-select", @@ -3511,7 +3511,7 @@ { "name": "font-access", "owners": [ "dslee" ], - "expiry_milestone": 105 + "expiry_milestone": 108 }, { "name": "force-color-profile", @@ -4289,7 +4289,7 @@ { "name": "messages-for-android-offer-notification", "owners": [ "vishwasuppoor", "siashah" ], - "expiry_milestone": 105 + "expiry_milestone": 111 }, { "name": "messages-for-android-passwords", @@ -5491,6 +5491,11 @@ "expiry_milestone": -1 }, { + "name": "release-track-ui", + "owners": [ "rtinkoff", "cros-status-area-eng@google.com" ], + "expiry_milestone": 114 + }, + { "name": "remove-extra-ntps", "owners": [ "thegreenfrog@chromium.org", "bling-team@google.org" ], "expiry_milestone": 105 @@ -5716,6 +5721,11 @@ "expiry_milestone": 98 }, { + "name": "shelf-auto-hide-separation", + "owners": [ "etuck", "//ash/shelf/OWNERS" ], + "expiry_milestone": 108 + }, + { "name": "shelf-drag-to-pin", "owners": ["tbarzic", "//ash/shelf/OWNERS" ], "expiry_milestone": 106 @@ -6448,11 +6458,6 @@ "expiry_milestone": 128 }, { - "name": "vertical-snap", - "owners": [ "cattalyya", "afakhry", "nupurjain", "fanafan"], - "expiry_milestone": 100 - }, - { "name": "video-tutorials", "owners": [ "shaktisahu"], "expiry_milestone": 102
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 5fe394a..b4cd233 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2887,12 +2887,6 @@ "Enable rendering of COLRv1 glyphs with font variations applied. When this " "flag is off, variations to COLRv1 tables are ignored."; -const char kVerticalSnapName[] = "Vertical Snap features"; -const char kVerticalSnapDescription[] = - "This enables Vertical Snap feature in portrait display." - "This feature allows users to snap windows to top and bottom in portrait " - "display orientation and maintains left/right snap for landscape display."; - const char kGlobalVaapiLockName[] = "Global lock on the VA-API wrapper."; const char kGlobalVaapiLockDescription[] = "Enable or disable the global VA-API lock for platforms and paths that " @@ -5569,6 +5563,10 @@ const char kReleaseNotesNotificationAllChannelsDescription[] = "Enables the release notes notification for all ChromeOS channels"; +const char kReleaseTrackUiName[] = "Release track system tray UI"; +const char kReleaseTrackUiDescription[] = + "Enables the release track UI in the system tray"; + const char kArcWindowPredictorName[] = "Enable ARC window predictor"; const char kArcWindowPredictorDescription[] = "Enables the window state and bounds predictor for ARC task windows"; @@ -5590,6 +5588,12 @@ "Enables a share action in the sharesheet that copies the selected data to " "the clipboard."; +const char kShelfAutoHideSeparationName[] = + "Enable separate shelf auto-hide preferences."; +const char kShelfAutoHideSeparationDescription[] = + "Allows for the shelf's auto-hide preference to be specified separately " + "for clamshell and tablet mode."; + const char kShimlessRMAFlowName[] = "Enable shimless RMA flow"; const char kShimlessRMAFlowDescription[] = "Enable shimless RMA flow";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 56f246d..22140fe7 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1615,9 +1615,6 @@ extern const char kVariableCOLRV1Name[]; extern const char kVariableCOLRV1Description[]; -extern const char kVerticalSnapName[]; -extern const char kVerticalSnapDescription[]; - extern const char kGlobalVaapiLockName[]; extern const char kGlobalVaapiLockDescription[]; @@ -3188,6 +3185,9 @@ extern const char kReleaseNotesNotificationAllChannelsName[]; extern const char kReleaseNotesNotificationAllChannelsDescription[]; +extern const char kReleaseTrackUiName[]; +extern const char kReleaseTrackUiDescription[]; + extern const char kArcWindowPredictorName[]; extern const char kArcWindowPredictorDescription[]; @@ -3200,6 +3200,9 @@ extern const char kSharesheetCopyToClipboardName[]; extern const char kSharesheetCopyToClipboardDescription[]; +extern const char kShelfAutoHideSeparationName[]; +extern const char kShelfAutoHideSeparationDescription[]; + extern const char kShimlessRMAFlowName[]; extern const char kShimlessRMAFlowDescription[];
diff --git a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc index f67c93b01..f698acff 100644 --- a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc +++ b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_browsertest.cc
@@ -115,8 +115,7 @@ void RunTestWithUrl(const GURL& url) { // Use the testing subclass of MimeHandlerViewGuest. - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); const extensions::Extension* extension = LoadTestExtension(); ASSERT_TRUE(extension); @@ -363,8 +362,7 @@ IN_PROC_BROWSER_TEST_F(ChromeMimeHandlerViewTest, EmbedWithInitialFrameAcceptBeforeUnloadDialog) { // Use the testing subclass of MimeHandlerViewGuest. - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); const extensions::Extension* extension = LoadTestExtension(); ASSERT_TRUE(extension); ASSERT_TRUE(ui_test_utils::NavigateToURL( @@ -581,8 +579,7 @@ // blocked in sandboxed frames). IN_PROC_BROWSER_TEST_F(ChromeMimeHandlerViewTest, DoNotLoadInSandboxedFrame) { // Use the testing subclass of MimeHandlerViewGuest. - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); const extensions::Extension* extension = LoadTestExtension(); ASSERT_TRUE(extension); @@ -630,8 +627,7 @@ // Tests that a MimeHandlerViewGuest auto-rejects pointer lock requests. IN_PROC_BROWSER_TEST_F(ChromeMimeHandlerViewTest, RejectPointLock) { - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); auto* extension = LoadTestExtension(); ASSERT_TRUE(extension);
diff --git a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_interactive_uitest.cc b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_interactive_uitest.cc index 1a1e483..8b9ec29 100644 --- a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_interactive_uitest.cc +++ b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_interactive_uitest.cc
@@ -83,8 +83,7 @@ void RunTestWithUrl(const GURL& url) { // Use the testing subclass of MimeHandlerViewGuest. - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); const Extension* extension = LoadTestExtension(); ASSERT_TRUE(extension); @@ -141,8 +140,7 @@ IN_PROC_BROWSER_TEST_F(ChromeMimeHandlerViewInteractiveUITest, MAYBE_EscapeExitsFullscreen) { // Use the testing subclass of MimeHandlerViewGuest. - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); const Extension* extension = LoadTestExtension(); ASSERT_TRUE(extension);
diff --git a/chrome/browser/media/capture_access_handler_base.cc b/chrome/browser/media/capture_access_handler_base.cc index b302eb17..bccdf0d 100644 --- a/chrome/browser/media/capture_access_handler_base.cc +++ b/chrome/browser/media/capture_access_handler_base.cc
@@ -14,7 +14,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_observer.h" #include "extensions/common/extension.h" #include "ui/gfx/native_widget_types.h" @@ -29,40 +28,41 @@ using content::BrowserThread; -namespace { - -// Keep track of the outermost WebContents for a particular tab. -// Similar semantics as base::WeakPtr<WebContents> as WebContentsObserver -// will detect when the WebContents no longer exists. -class WeakPtrToWebContents : private content::WebContentsObserver { - public: - WeakPtrToWebContents() = default; - - WeakPtrToWebContents(const WeakPtrToWebContents&) = delete; - WeakPtrToWebContents& operator=(const WeakPtrToWebContents&) = delete; - - ~WeakPtrToWebContents() override = default; - - void Set(int render_process_id, int render_frame_id) { - auto* target_web_contents = content::WebContents::FromRenderFrameHost( - content::RenderFrameHost::FromID(render_process_id, render_frame_id)); - // Use the outermost WebContents in the WebContents tree, if possible. - // If we can't find the WebContents, clear the observer. - WebContentsObserver::Observe( - target_web_contents ? target_web_contents->GetOutermostWebContents() - : nullptr); - } - - content::WebContents* get() const { - return WebContentsObserver::web_contents(); - } -}; - -} // namespace - // Tracks MEDIA_DESKTOP/TAB_VIDEO_CAPTURE sessions. Sessions are removed when // MEDIA_REQUEST_STATE_CLOSING is encountered. struct CaptureAccessHandlerBase::Session { + Session(int request_process_id, + int request_frame_id, + int page_request_id, + bool is_trusted, + bool is_capturing_link_secure, + content::DesktopMediaID::Type capturing_type, + gfx::NativeWindow target_window) + : request_process_id(request_process_id), + request_frame_id(request_frame_id), + page_request_id(page_request_id), + is_trusted(is_trusted), + is_capturing_link_secure(is_capturing_link_secure), + capturing_type(capturing_type), + target_window(target_window) { + SetWebContents(request_process_id, request_frame_id); + } + + void SetWebContents(int render_process_id, int render_frame_id) { + auto* target_web_contents = content::WebContents::FromRenderFrameHost( + content::RenderFrameHost::FromID(render_process_id, render_frame_id)); + // Use the outermost WebContents in the WebContents tree, if possible. + // If we can't find the WebContents, clear |target_web_contents|. + this->target_web_contents = + target_web_contents + ? target_web_contents->GetOutermostWebContents()->GetWeakPtr() + : nullptr; + } + + content::WebContents* GetWebContents() const { + return target_web_contents.get(); + } + int request_process_id; int request_frame_id; int page_request_id; @@ -78,10 +78,10 @@ // then |capturing_type| is TYPE_SCREEN. If a specific window is specified, // then |capturing_type| is TYPE_WINDOW and |target_window| is set. If a // specific tab is the target, then |capturing_type| is TYPE_WEB_CONTENTS and - // |target_weak_web_contents| is set. + // |target_web_contents| is set. content::DesktopMediaID::Type capturing_type; gfx::NativeWindow target_window; - std::unique_ptr<WeakPtrToWebContents> target_weak_web_contents; + base::WeakPtr<content::WebContents> target_web_contents; }; CaptureAccessHandlerBase::PendingAccessRequest::PendingAccessRequest( @@ -114,9 +114,7 @@ // Assume that the target is the same tab that is // requesting capture, not the display or any particular // window. This can be changed by calling UpdateTarget(). - content::DesktopMediaID::TYPE_WEB_CONTENTS, gfx::kNullNativeWindow, - std::make_unique<WeakPtrToWebContents>()}; - session.target_weak_web_contents->Set(render_process_id, render_frame_id); + content::DesktopMediaID::TYPE_WEB_CONTENTS, gfx::kNullNativeWindow}; sessions_.push_back(std::move(session)); } @@ -236,9 +234,8 @@ #endif } else if (target.type == content::DesktopMediaID::TYPE_WEB_CONTENTS) { // Specific tab captured. - it->target_weak_web_contents->Set( - target.web_contents_id.render_process_id, - target.web_contents_id.main_render_frame_id); + it->SetWebContents(target.web_contents_id.render_process_id, + target.web_contents_id.main_render_frame_id); } } @@ -294,7 +291,7 @@ case content::DesktopMediaID::TYPE_WEB_CONTENTS: // Check that the target is the frame selected. - auto* target_web_contents = session.target_weak_web_contents->get(); + auto* target_web_contents = session.GetWebContents(); if (!target_web_contents) return false; auto* web_contents = content::WebContents::FromRenderFrameHost(
diff --git a/chrome/browser/media/router/media_router_feature.cc b/chrome/browser/media/router/media_router_feature.cc index fe8c8ca..dcb025a 100644 --- a/chrome/browser/media/router/media_router_feature.cc +++ b/chrome/browser/media/router/media_router_feature.cc
@@ -40,6 +40,8 @@ base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kDialEnforceUrlIPAddress{"DialEnforceUrlIPAddress", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kMediaRemotingWithoutFullscreen{ + "MediaRemotingWithoutFullscreen", base::FEATURE_DISABLED_BY_DEFAULT}; #if BUILDFLAG(IS_CHROMEOS) const base::Feature kGlobalMediaControlsCastStartStop{
diff --git a/chrome/browser/media/router/media_router_feature.h b/chrome/browser/media/router/media_router_feature.h index 080713f..a3938f4 100644 --- a/chrome/browser/media/router/media_router_feature.h +++ b/chrome/browser/media/router/media_router_feature.h
@@ -51,6 +51,9 @@ // TODO(crbug.com/1270509): Remove this base::Feature once fully launched. extern const base::Feature kDialEnforceUrlIPAddress; +// If enabled, users can request Media Remoting without fullscreen-in-tab. +extern const base::Feature kMediaRemotingWithoutFullscreen; + // Registers |kMediaRouterCastAllowAllIPs| with local state pref |registry|. void RegisterLocalStatePrefs(PrefRegistrySimple* registry);
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc index 9d2f991..0b89d4b 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc +++ b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc
@@ -260,7 +260,7 @@ } const MediaSource source(source_id); - if (source.IsTabMirroringSource() || source.IsLocalFileSource()) { + if (source.IsTabMirroringSource()) { // Ensure the CastRemotingConnector is created before mirroring starts. CastRemotingConnector* const connector = CastRemotingConnector::Get(web_contents);
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity.cc b/chrome/browser/media/router/providers/cast/mirroring_activity.cc index 03d88afb..edd0a7a 100644 --- a/chrome/browser/media/router/providers/cast/mirroring_activity.cc +++ b/chrome/browser/media/router/providers/cast/mirroring_activity.cc
@@ -56,8 +56,6 @@ "MediaRouter.CastStreaming.Session.Length"; constexpr char kHistogramSessionLengthAccessCode[] = "MediaRouter.CastStreaming.Session.Length.AccessCode"; -constexpr char kHistogramSessionLengthFile[] = - "MediaRouter.CastStreaming.Session.Length.File"; constexpr char kHistogramSessionLengthOffscreenTab[] = "MediaRouter.CastStreaming.Session.Length.OffscreenTab"; constexpr char kHistogramSessionLengthScreen[] = @@ -106,7 +104,7 @@ return absl::nullopt; const auto source = route.media_source(); - if (source.IsTabMirroringSource() || source.IsLocalFileSource()) + if (source.IsTabMirroringSource()) return MirroringActivity::MirroringType::kTab; if (source.IsDesktopMirroringSource()) return MirroringActivity::MirroringType::kDesktop; @@ -165,11 +163,6 @@ auto cast_duration = base::Time::Now() - *did_start_mirroring_timestamp_; base::UmaHistogramLongTimes(kHistogramSessionLength, cast_duration); - if (route().media_source().IsLocalFileSource()) { - base::UmaHistogramLongTimes(kHistogramSessionLengthFile, cast_duration); - return; - } - if (!mirroring_type_) { // The mirroring activity should always be set by now, but check anyway // to avoid risk of a segfault.
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity_unittest.cc b/chrome/browser/media/router/providers/cast/mirroring_activity_unittest.cc index 04748af..bd19fb2 100644 --- a/chrome/browser/media/router/providers/cast/mirroring_activity_unittest.cc +++ b/chrome/browser/media/router/providers/cast/mirroring_activity_unittest.cc
@@ -43,8 +43,6 @@ "MediaRouter.CastStreaming.Session.Length.AccessCode"; constexpr char kHistogramSessionLengthDesktop[] = "MediaRouter.CastStreaming.Session.Length.Screen"; -constexpr char kHistogramSessionLengthFile[] = - "MediaRouter.CastStreaming.Session.Length.File"; constexpr char kHistogramSessionLengthOffscreenTab[] = "MediaRouter.CastStreaming.Session.Length.OffscreenTab"; constexpr char kHistogramSessionLengthTab[] = @@ -152,7 +150,6 @@ uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 1); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 0); @@ -170,7 +167,6 @@ uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 0); @@ -190,7 +186,6 @@ uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 0); @@ -211,30 +206,11 @@ uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 0); } -TEST_F(MirroringActivityTest, MirrorFile) { - base::HistogramTester uma_recorder; - EXPECT_CALL(media_router_, GetMirroringServiceHostForTab(kTabId, _)); - MediaSource source = MediaSource::ForLocalFile(); - ASSERT_TRUE(source.IsLocalFileSource()); - MakeActivity(source); - - activity_->DidStart(); - activity_.reset(); - - uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 1); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 0); -} - TEST_F(MirroringActivityTest, MirrorAccessCode) { base::HistogramTester uma_recorder; EXPECT_CALL(media_router_, GetMirroringServiceHostForTab(kTabId, _)); @@ -247,7 +223,6 @@ uma_recorder.ExpectTotalCount(kHistogramSessionLength, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthDesktop, 0); - uma_recorder.ExpectTotalCount(kHistogramSessionLengthFile, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthTab, 1); uma_recorder.ExpectTotalCount(kHistogramSessionLengthOffscreenTab, 0); uma_recorder.ExpectTotalCount(kHistogramSessionLengthAccessCode, 1);
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 2743e7a6..a058ba68 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -4587,8 +4587,7 @@ GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), url)); - GetGuestViewManager()->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType(GetGuestViewManager()); // Set a 1s delay to delay MimeHandlerViewGuest's creation to ensure that the // fenced frame is loaded while the PDF stream is not yet consumed. const int creation_delay = TestTimeouts::tiny_timeout().InMilliseconds();
diff --git a/chrome/browser/platform_util_unittest.cc b/chrome/browser/platform_util_unittest.cc index ec364122..d02a17b 100644 --- a/chrome/browser/platform_util_unittest.cc +++ b/chrome/browser/platform_util_unittest.cc
@@ -30,7 +30,6 @@ #include "chrome/browser/extensions/extension_special_storage_policy.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/intent_filter.h" #include "content/public/browser/browser_context.h" #include "content/public/common/content_client.h" @@ -139,18 +138,9 @@ app->intent_filters = apps_util::CreateIntentFiltersForChromeApp(extension.get()); apps.push_back(std::move(app)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - app_service_proxy_->AppRegistryCache().OnApps( - std::move(apps), apps::AppType::kChromeApp, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(apps[0])); - app_service_proxy_->AppRegistryCache().OnApps( - std::move(mojom_apps), apps::mojom::AppType::kChromeApp, - /*should_notify_initialized=*/false); - } + app_service_proxy_->AppRegistryCache().OnApps( + std::move(apps), apps::AppType::kChromeApp, + /*should_notify_initialized=*/false); app_service_test_.WaitForAppService(); }
diff --git a/chrome/browser/policy/BUILD.gn b/chrome/browser/policy/BUILD.gn index 1b43d99..e01bb75 100644 --- a/chrome/browser/policy/BUILD.gn +++ b/chrome/browser/policy/BUILD.gn
@@ -258,7 +258,7 @@ ] } - if (!is_chromeos_ash) { + if (!is_chromeos) { sources += [ "test/variation_restrict_parameter_policy_browsertest.cc" ] deps += [ "//components/variations/service" ] }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 5511a3f5..1a5840eb 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -333,9 +333,6 @@ { key::kBrowserAddPersonEnabled, prefs::kBrowserAddPersonEnabled, base::Value::Type::BOOLEAN }, - { key::kBrowserGuestModeEnforced, - prefs::kBrowserGuestModeEnforced, - base::Value::Type::BOOLEAN }, { key::kBrowserLabsEnabled, chrome_labs_prefs::kBrowserLabsEnabled, base::Value::Type::BOOLEAN }, @@ -722,14 +719,16 @@ { key::kDefaultGeolocationSetting, prefs::kManagedDefaultGeolocationSetting, base::Value::Type::INTEGER }, - #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) +#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) \ + || BUILDFLAG(IS_FUCHSIA) { key::kRequireOnlineRevocationChecksForLocalAnchors, prefs::kCertRevocationCheckingRequiredLocalAnchors, base::Value::Type::BOOLEAN }, { key::kFullscreenAllowed, prefs::kFullscreenAllowed, base::Value::Type::BOOLEAN }, -#endif // #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) +#endif // #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) + // || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA) { key::kAuthSchemes, prefs::kAuthSchemes, base::Value::Type::STRING }, @@ -776,9 +775,6 @@ { key::kAllowedDomainsForApps, prefs::kAllowedDomainsForApps, base::Value::Type::STRING }, - { key::kVariationsRestrictParameter, - variations::prefs::kVariationsRestrictParameter, - base::Value::Type::STRING }, { key::kSSLVersionMin, prefs::kSSLVersionMin, base::Value::Type::STRING }, @@ -814,6 +810,9 @@ { key::kMetricsReportingEnabled, metrics::prefs::kMetricsReportingEnabled, base::Value::Type::BOOLEAN }, + { key::kVariationsRestrictParameter, + variations::prefs::kVariationsRestrictParameter, + base::Value::Type::STRING }, #endif // !BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -1507,6 +1506,9 @@ { key::kAlternativeBrowserParameters, browser_switcher::prefs::kAlternativeBrowserParameters, base::Value::Type::LIST }, + { key::kBrowserGuestModeEnforced, + prefs::kBrowserGuestModeEnforced, + base::Value::Type::BOOLEAN }, { key::kBrowserSwitcherParsingMode, browser_switcher::prefs::kParsingMode, base::Value::Type::INTEGER }, @@ -1642,7 +1644,8 @@ base::Value::Type::BOOLEAN }, #endif // BUILDFLAG(IS_CHROMEOS_ASH) -#if BUILDFLAG(ENABLE_EXTENSIONS) && (BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_FUCHSIA)) +#if BUILDFLAG(ENABLE_EXTENSIONS) && (BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) \ + || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_FUCHSIA)) { key::kChromeAppsEnabled, extensions::pref_names::kChromeAppsEnabled, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/policy/messaging_layer/public/report_client.cc b/chrome/browser/policy/messaging_layer/public/report_client.cc index 0ef0ef49..426d22a 100644 --- a/chrome/browser/policy/messaging_layer/public/report_client.cc +++ b/chrome/browser/policy/messaging_layer/public/report_client.cc
@@ -127,6 +127,7 @@ const bool need_encryption_key_; std::vector<EncryptedRecord> encrypted_records_; ScopedReservation encrypted_records_reservation_; + SEQUENCE_CHECKER(sequence_checker_); UploadCallback upload_callback_; }; @@ -143,12 +144,16 @@ bool need_encryption_key, ReportingClient::Uploader::UploadCallback upload_callback) : need_encryption_key_(need_encryption_key), - upload_callback_(std::move(upload_callback)) {} + upload_callback_(std::move(upload_callback)) { + // Constructor is called on the task assigned by |SequenceBound|. + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} void ReportingClient::Uploader::Helper::ProcessRecord( EncryptedRecord data, ScopedReservation scoped_reservation, base::OnceCallback<void(bool)> processed_cb) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (completed_) { std::move(processed_cb).Run(false); return; @@ -162,6 +167,7 @@ SequenceInformation start, uint64_t count, base::OnceCallback<void(bool)> processed_cb) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (completed_) { std::move(processed_cb).Run(false); return; @@ -175,6 +181,7 @@ } void ReportingClient::Uploader::Helper::Completed(Status final_status) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!final_status.ok()) { // No work to do - something went wrong with storage and it no longer // wants to upload the records. Let the records die with |this|.
diff --git a/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc b/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc index 366471c9..aab94e1 100644 --- a/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc +++ b/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc
@@ -81,10 +81,12 @@ // Set policies before the browser starts up. PolicyMap policies; +#if !BUILDFLAG(IS_CHROMEOS) // Suppress the first-run dialog by disabling metrics reporting. policies.Set(key::kMetricsReportingEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, base::Value(false), nullptr); +#endif // Apply the policy setting under test. if (GetParam() != BooleanPolicy::kNotConfigured) {
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index d904afd..66c6b60a 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -777,6 +777,11 @@ const char kPrivacySandboxApisEnabledV2Init[] = "privacy_sandbox.apis_enabled_v2_init"; +#if BUILDFLAG(ENABLE_EXTENSIONS) +// Deprecated 07/2022. +const char kExtensionToolbar[] = "extensions.toolbar"; +#endif + // Register local state used only for migration (clearing or moving to a new // key). void RegisterLocalStatePrefsForMigration(PrefRegistrySimple* registry) { @@ -1025,6 +1030,11 @@ registry->RegisterBooleanPref(kPrivacySandboxFlocEnabled, true); registry->RegisterBooleanPref(kPrivacySandboxFlocDataAccessibleSince, false); registry->RegisterBooleanPref(kPrivacySandboxApisEnabledV2Init, false); + +#if BUILDFLAG(ENABLE_EXTENSIONS) + // Deprecated 07/2022 + registry->RegisterListPref(kExtensionToolbar); +#endif } } // namespace @@ -2015,6 +2025,11 @@ profile_prefs->ClearPref(kPrivacySandboxFlocDataAccessibleSince); profile_prefs->ClearPref(kPrivacySandboxApisEnabledV2Init); +#if BUILDFLAG(ENABLE_EXTENSIONS) + // Added 07/2022. + profile_prefs->ClearPref(kExtensionToolbar); +#endif + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_PROFILE_PREFS
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 0dbc60e..5d2b360 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -2187,9 +2187,7 @@ #endif // !BUILDFLAG(IS_FUCHSIA) void RenderViewContextMenu::AppendRegionSearchItem() { - // IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4 is the currently launched - // string for the regions search menu item. - int resource_id = IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT4; + int resource_id = IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH; if (lens::features::UseRegionSearchMenuItemAltText1()) { resource_id = IDS_CONTENT_CONTEXT_LENS_REGION_SEARCH_ALT1;
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index 3a43dc9..01005b2 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -439,8 +439,8 @@ WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); // Prepare to load a pdf plugin inside. - test_guest_view_manager_->RegisterTestGuestViewType<MimeHandlerViewGuest>( - base::BindRepeating(&TestMimeHandlerViewGuest::Create)); + TestMimeHandlerViewGuest::RegisterTestGuestViewType( + test_guest_view_manager_); ASSERT_TRUE( content::ExecuteScript(web_contents, "var l = document.getElementById('link1');"
diff --git a/chrome/browser/resources/bookmarks/command_manager.ts b/chrome/browser/resources/bookmarks/command_manager.ts index c966e0dd..ef3a9739 100644 --- a/chrome/browser/resources/bookmarks/command_manager.ts +++ b/chrome/browser/resources/bookmarks/command_manager.ts
@@ -23,7 +23,7 @@ import {getToastManager} from 'chrome://resources/cr_elements/cr_toast/cr_toast_manager.js'; import {assert, assertNotReached} from 'chrome://resources/js/assert_ts.js'; import {isMac} from 'chrome://resources/js/cr.m.js'; -import {KeyboardShortcutList} from 'chrome://resources/js/cr/ui/keyboard_shortcut_list.m.js'; +import {KeyboardShortcutList} from 'chrome://resources/js/cr/ui/keyboard_shortcut_list.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js';
diff --git a/chrome/browser/resources/chromeos/cloud_upload/BUILD.gn b/chrome/browser/resources/chromeos/cloud_upload/BUILD.gn new file mode 100644 index 0000000..23e1e83 --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/BUILD.gn
@@ -0,0 +1,16 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//chrome/browser/resources/tools/build_webui.gni") + +build_webui("build") { + grd_prefix = "cloud_upload" + + static_files = [ "main.html" ] + web_component_files = [ "cloud_upload_dialog.ts" ] + + html_to_wrapper_template = "native" + + ts_deps = [ "//ui/webui/resources:library" ] +}
diff --git a/chrome/browser/resources/chromeos/cloud_upload/OWNERS b/chrome/browser/resources/chromeos/cloud_upload/OWNERS new file mode 100644 index 0000000..73220a8 --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/OWNERS
@@ -0,0 +1 @@ +file://ui/file_manager/OWNERS
diff --git a/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.html b/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.html new file mode 100644 index 0000000..002cec6 --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.html
@@ -0,0 +1,13 @@ +<style> + cr-dialog::part(dialog) { + height: 100%; + } +</style> + +<cr-dialog id="dialog"> + <!-- TODO: Use localized strings --> + <div slot="title">Upload to Drive</div> + <div slot="body"> + Body + </div> +</cr-dialog>
diff --git a/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.ts b/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.ts new file mode 100644 index 0000000..7f0946f --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/cloud_upload_dialog.ts
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {getTemplate} from './cloud_upload_dialog.html.js'; + +/** + * @fileoverview + * 'cloud-upload-dialog' defines the UI for the "Upload to cloud" workflow. + */ + +class CloudUploadDialogElement extends HTMLElement { + constructor() { + super(); + const template = document.createElement('template'); + template.innerHTML = getTemplate() as string; + const fragment = template.content.cloneNode(true); + this.attachShadow({mode: 'open'}).appendChild(fragment); + } +} + +customElements.define('cloud-upload-dialog', CloudUploadDialogElement);
diff --git a/chrome/browser/resources/chromeos/cloud_upload/main.html b/chrome/browser/resources/chromeos/cloud_upload/main.html new file mode 100644 index 0000000..831e4cf --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/main.html
@@ -0,0 +1,18 @@ +<!doctype html> +<html dir="$i18n{textdirection}" lang="$i18n{language}"> + <head> + <meta charset="utf-8"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> + <link rel="stylesheet" + href="chrome://resources/chromeos/colors/cros_styles.css"> + <style> + body { + background-color: var(--cros-bg-color-elevation-3); + } + </style> + <script type="module" src="cloud_upload_dialog.js"></script> + </head> + <body> + <cloud-upload-dialog></cloud-upload-dialog> + </body> +</html> \ No newline at end of file
diff --git a/chrome/browser/resources/chromeos/cloud_upload/tsconfig_base.json b/chrome/browser/resources/chromeos/cloud_upload/tsconfig_base.json new file mode 100644 index 0000000..4874355 --- /dev/null +++ b/chrome/browser/resources/chromeos/cloud_upload/tsconfig_base.json
@@ -0,0 +1,12 @@ +{ + "extends": "../../../../../tools/typescript/tsconfig_base.json", + "compilerOptions": { + "importsNotUsedAsValues": "preserve", + "typeRoots": [ + "../../../../../third_party/node/node_modules/@types" + ], + "types": [ + "trusted-types" + ] + } +}
diff --git a/chrome/browser/resources/chromeos/login/md_login.html b/chrome/browser/resources/chromeos/login/md_login.html index d126082b..9d5dda96 100644 --- a/chrome/browser/resources/chromeos/login/md_login.html +++ b/chrome/browser/resources/chromeos/login/md_login.html
@@ -39,10 +39,6 @@ <script src="chrome://resources/js/cr/ui/list_item.js"></script> <script src="chrome://resources/js/cr/ui/list.js"></script> <script src="chrome://resources/js/cr/ui/grid.js"></script> -<script src="chrome://resources/js/cr/ui/position_util.js"></script> -<script src="chrome://resources/js/cr/ui/menu_item.js"></script> -<script src="chrome://resources/js/cr/ui/menu.js"></script> -<script src="chrome://resources/js/cr/ui/menu_button.js"></script> <script src="chrome://resources/js/promise_resolver.js"></script> <script src="chrome://resources/js/util.js"></script> <script src="chrome://oobe/debug/debug_util.js"></script>
diff --git a/chrome/browser/resources/chromeos/login/menu.js b/chrome/browser/resources/chromeos/login/menu.js new file mode 100644 index 0000000..8068746 --- /dev/null +++ b/chrome/browser/resources/chromeos/login/menu.js
@@ -0,0 +1,405 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// NOTE: This file depends on ui.js (or the autogenerated ui.m.js module +// version). These files and all files that depend on them are deprecated, and +// should only be used by legacy UIs that have not yet been updated to new +// patterns. Use Web Components in any new code. + +cr.define('cr.ui', function() { + /* #ignore */ /** @const */ const MenuItem = cr.ui.MenuItem; + + /** + * Creates a new menu element. Menu dispatches all commands on the element it + * was shown for. + * + * @param {Object=} opt_propertyBag Optional properties. + * @constructor + * @extends {HTMLElement} + */ + /* #export */ const Menu = cr.ui.define('cr-menu'); + + Menu.prototype = { + __proto__: HTMLElement.prototype, + + selectedIndex_: -1, + + /** + * Element for which menu is being shown. + */ + contextElement: null, + + /** + * Initializes the menu element. + */ + decorate() { + this.addEventListener('mouseover', this.handleMouseOver_); + this.addEventListener('mouseout', this.handleMouseOut_); + this.addEventListener('mouseup', this.handleMouseUp_, true); + + this.classList.add('decorated'); + this.setAttribute('role', 'menu'); + this.hidden = true; // Hide the menu by default. + + // Decorate the children as menu items. + const menuItems = this.menuItems; + for (let i = 0, menuItem; menuItem = menuItems[i]; i++) { + cr.ui.decorate(menuItem, MenuItem); + } + }, + + /** + * Adds menu item at the end of the list. + * @param {Object} item Menu item properties. + * @return {!cr.ui.MenuItem} The created menu item. + */ + addMenuItem(item) { + const menuItem = this.ownerDocument.createElement('cr-menu-item'); + this.appendChild(menuItem); + + cr.ui.decorate(menuItem, MenuItem); + + if (item.label) { + menuItem.label = item.label; + } + + if (item.iconUrl) { + menuItem.iconUrl = item.iconUrl; + } + + return menuItem; + }, + + /** + * Adds separator at the end of the list. + */ + addSeparator() { + const separator = this.ownerDocument.createElement('hr'); + cr.ui.decorate(separator, MenuItem); + this.appendChild(separator); + }, + + /** + * Clears menu. + */ + clear() { + this.selectedItem = null; + this.textContent = ''; + }, + + /** + * Walks up the ancestors of |node| until a menu item belonging to this menu + * is found. + * @param {Node} node The node to start searching from. + * @return {cr.ui.MenuItem} The found menu item or null. + * @private + */ + findMenuItem_(node) { + while (node && node.parentNode !== this && !(node instanceof MenuItem)) { + node = node.parentNode; + } + return node ? assertInstanceof(node, MenuItem) : null; + }, + + /** + * Handles mouseover events and selects the hovered item. + * @param {Event} e The mouseover event. + * @private + */ + handleMouseOver_(e) { + const overItem = this.findMenuItem_(/** @type {Element} */ (e.target)); + this.selectedItem = overItem; + }, + + /** + * Handles mouseout events and deselects any selected item. + * @param {Event} e The mouseout event. + * @private + */ + handleMouseOut_(e) { + this.selectedItem = null; + }, + + /** + * If there's a mouseup that happens quickly in about the same position, + * stop it from propagating to items. This is to prevent accidentally + * selecting a menu item that's created under the mouse cursor. + * @param {Event} e A mouseup event on the menu (in capturing phase). + * @private + */ + handleMouseUp_(e) { + assert(this.contains(/** @type {Element} */ (e.target))); + + if (!this.trustEvent_(e) || Date.now() - this.shown_.time > 200) { + return; + } + + const pos = this.shown_.mouseDownPos; + if (!pos || + Math.abs(pos.x - e.screenX) + Math.abs(pos.y - e.screenY) > 4) { + return; + } + + e.preventDefault(); + e.stopPropagation(); + }, + + /** + * @param {!Event} e + * @return {boolean} Whether |e| can be trusted. + * @private + * @suppress {checkTypes} + */ + trustEvent_(e) { + return e.isTrusted || e.isTrustedForTesting; + }, + + get menuItems() { + return this.querySelectorAll(this.menuItemSelector || '*'); + }, + + /** + * The selected menu item or null if none. + * @type {cr.ui.MenuItem} + */ + get selectedItem() { + return this.menuItems[this.selectedIndex]; + }, + set selectedItem(item) { + const index = Array.prototype.indexOf.call(this.menuItems, item); + this.selectedIndex = index; + }, + + /** + * Focuses the selected item. If selectedIndex is invalid, set it to 0 + * first. + */ + focusSelectedItem() { + const items = this.menuItems; + if (this.selectedIndex < 0 || this.selectedIndex > items.length) { + // Find first visible item to focus by default. + for (let idx = 0; idx < items.length; idx++) { + const item = items[idx]; + if (item.hasAttribute('hidden') || item.isSeparator()) { + continue; + } + // If the item is disabled we accept it, but try to find the next + // enabled item, but keeping the first disabled item. + if (!item.disabled) { + this.selectedIndex = idx; + break; + } else if (this.selectedIndex === -1) { + this.selectedIndex = idx; + } + } + } + + if (this.selectedItem) { + this.selectedItem.focus(); + this.setAttribute('aria-activedescendant', this.selectedItem.id); + } + }, + + /** + * Menu length + */ + get length() { + return this.menuItems.length; + }, + + /** + * Returns whether the given menu item is visible. + * @param {!cr.ui.MenuItem} menuItem + * @return {boolean} + * @private + */ + isItemVisible_(menuItem) { + if (menuItem.hidden) { + return false; + } + if (menuItem.offsetParent) { + return true; + } + // A "position: fixed" element won't have an offsetParent, so we have to + // do the full style computation. + return window.getComputedStyle(menuItem).display !== 'none'; + }, + + /** + * Returns whether the menu has any visible items. + * @return {boolean} True if the menu has visible item. Otherwise, false. + */ + hasVisibleItems() { + // Inspect items in reverse order to determine if the separator above each + // set of items is required. + for (const menuItem of this.menuItems) { + if (this.isItemVisible_(menuItem)) { + return true; + } + } + return false; + }, + + /** + * This is the function that handles keyboard navigation. This is usually + * called by the element responsible for managing the menu. + * @param {Event} e The keydown event object. + * @return {boolean} Whether the event was handled be the menu. + */ + handleKeyDown(e) { + let item = this.selectedItem; + + const self = this; + const selectNextAvailable = function(m) { + const menuItems = self.menuItems; + const len = menuItems.length; + if (!len) { + // Edge case when there are no items. + return; + } + let i = self.selectedIndex; + if (i === -1 && m === -1) { + // Edge case when needed to go the last item first. + i = 0; + } + + // "i" may be negative(-1), so modulus operation and cycle below + // wouldn't work as assumed. This trick makes startPosition positive + // without altering it's modulo. + const startPosition = (i + len) % len; + + while (true) { + i = (i + m + len) % len; + + // Check not to enter into infinite loop if all items are hidden or + // disabled. + if (i === startPosition) { + break; + } + + item = menuItems[i]; + if (item && !item.isSeparator() && !item.disabled && + this.isItemVisible_(item)) { + break; + } + } + if (item && !item.disabled) { + self.selectedIndex = i; + } + }.bind(this); + + switch (e.key) { + case 'ArrowDown': + selectNextAvailable(1); + this.focusSelectedItem(); + return true; + case 'ArrowUp': + selectNextAvailable(-1); + this.focusSelectedItem(); + return true; + case 'Enter': + case ' ': + if (item) { + // Store |contextElement| since it'll be removed when handling the + // 'activate' event. + const contextElement = this.contextElement; + const activationEvent = document.createEvent('Event'); + activationEvent.initEvent('activate', true, true); + activationEvent.originalEvent = e; + if (item.dispatchEvent(activationEvent)) { + if (item.command) { + item.command.execute(contextElement); + } + } + } + return true; + } + + return false; + }, + + hide() { + this.hidden = true; + delete this.shown_; + }, + + /** @param {{x: number, y: number}=} opt_mouseDownPos */ + show(opt_mouseDownPos) { + this.shown_ = {mouseDownPos: opt_mouseDownPos, time: Date.now()}; + this.hidden = false; + }, + + /** + * Updates menu items command according to context. + * @param {Node=} node Node for which to actuate commands state. + */ + updateCommands(node) { + const menuItems = this.menuItems; + + for (const menuItem of menuItems) { + if (!menuItem.isSeparator()) { + menuItem.updateCommand(node); + } + } + + let separatorRequired = false; + let lastSeparator = null; + // Hide any separators without a visible item between them and the next + // separator or the end of the menu. + for (const menuItem of menuItems) { + if (menuItem.isSeparator()) { + if (separatorRequired) { + lastSeparator = menuItem; + } + menuItem.hidden = true; + separatorRequired = false; + continue; + } + if (this.isItemVisible_(menuItem)) { + if (lastSeparator) { + lastSeparator.hidden = false; + } + separatorRequired = true; + } + } + }, + }; + + /** @suppress {globalThis} This standalone function is used like method. */ + function selectedIndexChanged(selectedIndex, oldSelectedIndex) { + const oldSelectedItem = this.menuItems[oldSelectedIndex]; + if (oldSelectedItem) { + oldSelectedItem.selected = false; + oldSelectedItem.blur(); + } + const item = this.selectedItem; + if (item) { + item.selected = true; + } + } + + /** + * The selected menu item. + * @type {number} + */ + Menu.prototype.selectedIndex; + Object.defineProperty( + Menu.prototype, 'selectedIndex', + cr.getPropertyDescriptor( + 'selectedIndex', cr.PropertyKind.JS, selectedIndexChanged)); + + /** + * Selector for children which are menu items. + * @type {string} + */ + Menu.prototype.menuItemSelector; + Object.defineProperty( + Menu.prototype, 'menuItemSelector', + cr.getPropertyDescriptor('menuItemSelector', cr.PropertyKind.ATTR)); + + // Export + // #cr_define_end + console.warn('crbug/1173575, non-JS module files deprecated.'); + return {Menu: Menu}; +});
diff --git a/chrome/browser/resources/chromeos/login/menu_button.js b/chrome/browser/resources/chromeos/login/menu_button.js new file mode 100644 index 0000000..d2ea9d7 --- /dev/null +++ b/chrome/browser/resources/chromeos/login/menu_button.js
@@ -0,0 +1,356 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// NOTE: This file depends on ui.js (or the autogenerated ui.m.js module +// version). These files and all files that depend on them are deprecated, and +// should only be used by legacy UIs that have not yet been updated to new +// patterns. Use Web Components in any new code. + +cr.define('cr.ui', function() { + /* #ignore */ const Menu = cr.ui.Menu; + + /** + * Enum for type of hide. Delayed is used when called by clicking on a + * checkable menu item. + * @enum {number} + */ + /* #export */ const HideType = { + INSTANT: 0, + DELAYED: 1, + }; + + /** @const */ + /* #ignore */ const positionPopupAroundElement = + /* #ignore */ cr.ui.positionPopupAroundElement; + + /** + * Creates a new menu button element. + * @param {Object=} opt_propertyBag Optional properties. + * @constructor + * @extends {HTMLButtonElement} + * @implements {EventListener} + */ + /* #export */ const MenuButton = cr.ui.define('button'); + + MenuButton.prototype = { + __proto__: HTMLButtonElement.prototype, + + /** + * Initializes the menu button. + */ + decorate() { + // Listen to the touch events on the document so that we can handle it + // before cancelled by other UI components. + this.ownerDocument.addEventListener('touchstart', this); + this.addEventListener('mousedown', this); + this.addEventListener('keydown', this); + this.addEventListener('dblclick', this); + this.addEventListener('blur', this); + + // Adding the 'custom-appearance' class prevents widgets.css from changing + // the appearance of this element. + this.classList.add('custom-appearance'); + this.classList.add('menu-button'); // For styles in menu_button.css. + + let menu; + if ((menu = this.getAttribute('menu'))) { + this.menu = menu; + } + + // An event tracker for events we only connect to while the menu is + // displayed. + this.showingEvents_ = new cr.EventTracker(); + + this.anchorType = cr.ui.AnchorType.BELOW; + this.invertLeftRight = false; + }, + + /** + * The menu associated with the menu button. + * @type {cr.ui.Menu} + */ + get menu() { + return this.menu_; + }, + set menu(menu) { + if (typeof menu === 'string' && menu[0] === '#') { + menu = assert(this.ownerDocument.getElementById(menu.slice(1))); + cr.ui.decorate(menu, Menu); + } + + this.menu_ = menu; + if (menu) { + if (menu.id) { + this.setAttribute('menu', '#' + menu.id); + } + } + }, + + /** + * Whether to show the menu on press of the Up or Down arrow keys. + */ + respondToArrowKeys: true, + + /** + * Checks if the menu should be closed based on the target of a mouse click + * or a touch event target. + * @param {Event} e The event object. + * @return {boolean} + * @private + */ + shouldDismissMenu_(e) { + // The menu is dismissed when clicking outside the menu. + // The button is excluded here because it should toggle show/hide the + // menu and handled separately. + return e.target instanceof Node && !this.contains(e.target) && + !this.menu.contains(e.target); + }, + + /** + * Handles event callbacks. + * @param {Event} e The event object. + */ + handleEvent(e) { + if (!this.menu) { + return; + } + + switch (e.type) { + case 'touchstart': + // Touch on the menu button itself is ignored to avoid that the menu + // opened again by the mousedown event following the touch events. + if (this.shouldDismissMenu_(e)) { + this.hideMenuWithoutTakingFocus_(); + } + break; + case 'mousedown': + if (e.currentTarget === this.ownerDocument) { + if (this.shouldDismissMenu_(e)) { + this.hideMenuWithoutTakingFocus_(); + } else { + e.preventDefault(); + } + } else { + if (this.isMenuShown()) { + this.hideMenuWithoutTakingFocus_(); + } else if (e.button === 0) { // Only show the menu when using left + // mouse button. + this.showMenu(false, {x: e.screenX, y: e.screenY}); + + // Prevent the button from stealing focus on mousedown. + e.preventDefault(); + } + } + + // Hide the focus ring on mouse click. + this.classList.add('using-mouse'); + break; + case 'keydown': + this.handleKeyDown(e); + // If the menu is visible we let it handle all the keyboard events. + if (this.isMenuShown() && e.currentTarget === this.ownerDocument) { + this.menu.handleKeyDown(e); + e.preventDefault(); + e.stopPropagation(); + } + + // Show the focus ring on keypress. + this.classList.remove('using-mouse'); + break; + case 'focus': + if (this.shouldDismissMenu_(e)) { + this.hideMenu(); + // Show the focus ring on focus - if it's come from a mouse event, + // the focus ring will be hidden in the mousedown event handler, + // executed after this. + this.classList.remove('using-mouse'); + } + break; + case 'blur': + // No need to hide the focus ring anymore, without having focus. + this.classList.remove('using-mouse'); + break; + case 'activate': + const hideDelayed = + e.target instanceof cr.ui.MenuItem && e.target.checkable; + const hideType = hideDelayed ? HideType.DELAYED : HideType.INSTANT; + if (e.originalEvent instanceof MouseEvent || + e.originalEvent instanceof TouchEvent) { + this.hideMenuWithoutTakingFocus_(hideType); + } else { + // Keyboard. Take focus to continue keyboard operation. + this.hideMenu(hideType); + } + break; + case 'scroll': + if (!(e.target === this.menu || this.menu.contains(e.target))) { + this.hideMenu(); + } + break; + case 'popstate': + case 'resize': + this.hideMenu(); + break; + case 'contextmenu': + if ((!this.menu || !this.menu.contains(e.target)) && + (!this.hideTimestamp_ || Date.now() - this.hideTimestamp_ > 50)) { + this.showMenu(true, {x: e.screenX, y: e.screenY}); + } + e.preventDefault(); + // Don't allow elements further up in the DOM to show their menus. + e.stopPropagation(); + break; + case 'dblclick': + // Don't allow double click events to propagate. + e.preventDefault(); + e.stopPropagation(); + break; + } + }, + + /** + * Shows the menu. + * @param {boolean} shouldSetFocus Whether to set focus on the + * selected menu item. + * @param {{x: number, y: number}=} opt_mousePos The position of the mouse + * when shown (in screen coordinates). + */ + showMenu(shouldSetFocus, opt_mousePos) { + this.hideMenu(); + + this.menu.updateCommands(this); + + const event = new UIEvent( + 'menushow', {bubbles: true, cancelable: true, view: window}); + if (!this.dispatchEvent(event)) { + return; + } + + this.menu.show(opt_mousePos); + + this.setAttribute('menu-shown', ''); + + // When the menu is shown we steal all keyboard events. + const doc = this.ownerDocument; + const win = doc.defaultView; + this.showingEvents_.add(doc, 'keydown', this, true); + this.showingEvents_.add(doc, 'mousedown', this, true); + this.showingEvents_.add(doc, 'focus', this, true); + this.showingEvents_.add(doc, 'scroll', this, true); + this.showingEvents_.add(win, 'popstate', this); + this.showingEvents_.add(win, 'resize', this); + this.showingEvents_.add(this.menu, 'contextmenu', this); + this.showingEvents_.add(this.menu, 'activate', this); + this.positionMenu_(); + + if (shouldSetFocus) { + this.menu.focusSelectedItem(); + } + }, + + /** + * Hides the menu. If your menu can go out of scope, make sure to call this + * first. + * @param {cr.ui.HideType=} opt_hideType Type of hide. + * default: cr.ui.HideType.INSTANT. + */ + hideMenu(opt_hideType) { + this.hideMenuInternal_(true, opt_hideType); + }, + + /** + * Hides the menu. If your menu can go out of scope, make sure to call this + * first. + * @param {cr.ui.HideType=} opt_hideType Type of hide. + * default: cr.ui.HideType.INSTANT. + */ + hideMenuWithoutTakingFocus_(opt_hideType) { + this.hideMenuInternal_(false, opt_hideType); + }, + + /** + * Hides the menu. If your menu can go out of scope, make sure to call this + * first. + * @param {boolean} shouldTakeFocus Moves the focus to the button if true. + * @param {cr.ui.HideType=} opt_hideType Type of hide. + * default: cr.ui.HideType.INSTANT. + */ + hideMenuInternal_(shouldTakeFocus, opt_hideType) { + if (!this.isMenuShown()) { + return; + } + + this.removeAttribute('menu-shown'); + if (opt_hideType === HideType.DELAYED) { + this.menu.classList.add('hide-delayed'); + } else { + this.menu.classList.remove('hide-delayed'); + } + this.menu.hide(); + + this.showingEvents_.removeAll(); + if (shouldTakeFocus) { + this.focus(); + } + + const event = new UIEvent( + 'menuhide', {bubbles: true, cancelable: false, view: window}); + this.dispatchEvent(event); + + // On windows we might hide the menu in a right mouse button up and if + // that is the case we wait some short period before we allow the menu + // to be shown again. + this.hideTimestamp_ = cr.isWindows ? Date.now() : 0; + }, + + /** + * Whether the menu is shown. + */ + isMenuShown() { + return this.hasAttribute('menu-shown'); + }, + + /** + * Positions the menu below the menu button. At this point we do not use any + * advanced positioning logic to ensure the menu fits in the viewport. + * @private + */ + positionMenu_() { + positionPopupAroundElement( + this, this.menu, this.anchorType, this.invertLeftRight); + }, + + /** + * Handles the keydown event for the menu button. + */ + handleKeyDown(e) { + switch (e.key) { + case 'ArrowDown': + case 'ArrowUp': + if (!this.respondToArrowKeys) { + break; + } + case 'Enter': + case ' ': + if (!this.isMenuShown()) { + this.showMenu(true); + } + e.preventDefault(); + break; + case 'Escape': + case 'Tab': + this.hideMenu(); + break; + } + }, + }; + + // Export + // #cr_define_end + console.warn('crbug/1173575, non-JS module files deprecated.'); + return { + HideType: HideType, + MenuButton: MenuButton, + }; +});
diff --git a/chrome/browser/resources/chromeos/login/menu_item.js b/chrome/browser/resources/chromeos/login/menu_item.js new file mode 100644 index 0000000..5a1ccda7 --- /dev/null +++ b/chrome/browser/resources/chromeos/login/menu_item.js
@@ -0,0 +1,307 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// NOTE: This file depends on ui.js (or the autogenerated ui.m.js module +// version). These files and all files that depend on them are deprecated, and +// should only be used by legacy UIs that have not yet been updated to new +// patterns. Use Web Components in any new code. + +cr.define('cr.ui', function() { + /* #ignore */ const Command = cr.ui.Command; + + /** + * Creates a new menu item element. + * @param {Object=} opt_propertyBag Optional properties. + * @constructor + * @extends {HTMLElement} + * @implements {EventListener} + */ + /* #export */ const MenuItem = cr.ui.define('cr-menu-item'); + + /** + * Creates a new menu separator element. + * @return {!cr.ui.MenuItem} The new separator element. + */ + MenuItem.createSeparator = function() { + const el = /** @type {!cr.ui.MenuItem} */ (document.createElement('hr')); + if (MenuItem.decorate) { + MenuItem.decorate(el); + } + return el; + }; + + MenuItem.prototype = { + __proto__: HTMLElement.prototype, + + /** + * Initializes the menu item. + */ + decorate() { + let commandId; + if ((commandId = this.getAttribute('command'))) { + this.command = commandId; + } + + this.addEventListener('mouseup', this.handleMouseUp_); + + // Adding the 'custom-appearance' class prevents widgets.css from changing + // the appearance of this element. + this.classList.add('custom-appearance'); + + // Enable Text to Speech on the menu. Additionally, ID has to be set, + // since it is used in element's aria-activedescendant attribute. + if (!this.isSeparator()) { + this.setAttribute('role', 'menuitem'); + this.setAttribute('tabindex', this.getAttribute('tabindex') || -1); + } + + let iconUrl; + if ((iconUrl = this.getAttribute('icon'))) { + this.iconUrl = iconUrl; + } + }, + + /** + * The command associated with this menu item. If this is set to a string + * of the form "#element-id" then the element is looked up in the document + * of the command. + * @type {cr.ui.Command} + */ + command_: null, + get command() { + return this.command_; + }, + set command(command) { + if (this.command_) { + this.command_.removeEventListener('labelChange', this); + this.command_.removeEventListener('disabledChange', this); + this.command_.removeEventListener('hiddenChange', this); + this.command_.removeEventListener('checkedChange', this); + } + + if (typeof command === 'string' && command[0] === '#') { + command = assert(this.ownerDocument.body.querySelector(command)); + cr.ui.decorate(command, Command); + } + + this.command_ = command; + if (command) { + if (command.id) { + this.setAttribute('command', '#' + command.id); + } + + if (typeof command.label === 'string') { + this.label = command.label; + } + this.disabled = command.disabled; + this.hidden = command.hidden; + this.checked = command.checked; + + this.command_.addEventListener('labelChange', this); + this.command_.addEventListener('disabledChange', this); + this.command_.addEventListener('hiddenChange', this); + this.command_.addEventListener('checkedChange', this); + } + + this.updateShortcut_(); + }, + + /** + * The text label. + * @type {string} + */ + get label() { + return this.textContent; + }, + set label(label) { + this.textContent = label; + }, + + /** + * Menu icon. + * @type {string} + */ + get iconUrl() { + return this.style.backgroundImage; + }, + set iconUrl(url) { + this.style.backgroundImage = 'url(' + url + ')'; + }, + + /** + * @return {boolean} Whether the menu item is a separator. + */ + isSeparator() { + return this.tagName === 'HR'; + }, + + /** + * Updates shortcut text according to associated command. If command has + * multiple shortcuts, only first one is displayed. + */ + updateShortcut_() { + this.removeAttribute('shortcutText'); + + if (!this.command_ || !this.command_.shortcut || + this.command_.hideShortcutText) { + return; + } + + const shortcuts = this.command_.shortcut.split(/\s+/); + + if (shortcuts.length === 0) { + return; + } + + const shortcut = shortcuts[0]; + const mods = {}; + let ident = ''; + shortcut.split('|').forEach(function(part) { + const partUc = part.toUpperCase(); + switch (partUc) { + case 'CTRL': + case 'ALT': + case 'SHIFT': + case 'META': + mods[partUc] = true; + break; + default: + console.assert(!ident, 'Shortcut has two non-modifier keys'); + ident = part; + } + }); + + let shortcutText = ''; + + ['CTRL', 'ALT', 'SHIFT', 'META'].forEach(function(mod) { + if (mods[mod]) { + shortcutText += loadTimeData.getString('SHORTCUT_' + mod) + '+'; + } + }); + + if (ident === ' ') { + ident = 'Space'; + } + + if (ident.length !== 1) { + shortcutText += + loadTimeData.getString('SHORTCUT_' + ident.toUpperCase()); + } else { + shortcutText += ident.toUpperCase(); + } + + this.setAttribute('shortcutText', shortcutText); + }, + + /** + * Handles mouseup events. This dispatches an activate event; if there is an + * associated command, that command is executed. + * @param {!Event} e The mouseup event object. + * @private + */ + handleMouseUp_(e) { + e = /** @type {!MouseEvent} */ (e); + // Only dispatch an activate event for left or middle click. + if (e.button > 1) { + return; + } + + if (!this.disabled && !this.isSeparator() && this.selected) { + // Store |contextElement| since it'll be removed by {Menu} on handling + // 'activate' event. + const contextElement = + /** @type {{contextElement: Element}} */ (this.parentNode) + .contextElement; + const activationEvent = document.createEvent('Event'); + activationEvent.initEvent('activate', true, true); + activationEvent.originalEvent = e; + // Dispatch command event followed by executing the command object. + if (this.dispatchEvent(activationEvent)) { + const command = this.command; + if (command) { + command.execute(contextElement); + cr.ui.swallowDoubleClick(e); + } + } + } + }, + + /** + * Updates command according to the node on which this menu was invoked. + * @param {Node=} opt_node Node on which menu was opened. + */ + updateCommand(opt_node) { + if (this.command_) { + this.command_.canExecuteChange(opt_node); + } + }, + + /** + * Handles changes to the associated command. + * @param {Event} e The event object. + */ + handleEvent(e) { + switch (e.type) { + case 'disabledChange': + this.disabled = this.command.disabled; + break; + case 'hiddenChange': + this.hidden = this.command.hidden; + break; + case 'labelChange': + this.label = this.command.label; + break; + case 'checkedChange': + this.checked = this.command.checked; + break; + } + }, + }; + /** + * Whether the menu item is disabled or not. + * @type {boolean} + */ + MenuItem.prototype.disabled; + Object.defineProperty( + MenuItem.prototype, 'disabled', + cr.getPropertyDescriptor('disabled', cr.PropertyKind.BOOL_ATTR)); + + /** + * Whether the menu item is hidden or not. + */ + Object.defineProperty( + MenuItem.prototype, 'hidden', + cr.getPropertyDescriptor('hidden', cr.PropertyKind.BOOL_ATTR)); + + /** + * Whether the menu item is selected or not. + * @type {boolean} + */ + MenuItem.prototype.selected; + Object.defineProperty( + MenuItem.prototype, 'selected', + cr.getPropertyDescriptor('selected', cr.PropertyKind.BOOL_ATTR)); + + /** + * Whether the menu item is checked or not. + * @type {boolean} + */ + MenuItem.prototype.checked; + Object.defineProperty( + MenuItem.prototype, 'checked', + cr.getPropertyDescriptor('checked', cr.PropertyKind.BOOL_ATTR)); + + /** + * Whether the menu item is checkable or not. + * @type {boolean} + */ + MenuItem.prototype.checkable; + Object.defineProperty( + MenuItem.prototype, 'checkable', + cr.getPropertyDescriptor('checkable', cr.PropertyKind.BOOL_ATTR)); + + // Export + // #cr_define_end + return {MenuItem: MenuItem}; +});
diff --git a/chrome/browser/resources/chromeos/login/oobe.html b/chrome/browser/resources/chromeos/login/oobe.html index d7d2633..0e3f2b2 100644 --- a/chrome/browser/resources/chromeos/login/oobe.html +++ b/chrome/browser/resources/chromeos/login/oobe.html
@@ -42,10 +42,6 @@ <script src="chrome://resources/js/cr/ui/list_item.js"></script> <script src="chrome://resources/js/cr/ui/list.js"></script> <script src="chrome://resources/js/cr/ui/grid.js"></script> -<script src="chrome://resources/js/cr/ui/position_util.js"></script> -<script src="chrome://resources/js/cr/ui/menu_item.js"></script> -<script src="chrome://resources/js/cr/ui/menu.js"></script> -<script src="chrome://resources/js/cr/ui/menu_button.js"></script> <script src="chrome://resources/js/promise_resolver.js"></script> <script src="chrome://resources/js/util.js"></script> <script src="chrome://oobe/debug/debug_util.js"></script>
diff --git a/chrome/browser/resources/chromeos/login/oobe.js b/chrome/browser/resources/chromeos/login/oobe.js index 56cdd46..f05493c 100644 --- a/chrome/browser/resources/chromeos/login/oobe.js +++ b/chrome/browser/resources/chromeos/login/oobe.js
@@ -7,6 +7,10 @@ * This is the main code for the OOBE WebUI implementation. */ +// <include src="position_util.js"> +// <include src="menu_item.js"> +// <include src="menu.js"> +// <include src="menu_button.js"> // <include src="components/display_manager_types.js"> // <include src="components/oobe_types.js"> // <include src="display_manager.js">
diff --git a/chrome/browser/resources/chromeos/login/position_util.js b/chrome/browser/resources/chromeos/login/position_util.js new file mode 100644 index 0000000..453944b5 --- /dev/null +++ b/chrome/browser/resources/chromeos/login/position_util.js
@@ -0,0 +1,248 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview This file provides utility functions for position popups. + */ + +cr.define('cr.ui', function() { + /** + * Type def for rects as returned by getBoundingClientRect. + * @typedef {{left: number, top: number, width: number, height: number, + * right: number, bottom: number}} + */ + let Rect; + + /** + * Enum for defining how to anchor a popup to an anchor element. + * @enum {number} + */ + /* #export */ const AnchorType = { + /** + * The popup's right edge is aligned with the left edge of the anchor. + * The popup's top edge is aligned with the top edge of the anchor. + */ + BEFORE: 1, // p: right, a: left, p: top, a: top + + /** + * The popop's left edge is aligned with the right edge of the anchor. + * The popup's top edge is aligned with the top edge of the anchor. + */ + AFTER: 2, // p: left a: right, p: top, a: top + + /** + * The popop's bottom edge is aligned with the top edge of the anchor. + * The popup's left edge is aligned with the left edge of the anchor. + */ + ABOVE: 3, // p: bottom, a: top, p: left, a: left + + /** + * The popop's top edge is aligned with the bottom edge of the anchor. + * The popup's left edge is aligned with the left edge of the anchor. + */ + BELOW: 4, // p: top, a: bottom, p: left, a: left + }; + + /** + * Helper function for positionPopupAroundElement and positionPopupAroundRect. + * @param {!Rect} anchorRect The rect for the anchor. + * @param {!HTMLElement} popupElement The element used for the popup. + * @param {cr.ui.AnchorType} type The type of anchoring to do. + * @param {boolean=} opt_invertLeftRight Whether to invert the right/left + * alignment. + */ + function positionPopupAroundRect( + anchorRect, popupElement, type, opt_invertLeftRight) { + const popupRect = popupElement.getBoundingClientRect(); + let availRect; + const ownerDoc = popupElement.ownerDocument; + const cs = ownerDoc.defaultView.getComputedStyle(popupElement); + const docElement = ownerDoc.documentElement; + + if (cs.position === 'fixed') { + // For 'fixed' positioned popups, the available rectangle should be based + // on the viewport rather than the document. + availRect = { + height: docElement.clientHeight, + width: docElement.clientWidth, + top: 0, + bottom: docElement.clientHeight, + left: 0, + right: docElement.clientWidth, + }; + } else { + availRect = popupElement.offsetParent.getBoundingClientRect(); + } + + if (cs.direction === 'rtl') { + opt_invertLeftRight = !opt_invertLeftRight; + } + + // Flip BEFORE, AFTER based on alignment. + if (opt_invertLeftRight) { + if (type === AnchorType.BEFORE) { + type = AnchorType.AFTER; + } else if (type === AnchorType.AFTER) { + type = AnchorType.BEFORE; + } + } + + // Flip type based on available size + switch (type) { + case AnchorType.BELOW: + if (anchorRect.bottom + popupRect.height > availRect.height && + popupRect.height <= anchorRect.top) { + type = AnchorType.ABOVE; + } + break; + case AnchorType.ABOVE: + if (popupRect.height > anchorRect.top && + anchorRect.bottom + popupRect.height <= availRect.height) { + type = AnchorType.BELOW; + } + break; + case AnchorType.AFTER: + if (anchorRect.right + popupRect.width > availRect.width && + popupRect.width <= anchorRect.left) { + type = AnchorType.BEFORE; + } + break; + case AnchorType.BEFORE: + if (popupRect.width > anchorRect.left && + anchorRect.right + popupRect.width <= availRect.width) { + type = AnchorType.AFTER; + } + break; + } + // flipping done + + const style = popupElement.style; + // Reset all directions. + style.left = style.right = style.top = style.bottom = 'auto'; + + // Primary direction + switch (type) { + case AnchorType.BELOW: + if (anchorRect.bottom + popupRect.height <= availRect.height) { + style.top = anchorRect.bottom + 'px'; + } else { + style.bottom = '0'; + } + break; + case AnchorType.ABOVE: + if (availRect.height - anchorRect.top >= 0) { + style.bottom = availRect.height - anchorRect.top + 'px'; + } else { + style.top = '0'; + } + break; + case AnchorType.AFTER: + if (anchorRect.right + popupRect.width <= availRect.width) { + style.left = anchorRect.right + 'px'; + } else { + style.right = '0'; + } + break; + case AnchorType.BEFORE: + if (availRect.width - anchorRect.left >= 0) { + style.right = availRect.width - anchorRect.left + 'px'; + } else { + style.left = '0'; + } + break; + } + + // Secondary direction + switch (type) { + case AnchorType.BELOW: + case AnchorType.ABOVE: + if (opt_invertLeftRight) { + // align right edges + if (anchorRect.right - popupRect.width >= 0) { + style.right = availRect.width - anchorRect.right + 'px'; + + // align left edges + } else if (anchorRect.left + popupRect.width <= availRect.width) { + style.left = anchorRect.left + 'px'; + + // not enough room on either side + } else { + style.right = '0'; + } + } else { + // align left edges + if (anchorRect.left + popupRect.width <= availRect.width) { + style.left = anchorRect.left + 'px'; + + // align right edges + } else if (anchorRect.right - popupRect.width >= 0) { + style.right = availRect.width - anchorRect.right + 'px'; + + // not enough room on either side + } else { + style.left = '0'; + } + } + break; + + case AnchorType.AFTER: + case AnchorType.BEFORE: + // align top edges + if (anchorRect.top + popupRect.height <= availRect.height) { + style.top = anchorRect.top + 'px'; + + // align bottom edges + } else if (anchorRect.bottom - popupRect.height >= 0) { + style.bottom = availRect.height - anchorRect.bottom + 'px'; + + // not enough room on either side + } else { + style.top = '0'; + } + break; + } + } + + /** + * Positions a popup element relative to an anchor element. The popup element + * should have position set to absolute and it should be a child of the body + * element. + * @param {!HTMLElement} anchorElement The element that the popup is anchored + * to. + * @param {!HTMLElement} popupElement The popup element we are positioning. + * @param {cr.ui.AnchorType} type The type of anchoring we want. + * @param {boolean=} opt_invertLeftRight Whether to invert the right/left + * alignment. + */ + /* #export */ function positionPopupAroundElement( + anchorElement, popupElement, type, opt_invertLeftRight) { + const anchorRect = anchorElement.getBoundingClientRect(); + positionPopupAroundRect( + anchorRect, popupElement, type, !!opt_invertLeftRight); + } + + /** + * Positions a popup around a point. + * @param {number} x The client x position. + * @param {number} y The client y position. + * @param {!HTMLElement} popupElement The popup element we are positioning. + * @param {cr.ui.AnchorType=} opt_anchorType The type of anchoring we want. + */ + /* #export */ function positionPopupAtPoint( + x, y, popupElement, opt_anchorType) { + const rect = {left: x, top: y, width: 0, height: 0, right: x, bottom: y}; + + const anchorType = opt_anchorType || AnchorType.BELOW; + positionPopupAroundRect(rect, popupElement, anchorType); + } + + // Export + // #cr_define_end + console.warn('crbug/1173575, non-JS module files deprecated.'); + return { + AnchorType: AnchorType, + positionPopupAroundElement: positionPopupAroundElement, + positionPopupAtPoint: positionPopupAtPoint, + }; +});
diff --git a/chrome/browser/resources/ntp4/apps_page.js b/chrome/browser/resources/ntp4/apps_page.js index e8eb93b..78f8043f 100644 --- a/chrome/browser/resources/ntp4/apps_page.js +++ b/chrome/browser/resources/ntp4/apps_page.js
@@ -5,9 +5,9 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {addSingletonGetter} from 'chrome://resources/js/cr.m.js'; import {decorate, toCssPx} from 'chrome://resources/js/cr/ui.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {$, appendParam, findAncestorByClass} from 'chrome://resources/js/util.m.js';
diff --git a/chrome/browser/resources/settings/chromeos/os_a11y_page/os_a11y_page.html b/chrome/browser/resources/settings/chromeos/os_a11y_page/os_a11y_page.html index 48140f8b..a7ab4fa 100644 --- a/chrome/browser/resources/settings/chromeos/os_a11y_page/os_a11y_page.html +++ b/chrome/browser/resources/settings/chromeos/os_a11y_page/os_a11y_page.html
@@ -29,24 +29,28 @@ sub-label="$i18n{textToSpeechLinkDescription}" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> + <div class="hr"></div> <cr-link-row id="display-and-magnification-page-trigger" label="$i18n{displayAndMagnificationLinkTitle}" on-click="onDisplayAndMagnificationTap_" sub-label="$i18n{displayAndMagnificationLinkDescription}" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> + <div class="hr"></div> <cr-link-row id="keyboard-and-text-input-page-trigger" label="$i18n{keyboardAndTextInputLinkTitle}" on-click="onKeyboardAndTextInputTap_" sub-label="$i18n{keyboardAndTextInputLinkDescription}" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> + <div class="hr"></div> <cr-link-row id="cursor-and-touchpad-page-trigger" label="$i18n{cursorAndTouchpadLinkTitle}" on-click="onCursorAndTouchpadTap_" sub-label="$i18n{cursorAndTouchpadLinkDescription}" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> + <div class="hr"></div> <cr-link-row id="audio-and-captions-page-trigger" label="$i18n{audioAndCaptionsLinkTitle}" on-click="onAudioAndCaptionsTap_"
diff --git a/chrome/browser/search_resumption/java/res/layout/search_resumption_module_layout.xml b/chrome/browser/search_resumption/java/res/layout/search_resumption_module_layout.xml index 8093a57b..a8520fc5 100644 --- a/chrome/browser/search_resumption/java/res/layout/search_resumption_module_layout.xml +++ b/chrome/browser/search_resumption/java/res/layout/search_resumption_module_layout.xml
@@ -57,7 +57,8 @@ android:layout_alignParentEnd="true" android:layout_centerVertical="true" android:contentDescription="@string/DefaultSearchProviderSuggestURLDesc" - android:src="@drawable/ic_expand_less_black_24dp"/> + android:src="@drawable/ic_expand_less_black_24dp" + app:tint="@color/default_icon_color_tint_list"/> </RelativeLayout> <org.chromium.chrome.browser.search_resumption.SearchResumptionTileContainerView
diff --git a/chrome/browser/search_resumption/java/src/org/chromium/chrome/browser/search_resumption/SearchResumptionModuleView.java b/chrome/browser/search_resumption/java/src/org/chromium/chrome/browser/search_resumption/SearchResumptionModuleView.java index 1587531e..2b5ef850 100644 --- a/chrome/browser/search_resumption/java/src/org/chromium/chrome/browser/search_resumption/SearchResumptionModuleView.java +++ b/chrome/browser/search_resumption/java/src/org/chromium/chrome/browser/search_resumption/SearchResumptionModuleView.java
@@ -65,6 +65,13 @@ } else { mOptionView.setImageResource(org.chromium.ui.R.drawable.ic_expand_more_black_24dp); } + + String collapseOrExpandedText = getContext().getResources().getString( + shouldExpand ? R.string.accessibility_expanded : R.string.accessibility_collapsed); + String description = getContext().getResources().getString( + R.string.search_resumption_module_title_short); + mHeaderView.setContentDescription(description + collapseOrExpandedText); + mTileContainerView.configureExpandedCollapsed(shouldExpand, isAnimationEnabled); } }
diff --git a/chrome/browser/secure_origin_allowlist_browsertest.cc b/chrome/browser/secure_origin_allowlist_browsertest.cc index fba40dd40..22107f9 100644 --- a/chrome/browser/secure_origin_allowlist_browsertest.cc +++ b/chrome/browser/secure_origin_allowlist_browsertest.cc
@@ -91,6 +91,7 @@ } policy::PolicyMap values; +#if !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) values.Set((variant == TestVariant::kPolicyOld || variant == TestVariant::kPolicyOldAndNew) ? policy::key::kUnsafelyTreatInsecureOriginAsSecure @@ -104,6 +105,11 @@ policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, std::move(other_urls), nullptr); } +#else + values.Set(policy::key::kOverrideSecurityRestrictionsOnInsecureOrigin, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, + policy::POLICY_SOURCE_CLOUD, std::move(urls), nullptr); +#endif // !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) provider_.UpdateChromePolicy(values); }
diff --git a/chrome/browser/sharesheet/sharesheet_service.cc b/chrome/browser/sharesheet/sharesheet_service.cc index 34a872b..9d72eb9 100644 --- a/chrome/browser/sharesheet/sharesheet_service.cc +++ b/chrome/browser/sharesheet/sharesheet_service.cc
@@ -17,7 +17,9 @@ #include "chrome/browser/sharesheet/share_action/share_action.h" #include "chrome/browser/sharesheet/sharesheet_service_delegator.h" #include "chrome/grit/generated_resources.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_types.h" +#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "content/public/browser/web_contents.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -390,13 +392,22 @@ void SharesheetService::LaunchApp(const std::u16string& target_name, apps::IntentPtr intent) { - auto launch_source = apps::mojom::LaunchSource::kFromSharesheet; - app_service_proxy_->LaunchAppWithIntent( - base::UTF16ToUTF8(target_name), - apps::GetEventFlags(WindowOpenDisposition::NEW_WINDOW, - /*prefer_container=*/true), - apps::ConvertIntentToMojomIntent(intent), launch_source, - apps::MakeWindowInfo(display::kDefaultDisplayId)); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + app_service_proxy_->LaunchAppWithIntent( + base::UTF16ToUTF8(target_name), + apps::GetEventFlags(WindowOpenDisposition::NEW_WINDOW, + /*prefer_container=*/true), + std::move(intent), apps::LaunchSource::kFromSharesheet, + std::make_unique<apps::WindowInfo>(display::kDefaultDisplayId)); + } else { + app_service_proxy_->LaunchAppWithIntent( + base::UTF16ToUTF8(target_name), + apps::GetEventFlags(WindowOpenDisposition::NEW_WINDOW, + /*prefer_container=*/true), + apps::ConvertIntentToMojomIntent(intent), + apps::mojom::LaunchSource::kFromSharesheet, + apps::MakeWindowInfo(display::kDefaultDisplayId)); + } } SharesheetServiceDelegator* SharesheetService::GetOrCreateDelegator(
diff --git a/chrome/browser/speech/tts_client_lacros.cc b/chrome/browser/speech/tts_client_lacros.cc index e287804..3310a11 100644 --- a/chrome/browser/speech/tts_client_lacros.cc +++ b/chrome/browser/speech/tts_client_lacros.cc
@@ -19,8 +19,17 @@ #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" +namespace { + +bool IsOffline(net::NetworkChangeNotifier::ConnectionType type) { + return type == net::NetworkChangeNotifier::CONNECTION_NONE; +} + +} // namespace + TtsClientLacros::TtsClientLacros(content::BrowserContext* browser_context) - : browser_context_(browser_context) { + : browser_context_(browser_context), + is_offline_(IsOffline(net::NetworkChangeNotifier::GetConnectionType())) { auto* service = chromeos::LacrosService::Get(); if (!service->IsAvailable<crosapi::mojom::Tts>()) return; @@ -38,6 +47,8 @@ receiver_.BindNewPipeAndPassRemoteWithVersion(), browser_context_id_, /*is_primary_profile=*/is_primary_profile); + net::NetworkChangeNotifier::AddNetworkChangeObserver(this); + // Push Lacros voices to Ash. NotifyLacrosVoicesChanged(); } @@ -62,13 +73,28 @@ out_voices->push_back(voice); } -TtsClientLacros::~TtsClientLacros() = default; +TtsClientLacros::~TtsClientLacros() { + net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); +} TtsClientLacros* TtsClientLacros::GetForBrowserContext( content::BrowserContext* context) { return TtsClientFactoryLacros::GetForBrowserContext(context); } +void TtsClientLacros::OnNetworkChanged( + net::NetworkChangeNotifier::ConnectionType type) { + // Since the remote voices are NOT returned by TtsExtensionEngine::GetVoices() + // if the system is offline, threfore, when the network status changes, the + // Lacros voices need to be refreshed to ensure the remote voices to be + // included or excluded according to the current network state. + bool is_offline = IsOffline(type); + if (is_offline_ != is_offline) { + is_offline_ = is_offline; + NotifyLacrosVoicesChanged(); + } +} + void TtsClientLacros::NotifyLacrosVoicesChanged() { chromeos::LacrosService* service = chromeos::LacrosService::Get(); if (!service->IsAvailable<crosapi::mojom::Tts>())
diff --git a/chrome/browser/speech/tts_client_lacros.h b/chrome/browser/speech/tts_client_lacros.h index f59f5cc..3c397729 100644 --- a/chrome/browser/speech/tts_client_lacros.h +++ b/chrome/browser/speech/tts_client_lacros.h
@@ -15,6 +15,7 @@ #include "content/public/browser/tts_controller.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "net/base/network_change_notifier.h" namespace content { class BrowserContext; @@ -23,8 +24,10 @@ // Implements crosapi::mojom::TtsClient, which is called by ash to handle // TTS requests to Lacros such as retrieving voice data, etc. It also manages // To send TTS requests ash. TtsClientLacros is created per BrowserContext. -class TtsClientLacros : public extensions::BrowserContextKeyedAPI, - public crosapi::mojom::TtsClient { +class TtsClientLacros + : public extensions::BrowserContextKeyedAPI, + public crosapi::mojom::TtsClient, + public net::NetworkChangeNotifier::NetworkChangeObserver { public: explicit TtsClientLacros(content::BrowserContext* context); TtsClientLacros(const TtsClientLacros&) = delete; @@ -51,6 +54,10 @@ private: friend class extensions::BrowserContextKeyedAPIFactory<TtsClientLacros>; + // net::NetworkChangeNotifier::NetworkChangeObserver: + void OnNetworkChanged( + net::NetworkChangeNotifier::ConnectionType type) override; + // Notifies Ash about Lacros voices change. void NotifyLacrosVoicesChanged(); @@ -63,6 +70,8 @@ // Cached voices for |browser_context_|, including both ash and lacros voices. std::vector<content::VoiceData> all_voices_; + bool is_offline_; + base::WeakPtrFactory<TtsClientLacros> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 3062f034..e84c25c 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -3116,6 +3116,7 @@ "//chrome/browser/resources:internet_config_dialog_resources", "//chrome/browser/resources:internet_detail_dialog_resources", "//chrome/browser/resources/chromeos:multidevice_setup_resources", + "//chrome/browser/resources/chromeos/cloud_upload:resources", "//chrome/browser/ui/app_list/search/cros_action_history:cros_action_proto", "//chrome/browser/ui/app_list/search/ranking:proto", "//chrome/browser/ui/app_list/search/search_result_ranker:app_launch_event_logger_proto", @@ -4522,6 +4523,8 @@ "views/md_text_button_with_down_arrow.h", "views/media_router/cast_dialog_access_code_cast_button.cc", "views/media_router/cast_dialog_access_code_cast_button.h", + "views/media_router/cast_dialog_coordinator.cc", + "views/media_router/cast_dialog_coordinator.h", "views/media_router/cast_dialog_helper.cc", "views/media_router/cast_dialog_helper.h", "views/media_router/cast_dialog_metrics.cc",
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java index ac59d9d..e7a466c 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java
@@ -69,7 +69,7 @@ @Override public void getItemOffsets( Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { - outRect.left = mItemSpacingPx; + outRect.left = 0; outRect.right = mItemSpacingPx; } });
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java index 2a6782dd..8362a7c 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.omnibox.suggestions.carousel; +import android.content.res.Configuration; import android.content.res.Resources; import android.view.View; @@ -62,6 +63,10 @@ * @return The requested item spacing, expressed in Pixels. */ static int getItemSpacingPx(@FormFactor int formFactor, @NonNull Resources resources) { + if (resources.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { + return resources.getDimensionPixelOffset(R.dimen.tile_view_padding_landscape); + } + int maxTileSpacing = resources.getDimensionPixelOffset( R.dimen.omnibox_suggestion_carousel_spacing_maximum); int tileViewPortraitEdgePadding = @@ -70,8 +75,8 @@ case FormFactor.PHONE: int screenWidth = resources.getDisplayMetrics().widthPixels; int tileViewWidth = resources.getDimensionPixelOffset(R.dimen.tile_view_width); - return Integer.min(maxTileSpacing, - (int) ((screenWidth - tileViewPortraitEdgePadding - tileViewWidth * 4.7) + return Integer.max(-resources.getDimensionPixelOffset(R.dimen.tile_view_padding), + (int) ((screenWidth - tileViewPortraitEdgePadding - tileViewWidth * 4.5) / 4)); case FormFactor.TABLET: return tileViewPortraitEdgePadding;
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java index 081f32d..1c11c4e 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java
@@ -12,6 +12,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; import android.view.View; @@ -64,9 +65,9 @@ @Mock Resources mResources; - ModelList mTiles; - - PropertyModel mModel; + private ModelList mTiles; + private PropertyModel mModel; + private Configuration mConfiguration; @Before public void setUp() { @@ -75,6 +76,8 @@ PropertyModelChangeProcessor.create(mModel, mView, BaseCarouselSuggestionViewBinder::bind); mTiles = new ModelList(); + mConfiguration = new Configuration(); + mConfiguration.orientation = Configuration.ORIENTATION_PORTRAIT; when(mView.getHeaderTextView()).thenReturn(mHeaderTextView); when(mView.getHeaderView()).thenReturn(mHeaderView); @@ -84,6 +87,7 @@ when(mResources.getDimensionPixelSize(eq(R.dimen.omnibox_carousel_suggestion_padding))) .thenReturn(SUGGESTION_VERTICAL_PADDING); + when(mResources.getConfiguration()).thenReturn(mConfiguration); } @Test @@ -153,7 +157,7 @@ * tile_view_padding */ @Test - public void formFactor_itemSpacingPhone_computed() { + public void formFactor_itemSpacingPhone_computedPortrait() { int tileSpacingMaximum = 28; int displayWidth = 1440; int tileViewPaddingEdgePortrait = 12; @@ -172,40 +176,13 @@ when(mResources.getDisplayMetrics()).thenReturn(displayMetrics); final int expectedSpacingPx = - (int) ((displayWidth - tileViewPaddingEdgePortrait - tileViewwidth * 4.7) / 4); + (int) ((displayWidth - tileViewPaddingEdgePortrait - tileViewwidth * 4.5) / 4); Assert.assertEquals(expectedSpacingPx, BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.PHONE, mResources)); } - /** - * We expect value to be fixed as tile_view_padding is larger than the tile margin value - * computed - */ @Test - public void formFactor_itemSpacingPhone_fixed() { - int tileSpacingMaximum = 28; - int displayWidth = 2990; - int tileViewPaddingEdgePortrait = 12; - int tileViewwidth = 280; - - when(mResources.getDimensionPixelOffset( - eq(R.dimen.omnibox_suggestion_carousel_spacing_maximum))) - .thenReturn(tileSpacingMaximum); - when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) - .thenReturn(tileViewPaddingEdgePortrait); - when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_width))) - .thenReturn(tileViewwidth); - - DisplayMetrics displayMetrics = new DisplayMetrics(); - displayMetrics.widthPixels = displayWidth; - when(mResources.getDisplayMetrics()).thenReturn(displayMetrics); - - Assert.assertEquals(tileSpacingMaximum, - BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.PHONE, mResources)); - } - - @Test - public void formFactor_itemSpacingTablet() { + public void formFactor_itemSpacingTabletPortrait() { final int paddingPx = 100; when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) .thenReturn(paddingPx); @@ -223,4 +200,34 @@ mModel.set(SuggestionCommonProperties.DEVICE_FORM_FACTOR, FormFactor.TABLET); verify(mView, times(1)).setItemSpacingPx(eq(spacingPx)); } + + @Test + public void formFactor_itemSpacingPhone_landscape() { + int landscapePadding = 123456789; + + mConfiguration.orientation = Configuration.ORIENTATION_LANDSCAPE; + + // Ignore all other dimensions. Allow the logic to return garbage (or crash) if expectation + // is not met. + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_padding_landscape))) + .thenReturn(landscapePadding); + + Assert.assertEquals(landscapePadding, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.PHONE, mResources)); + } + + @Test + public void formFactor_itemSpacingTablet_landscape() { + int landscapePadding = 123456789; + + mConfiguration.orientation = Configuration.ORIENTATION_LANDSCAPE; + + // Ignore all other dimensions. Allow the logic to return garbage (or crash) if expectation + // is not met. + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_padding_landscape))) + .thenReturn(landscapePadding); + + Assert.assertEquals(landscapePadding, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.TABLET, mResources)); + } }
diff --git a/chrome/browser/ui/app_list/app_list_syncable_service.cc b/chrome/browser/ui/app_list/app_list_syncable_service.cc index 91e170d..ca20faa4 100644 --- a/chrome/browser/ui/app_list/app_list_syncable_service.cc +++ b/chrome/browser/ui/app_list/app_list_syncable_service.cc
@@ -52,7 +52,6 @@ #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sync/driver/sync_service.h" #include "components/sync/model/sync_change_processor.h" @@ -131,21 +130,12 @@ std::make_unique<apps::App>(apps::AppType::kChromeApp, id); delta->install_reason = apps::InstallReason::kDefault; - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> deltas; - deltas.push_back(std::move(delta)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(deltas), apps::AppType::kChromeApp, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(delta)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(mojom_deltas), apps::mojom::AppType::kChromeApp, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> deltas; + deltas.push_back(std::move(delta)); + apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache() + .OnApps(std::move(deltas), apps::AppType::kChromeApp, + false /* should_notify_initialized */); } bool IsUnRemovableDefaultApp(const std::string& id) {
diff --git a/chrome/browser/ui/app_list/app_service/app_service_app_item_browsertest.cc b/chrome/browser/ui/app_list/app_service/app_service_app_item_browsertest.cc index 60bbc25..140e54ad4 100644 --- a/chrome/browser/ui/app_list/app_service/app_service_app_item_browsertest.cc +++ b/chrome/browser/ui/app_list/app_service/app_service_app_item_browsertest.cc
@@ -30,7 +30,6 @@ #include "components/account_id/account_id.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" @@ -51,21 +50,12 @@ block ? apps::Readiness::kDisabledByPolicy : apps::Readiness::kReady; app->paused = pause; - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kChromeApp, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(mojom_deltas), apps::mojom::AppType::kChromeApp, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app)); + apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kChromeApp, + false /* should_notify_initialized */); } void UpdateAppNameInRegistryCache(Profile* profile, @@ -75,21 +65,12 @@ std::make_unique<apps::App>(apps::AppType::kChromeApp, app_id); app->name = app_name; - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kChromeApp, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(app)); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(mojom_deltas), apps::mojom::AppType::kChromeApp, - false /* should_notify_initialized */); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app)); + apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kChromeApp, + false /* should_notify_initialized */); } ash::AppListItem* GetAppListItem(const std::string& id) {
diff --git a/chrome/browser/ui/app_list/arc/arc_app_launcher.cc b/chrome/browser/ui/app_list/arc/arc_app_launcher.cc index 22aa7303..3e46457 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_launcher.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_launcher.cc
@@ -11,12 +11,13 @@ #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/profiles/profile.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/features.h" #include "ui/events/event_constants.h" ArcAppLauncher::ArcAppLauncher(content::BrowserContext* context, const std::string& app_id, - apps::mojom::IntentPtr launch_intent, + apps::IntentPtr launch_intent, bool deferred_launch_allowed, int64_t display_id, apps::LaunchSource launch_source) @@ -123,10 +124,17 @@ Observe(nullptr); if (launch_intent_) { - proxy->LaunchAppWithIntent( - app_id_, ui::EF_NONE, std::move(launch_intent_), - apps::ConvertLaunchSourceToMojomLaunchSource(launch_source_), - apps::MakeWindowInfo(display_id_)); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + proxy->LaunchAppWithIntent( + app_id_, ui::EF_NONE, std::move(launch_intent_), launch_source_, + std::make_unique<apps::WindowInfo>(display_id_)); + } else { + proxy->LaunchAppWithIntent( + app_id_, ui::EF_NONE, + apps::ConvertIntentToMojomIntent(launch_intent_), + apps::ConvertLaunchSourceToMojomLaunchSource(launch_source_), + apps::MakeWindowInfo(display_id_)); + } } else { if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { proxy->Launch(app_id_, ui::EF_NONE, launch_source_,
diff --git a/chrome/browser/ui/app_list/arc/arc_app_launcher.h b/chrome/browser/ui/app_list/arc/arc_app_launcher.h index 89ca768..19981bf5 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_launcher.h +++ b/chrome/browser/ui/app_list/arc/arc_app_launcher.h
@@ -15,7 +15,7 @@ #include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/mojom/types.mojom.h" +#include "components/services/app_service/public/cpp/intent.h" namespace content { class BrowserContext; @@ -28,7 +28,7 @@ public: ArcAppLauncher(content::BrowserContext* context, const std::string& app_id, - apps::mojom::IntentPtr launch_intent, + apps::IntentPtr launch_intent, bool deferred_launch_allowed, int64_t display_id, apps::LaunchSource launch_source); @@ -62,7 +62,7 @@ const std::string app_id_; // Optional intent to launch the app. If not set then app is started default // way. - apps::mojom::IntentPtr launch_intent_; + apps::IntentPtr launch_intent_; // If it is set to true that means app is allowed to launch in deferred mode // once it is registered, regardless it is ready or not. Otherwise app is // launched when it becomes ready.
diff --git a/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc b/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc index 9679eda..986aa1d 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc
@@ -1689,6 +1689,8 @@ web_app_info_dict.Set(kCertificateSha256Fingerprint, *fingerprint); } package_dict.Set(kWebAppInfo, std::move(web_app_info_dict)); + } else { + package_dict.Remove(kWebAppInfo); } if (old_package_version == -1 ||
diff --git a/chrome/browser/ui/app_list/arc/arc_app_test.cc b/chrome/browser/ui/app_list/arc/arc_app_test.cc index 9cfdffbf..d37910e 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_test.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_test.cc
@@ -330,6 +330,17 @@ fake_packages_.push_back(std::move(package)); } +void ArcAppTest::UpdatePackage(arc::mojom::ArcPackageInfoPtr updated_package) { + auto it = std::find_if(fake_packages_.begin(), fake_packages_.end(), + [&updated_package](const auto& package) { + return package->package_name == + updated_package->package_name; + }); + if (it != fake_packages_.end()) { + *it = std::move(updated_package); + } +} + void ArcAppTest::RemovePackage(const std::string& package_name) { base::EraseIf(fake_packages_, [package_name](const auto& package) { return package->package_name == package_name;
diff --git a/chrome/browser/ui/app_list/arc/arc_app_test.h b/chrome/browser/ui/app_list/arc/arc_app_test.h index e53b6c9..8df106b9 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_test.h +++ b/chrome/browser/ui/app_list/arc/arc_app_test.h
@@ -72,6 +72,9 @@ // Adds package info and takes ownership. void AddPackage(arc::mojom::ArcPackageInfoPtr package); + // Replaces package if a package with this package name exists. + void UpdatePackage(arc::mojom::ArcPackageInfoPtr package); + void RemovePackage(const std::string& package_name); void WaitForDefaultApps();
diff --git a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc index cd5341c..2aa8d78 100644 --- a/chrome/browser/ui/app_list/arc/arc_app_unittest.cc +++ b/chrome/browser/ui/app_list/arc/arc_app_unittest.cc
@@ -84,6 +84,7 @@ #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" #include "components/services/app_service/public/cpp/icon_types.h" +#include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/services/app_service/public/cpp/stub_icon_loader.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -114,6 +115,7 @@ namespace { constexpr char kTestPackageName[] = "fake.package.name2"; +constexpr char kTestPackageName4[] = "fake.package.name4"; constexpr char kFrameworkPackageName[] = "android"; constexpr int kFrameworkNycVersion = 25; @@ -788,6 +790,12 @@ FlushMojoCallsForAppService(); } + void UpdatePackage(const arc::mojom::ArcPackageInfoPtr& package) { + arc_test_.UpdatePackage(package->Clone()); + app_instance()->SendPackageModified(package->Clone()); + FlushMojoCallsForAppService(); + } + void RemovePackage(const std::string& package_name) { arc_test_.RemovePackage(package_name); app_instance()->SendPackageUninstalled(package_name); @@ -1451,6 +1459,10 @@ package->last_backup_time = 2; AddPackage(package); ValidateHavePackages(fake_packages()); + + // Update web_app_info of the last package to null. + UpdatePackage(CreatePackage(kTestPackageName4)); + ValidateHavePackages(fake_packages()); } TEST_P(ArcAppModelBuilderTest, RefreshAllFillsContent) { @@ -3143,7 +3155,7 @@ app2.package_name, app2.activity, std::vector<std::string>{"S.org.chromium.arc.start_type=initialStart"}); { - auto launch_intent2 = apps_util::CreateIntentForActivity( + auto launch_intent2 = apps_util::MakeIntentForActivity( app2.activity, arc::kInitialStartParam, arc::kCategoryLauncher); ArcAppLauncher launcher2(profile(), id2, std::move(launch_intent2), false, display::kInvalidDisplayId,
diff --git a/chrome/browser/ui/app_list/search/app_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/app_search_provider_unittest.cc index d458cb3..48c1cfe 100644 --- a/chrome/browser/ui/app_list/search/app_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/app_search_provider_unittest.cc
@@ -48,7 +48,6 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "components/crx_file/id_util.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/icon_types.h" #include "components/services/app_service/public/cpp/stub_icon_loader.h" #include "components/services/app_service/public/mojom/types.mojom.h" @@ -136,17 +135,8 @@ apps::AppPtr app = std::make_unique<apps::App>(app_type, app_id); app->icon_key = std::move(*icon_key); apps.push_back(std::move(app)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - proxy.AppRegistryCache().OnApps(std::move(apps), apps::AppType::kUnknown, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(apps[0])); - proxy.AppRegistryCache().OnApps(std::move(mojom_apps), - apps::mojom::AppType::kUnknown, - false /* should_notify_initialized */); - proxy.FlushMojoCallsForTesting(); - } + proxy.AppRegistryCache().OnApps(std::move(apps), apps::AppType::kUnknown, + false /* should_notify_initialized */); } class AppSearchProviderTest : public AppListTestBase {
diff --git a/chrome/browser/ui/ash/app_access_notifier_unittest.cc b/chrome/browser/ui/ash/app_access_notifier_unittest.cc index 59b5f75..25d9e0e 100644 --- a/chrome/browser/ui/ash/app_access_notifier_unittest.cc +++ b/chrome/browser/ui/ash/app_access_notifier_unittest.cc
@@ -16,7 +16,6 @@ #include "components/services/app_service/public/cpp/app_registry_cache_wrapper.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/capability_access_update.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/user_manager/fake_user_manager.h" #include "components/user_manager/scoped_user_manager.h" #include "testing/gtest/include/gtest/gtest.h" @@ -151,16 +150,8 @@ std::vector<apps::AppPtr> registry_deltas; registry_deltas.push_back(MakeApp(id, name)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - reg_cache->OnApps(std::move(registry_deltas), apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(registry_deltas[0])); - reg_cache->OnApps(std::move(mojom_deltas), apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + reg_cache->OnApps(std::move(registry_deltas), apps::AppType::kUnknown, + /*should_notify_initialized=*/false); std::vector<apps::mojom::CapabilityAccessPtr> capability_access_deltas; capability_access_deltas.push_back(MakeCapabilityAccess(
diff --git a/chrome/browser/ui/ash/arc_open_url_delegate_impl.cc b/chrome/browser/ui/ash/arc_open_url_delegate_impl.cc index 2976e7d..4e00404 100644 --- a/chrome/browser/ui/ash/arc_open_url_delegate_impl.cc +++ b/chrome/browser/ui/ash/arc_open_url_delegate_impl.cc
@@ -45,7 +45,10 @@ #include "chrome/common/webui_url_constants.h" #include "components/arc/intent_helper/arc_intent_helper_bridge.h" #include "components/arc/intent_helper/custom_tab.h" +#include "components/services/app_service/public/cpp/app_launch_util.h" #include "components/services/app_service/public/cpp/app_update.h" +#include "components/services/app_service/public/cpp/features.h" +#include "components/services/app_service/public/cpp/intent.h" #include "components/services/app_service/public/cpp/intent_filter_util.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "components/services/app_service/public/cpp/types_util.h" @@ -185,15 +188,12 @@ base::FilePath(fusebox::MonikerMap::GetFilename(moniker))); } -apps::mojom::IntentPtr ConvertLaunchIntent( +apps::IntentPtr ConvertLaunchIntent( Profile* profile, const arc::mojom::LaunchIntentPtr& launch_intent) { - apps::mojom::IntentPtr intent = apps::mojom::Intent::New(); - const char* action = apps_util::ConvertArcToAppServiceIntentAction(launch_intent->action); - if (action) - intent->action = action; + auto intent = std::make_unique<apps::Intent>(action ? action : ""); intent->url = launch_intent->data; intent->mime_type = launch_intent->type; @@ -202,19 +202,17 @@ if (launch_intent->files.has_value() && launch_intent->files->size() > 0) { std::vector<std::string> mime_types; - intent->files = std::vector<apps::mojom::IntentFilePtr>(); for (const auto& file_info : *launch_intent->files) { - auto file = apps::mojom::IntentFile::New(); - - file->url = arc::ArcUrlToExternalFileUrl(file_info->content_uri); + GURL url = arc::ArcUrlToExternalFileUrl(file_info->content_uri); if (ash::features::IsArcFuseBoxFileSharingEnabled()) { - file->url = ConvertToMonikerFileUrl(profile, file->url); + url = ConvertToMonikerFileUrl(profile, url); } + apps::IntentFilePtr file = std::make_unique<apps::IntentFile>(url); file->mime_type = file_info->type; file->file_name = file_info->name; file->file_size = file_info->size; - intent->files->push_back(std::move(file)); + intent->files.push_back(std::move(file)); mime_types.push_back(file_info->type); } @@ -459,7 +457,7 @@ return; } - apps::mojom::IntentPtr intent = ConvertLaunchIntent(profile, arc_intent); + apps::IntentPtr intent = ConvertLaunchIntent(profile, arc_intent); auto disposition = WindowOpenDisposition::NEW_WINDOW; proxy->AppRegistryCache().ForOneApp( @@ -472,6 +470,12 @@ int event_flags = apps::GetEventFlags(disposition, /*prefer_container=*/false); - proxy->LaunchAppWithIntent(app_id, event_flags, std::move(intent), - apps::mojom::LaunchSource::kFromArc); + if (base::FeatureList::IsEnabled(apps::kAppServiceLaunchWithoutMojom)) { + proxy->LaunchAppWithIntent(app_id, event_flags, std::move(intent), + apps::LaunchSource::kFromArc); + } else { + proxy->LaunchAppWithIntent(app_id, event_flags, + apps::ConvertIntentToMojomIntent(intent), + apps::mojom::LaunchSource::kFromArc); + } }
diff --git a/chrome/browser/ui/ash/assistant/assistant_state_client_unittest.cc b/chrome/browser/ui/ash/assistant/assistant_state_client_unittest.cc index 140458b..a5a75d80 100644 --- a/chrome/browser/ui/ash/assistant/assistant_state_client_unittest.cc +++ b/chrome/browser/ui/ash/assistant/assistant_state_client_unittest.cc
@@ -17,7 +17,6 @@ #include "chrome/test/base/chrome_ash_test_base.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/concierge/concierge_client.h" -#include "chromeos/dbus/dbus_thread_manager.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "components/user_manager/scoped_user_manager.h" @@ -30,9 +29,6 @@ ~AssistantStateClientTest() override = default; void SetUp() override { - // Need to initialize DBusThreadManager before ArcSessionManager's - // constructor calls DBusThreadManager::Get(). - chromeos::DBusThreadManager::Initialize(); ash::ConciergeClient::InitializeFake(/*fake_cicerone_client=*/nullptr); ChromeAshTestBase::SetUp(); @@ -63,7 +59,6 @@ arc_session_manager_.reset(); ChromeAshTestBase::TearDown(); ash::ConciergeClient::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } AssistantStateClient* assistant_state_client() {
diff --git a/chrome/browser/ui/ash/media_client_impl_unittest.cc b/chrome/browser/ui/ash/media_client_impl_unittest.cc index c0ecbb1..2fd47ced 100644 --- a/chrome/browser/ui/ash/media_client_impl_unittest.cc +++ b/chrome/browser/ui/ash/media_client_impl_unittest.cc
@@ -18,7 +18,6 @@ #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_registry_cache_wrapper.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/mojom/types.mojom-forward.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -195,18 +194,8 @@ apps::mojom::OptionalBool use_camera) { std::vector<apps::AppPtr> registry_deltas; registry_deltas.push_back(MakeApp(id, name)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - registry_cache_.OnApps(std::move(registry_deltas), - apps::AppType::kUnknown, - /* should_notify_initialized = */ false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(registry_deltas[0])); - registry_cache_.OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kUnknown, - /* should_notify_initialized = */ false); - } + registry_cache_.OnApps(std::move(registry_deltas), apps::AppType::kUnknown, + /* should_notify_initialized = */ false); std::vector<apps::mojom::CapabilityAccessPtr> capability_access_deltas; capability_access_deltas.push_back(MakeCapabilityAccess(id, use_camera));
diff --git a/chrome/browser/ui/ash/projector/pending_screencast_manager.cc b/chrome/browser/ui/ash/projector/pending_screencast_manager.cc index 49dcdbb..5a7405f 100644 --- a/chrome/browser/ui/ash/projector/pending_screencast_manager.cc +++ b/chrome/browser/ui/ash/projector/pending_screencast_manager.cc
@@ -10,7 +10,7 @@ #include "ash/components/drivefs/mojom/drivefs.mojom.h" #include "ash/constants/ash_features.h" #include "ash/projector/projector_metrics.h" -#include "ash/public/cpp/projector/projector_controller.h" +#include "ash/webui/projector_app/public/cpp/projector_app_constants.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/check.h" @@ -35,8 +35,6 @@ namespace { -constexpr base::FilePath::CharType kMediaExtension[] = - FILE_PATH_LITERAL(".webm"); constexpr char kOpenUrlBase[] = "https://drive.google.com/open"; constexpr char kDriveRequestContentHintsKey[] = "contentHints"; constexpr char kDriveRequestIndexableTextKey[] = "indexableText"; @@ -46,13 +44,9 @@ // so put 3s here to allow Drive to populate the metadata. constexpr base::TimeDelta kDriveGetMetadataDelay = base::Seconds(3); -const std::string GetMetadataFileExtension() { - return base::StrCat({".", ash::kProjectorMetadataFileExtension}); -} - bool IsWebmOrProjectorFile(const base::FilePath& path) { - return path.MatchesExtension(kMediaExtension) || - path.MatchesExtension(GetMetadataFileExtension()); + return path.MatchesExtension(ash::kProjectorMediaFileExtension) || + path.MatchesExtension(ash::kProjectorMetadataFileExtension); } drivefs::DriveFsHost* GetDriveFsHostForActiveProfile() { @@ -234,19 +228,18 @@ // Calculates the size of media file and metadata file, and the created time // of media. - const std::string metadata_extension = GetMetadataFileExtension(); for (base::FilePath path = files.Next(); !path.empty(); path = files.Next()) { - if (path.MatchesExtension(metadata_extension)) { + if (path.MatchesExtension(ash::kProjectorMetadataFileExtension)) { total_size_in_bytes += files.GetInfo().GetSize(); - media_file_count++; - } else if (path.MatchesExtension(kMediaExtension)) { + metadata_file_count++; + } else if (path.MatchesExtension(ash::kProjectorMediaFileExtension)) { base::File::Info info; if (!base::GetFileInfo(path, &info)) continue; created_time = info.creation_time; total_size_in_bytes += files.GetInfo().GetSize(); media_name = path.BaseName().RemoveExtension().value(); - metadata_file_count++; + media_file_count++; } // Return null if the screencast is not valid. @@ -405,7 +398,7 @@ // "kCompleted" state for a file so that we could only update indexable text // once. if (ash::features::IsProjectorUpdateIndexableTextEnabled() && - event_file.MatchesExtension(GetMetadataFileExtension())) { + event_file.MatchesExtension(ash::kProjectorMetadataFileExtension)) { syncing_metadata_files_.emplace(event_file); } pending_webm_or_projector_events.push_back(
diff --git a/chrome/browser/ui/ash/projector/screencast_manager.cc b/chrome/browser/ui/ash/projector/screencast_manager.cc index fa75518..6d53a9c 100644 --- a/chrome/browser/ui/ash/projector/screencast_manager.cc +++ b/chrome/browser/ui/ash/projector/screencast_manager.cc
@@ -4,19 +4,93 @@ #include "chrome/browser/ui/ash/projector/screencast_manager.h" -#include <memory> +#include <vector> #include "ash/webui/projector_app/projector_screencast.h" +#include "ash/webui/projector_app/public/cpp/projector_app_constants.h" +#include "base/bind.h" #include "base/check.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "components/drive/service/drive_api_service.h" +#include "components/drive/service/drive_service_interface.h" +#include "components/signin/public/base/consent_level.h" +#include "components/signin/public/identity_manager/identity_manager.h" +#include "content/public/browser/storage_partition.h" +#include "google_apis/common/api_error_codes.h" +#include "google_apis/drive/drive_api_parser.h" +#include "google_apis/drive/drive_api_url_generator.h" +#include "google_apis/drive/drive_common_callbacks.h" +#include "google_apis/gaia/gaia_urls.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "url/gurl.h" namespace ash { +namespace { + +// Projector network traffic annotation tags. +constexpr net::NetworkTrafficAnnotationTag kNetworkTrafficAnnotationTag = + net::DefineNetworkTrafficAnnotation("projector_drive_request", + R"( + semantics: { + sender: "ChromeOS Projector" + description: "ChromeOS send Drive request for Projector" + destination: GOOGLE_OWNED_SERVICE + } + policy: { + cookies_allowed: YES + })"); + +// Populates the `metadata_file_id` and `video.file_id` fields for `screencast` +// on get the results from GetFileListInDirectory(). +void OnGetScreencastFilesResult( + std::unique_ptr<ProjectorScreencast> screencast, + ProjectorAppClient::OnGetScreencastCallback callback, + google_apis::ApiErrorCode error, + std::unique_ptr<google_apis::FileList> entry) { + // Copies screencast id since `screencast` will be deleted after std::move(). + const std::string screencast_id = screencast->container_folder_id; + if (error != google_apis::ApiErrorCode::HTTP_SUCCESS) { + std::move(callback).Run( + std::move(screencast), + base::StringPrintf( + "Search Drive files error. ScreencastId=%s, ErrorCode=%d", + screencast_id.c_str(), error)); + return; + } + + for (const auto& file_resource : entry->items()) { + if (base::EndsWith(file_resource->title(), kProjectorMediaFileExtension)) { + screencast->video.file_id = file_resource->file_id(); + } else if (base::EndsWith(file_resource->title(), + kProjectorMetadataFileExtension)) { + screencast->metadata_file_id = file_resource->file_id(); + } + } + + std::string error_msg; + if (screencast->metadata_file_id.empty() || + screencast->video.file_id.empty()) { + error_msg = base::StringPrintf( + "Invalid screencast. Missing video file or metadata file. " + "ScreencastId=%s", + screencast_id.c_str()); + } + std::move(callback).Run(std::move(screencast), error_msg); +} + +} // namespace + ScreencastManager::ScreencastManager() = default; ScreencastManager::~ScreencastManager() = default; // TODO(b/237089852): Find the path for local video file. -// TODO(b/236857019): Set video and metadata file ids and rest fields for -// screencasts. +// TODO(b/236857019): Set the rest of the fields for the screencast. void ScreencastManager::GetScreencast( const std::string& screencast_id, ProjectorAppClient::OnGetScreencastCallback callback) { @@ -24,7 +98,48 @@ std::unique_ptr<ProjectorScreencast> screencast = std::make_unique<ProjectorScreencast>(); screencast->container_folder_id = screencast_id; - std::move(callback).Run(std::move(screencast), std::string()); + if (!drive_api_service_) + InitDriveAPIService(); + + drive_api_service_->GetFileListInDirectory( + screencast_id, + base::BindOnce(&OnGetScreencastFilesResult, std::move(screencast), + std::move(callback))); +} + +void ScreencastManager::SetDriveAPIServiceForTest( + std::unique_ptr<drive::DriveServiceInterface> drive_api_service) { + drive_api_service_ = std::move(drive_api_service); +} + +void ScreencastManager::InitDriveAPIService() { + // TODO(b/221492092): Add one DriveFS/Drive helper to manage the profile + // switch. + signin::IdentityManager* identity_manager = + ProjectorAppClient::Get()->GetIdentityManager(); + auto* profile = ProfileManager::GetActiveUserProfile(); + DCHECK(profile); + DCHECK(identity_manager); + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory = + profile->GetDefaultStoragePartition() + ->GetURLLoaderFactoryForBrowserProcess(); + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner = + base::ThreadPool::CreateSequencedTaskRunner( + {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); + GURL base_url(GaiaUrls::GetInstance()->google_apis_origin_url()); + GURL base_thumbnail_url( + google_apis::DriveApiUrlGenerator::kBaseThumbnailUrlForProduction); + drive_api_service_ = std::make_unique<drive::DriveAPIService>( + identity_manager, url_loader_factory, blocking_task_runner.get(), + base_url, base_thumbnail_url, /*custom_user_agent=*/std::string(), + kNetworkTrafficAnnotationTag); + + // The screencast object will be used to load screencast from DriveFS and + // since DriveFS only support primary account, we don't need to handle + // secondary account here. + drive_api_service_->Initialize( + identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin)); } } // namespace ash
diff --git a/chrome/browser/ui/ash/projector/screencast_manager.h b/chrome/browser/ui/ash/projector/screencast_manager.h index c7c13c2..c830614 100644 --- a/chrome/browser/ui/ash/projector/screencast_manager.h +++ b/chrome/browser/ui/ash/projector/screencast_manager.h
@@ -5,10 +5,15 @@ #ifndef CHROME_BROWSER_UI_ASH_PROJECTOR_SCREENCAST_MANAGER_H_ #define CHROME_BROWSER_UI_ASH_PROJECTOR_SCREENCAST_MANAGER_H_ +#include <memory> #include <string> #include "ash/webui/projector_app/projector_app_client.h" +namespace drive { +class DriveServiceInterface; +} // namespace drive + namespace ash { // Class to get and modify screencast data through IO and Drive/DriveFS. @@ -24,9 +29,21 @@ void GetScreencast(const std::string& screencast_id, ProjectorAppClient::OnGetScreencastCallback callback); + void SetDriveAPIServiceForTest( + std::unique_ptr<drive::DriveServiceInterface> drive_api_service); + + private: + // Should not call this in constructor because Drive service for active + // profile might not be ready. + void InitDriveAPIService(); + // TODO(b/236857019): - // SearchScreencastFilesByParentId(): Call rest API to populate screencast - // metadata file id and video file id. + // GetScreencastMetadata(): Read metadata file into ProjectorScreencast. + // GetScreencastStatus(): Determine the status of ProjectorScreencast. + + // TODO(b/236857019): Replace the REST API with DriveFs integration service + // once it supports search file by parent id. + std::unique_ptr<drive::DriveServiceInterface> drive_api_service_; }; } // namespace ash
diff --git a/chrome/browser/ui/ash/projector/screencast_manager_unittest.cc b/chrome/browser/ui/ash/projector/screencast_manager_unittest.cc index 21a9ebb..648312f1 100644 --- a/chrome/browser/ui/ash/projector/screencast_manager_unittest.cc +++ b/chrome/browser/ui/ash/projector/screencast_manager_unittest.cc
@@ -12,6 +12,9 @@ #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" +#include "components/drive/service/fake_drive_service.h" +#include "google_apis/common/api_error_codes.h" +#include "google_apis/drive/drive_api_parser.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { @@ -22,16 +25,79 @@ } // namespace class ScreencastManagerTest : public testing::Test { + public: + // testing::Test: + void SetUp() override { + testing::Test::SetUp(); + + auto fake_drive_service = std::make_unique<drive::FakeDriveService>(); + drive_service_ = fake_drive_service.get(); + screencast_manager_.SetDriveAPIServiceForTest( + std::move(fake_drive_service)); + } + protected: + // Creates a default screencast folder with item id = |kScreencastId| for + // DriveAPIService. + void AddDefaultScreencastFolder() { + base::RunLoop run_loop; + drive_service()->AddNewDirectoryWithResourceId( + kScreencastId, + /*parent_resource_id=*/"", + /*directory_title=*/"Screencast", drive::AddNewDirectoryOptions(), + base::BindLambdaForTesting( + [&run_loop]( + google_apis::ApiErrorCode drive_error, + std::unique_ptr<google_apis::FileResource> drive_entry) { + ASSERT_EQ(drive_error, google_apis::ApiErrorCode::HTTP_CREATED); + run_loop.Quit(); + })); + run_loop.Run(); + } + + // Creates a file under the default screencast folder for DriveAPIService. + void AddFileToDefaultScreencastFolder(const std::string& file_id, + const std::string& content_type, + const std::string& title, + bool shared_with_me) { + base::RunLoop run_loop; + drive_service()->AddNewFileWithResourceId( + file_id, content_type, "This is some test content.", + /*parent_resource_id=*/kScreencastId, title, shared_with_me, + base::BindLambdaForTesting( + [&run_loop]( + google_apis::ApiErrorCode drive_error, + std::unique_ptr<google_apis::FileResource> drive_entry) { + ASSERT_EQ(drive_error, google_apis::ApiErrorCode::HTTP_CREATED); + run_loop.Quit(); + })); + run_loop.Run(); + } + ScreencastManager& screencast_manager() { return screencast_manager_; } + drive::FakeDriveService* drive_service() { return drive_service_; } + base::test::SingleThreadTaskEnvironment task_environment_; private: + drive::FakeDriveService* drive_service_ = nullptr; + ScreencastManager screencast_manager_; }; -TEST_F(ScreencastManagerTest, GetScreencast) { +TEST_F(ScreencastManagerTest, GetScreencastSuccess) { + // Creates default screencast folder. + AddDefaultScreencastFolder(); + const std::string video_file_id = "videoFileId"; + const std::string metadata_file_id = "metadataFileId"; + + // Creates screencasts files. + AddFileToDefaultScreencastFolder(video_file_id, "video/webm", + "Screencast.webm", true); + AddFileToDefaultScreencastFolder(metadata_file_id, "text/plain", + "Screencast.projector", true); + base::RunLoop run_loop; screencast_manager().GetScreencast( kScreencastId, @@ -39,6 +105,9 @@ [&run_loop](std::unique_ptr<ash::ProjectorScreencast> screencast, const std::string& error) { EXPECT_EQ(screencast->container_folder_id, kScreencastId); + // Expects video file id and metadata file id are populated. + EXPECT_EQ(screencast->video.file_id, "videoFileId"); + EXPECT_EQ(screencast->metadata_file_id, "metadataFileId"); EXPECT_TRUE(error.empty()); // Quits the run loop. run_loop.Quit(); @@ -46,4 +115,48 @@ run_loop.Run(); } +TEST_F(ScreencastManagerTest, GetScreencastInvalidScreencastError) { + AddDefaultScreencastFolder(); + // Creates invalid screencast without video file. + AddFileToDefaultScreencastFolder("metadataFileId", "text/plain", + "Screencast.projector", true); + + base::RunLoop run_loop; + screencast_manager().GetScreencast( + kScreencastId, + base::BindLambdaForTesting( + [&run_loop](std::unique_ptr<ash::ProjectorScreencast> screencast, + const std::string& error) { + // Expects missing file error. + EXPECT_EQ( + error, + "Invalid screencast. Missing video file or metadata file. " + "ScreencastId=screencastId"); + // Quits the run loop. + run_loop.Quit(); + })); + + run_loop.Run(); +} + +TEST_F(ScreencastManagerTest, GetScreencastHttpError) { + // Mocks offline. + drive_service()->set_offline(true); + + base::RunLoop run_loop; + screencast_manager().GetScreencast( + kScreencastId, + base::BindLambdaForTesting( + [&run_loop](std::unique_ptr<ash::ProjectorScreencast> screencast, + const std::string& error) { + // Expects search file error. + EXPECT_EQ(error, + "Search Drive files error. ScreencastId=screencastId, " + "ErrorCode=900"); + // Quits the run loop. + run_loop.Quit(); + })); + run_loop.Run(); +} + } // namespace ash
diff --git a/chrome/browser/ui/ash/shelf/app_service/app_service_app_window_browsertest.cc b/chrome/browser/ui/ash/shelf/app_service/app_service_app_window_browsertest.cc index 9b9f737..e3b7e69 100644 --- a/chrome/browser/ui/ash/shelf/app_service/app_service_app_window_browsertest.cc +++ b/chrome/browser/ui/ash/shelf/app_service/app_service_app_window_browsertest.cc
@@ -44,7 +44,6 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/app_constants/constants.h" #include "components/exo/shell_surface_util.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/instance.h" #include "components/services/app_service/public/cpp/instance_registry.h" #include "content/public/test/browser_test.h" @@ -459,20 +458,6 @@ app_service_proxy_->InstanceRegistry().GetInstances(app_id).size()); ASSERT_NE(-1, shelf_model()->ItemIndexByAppID(app_id)); - // With non mojom AppService, anonymous apps are published sync, so we don't - // need to flush mojom calls and verify no title for shelf items. - if (!base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - // Initially, anonymous apps haven't been published, as that is an - // asynchronous operation. This means their shelf item has no title. - EXPECT_TRUE(shelf_model() - ->items()[shelf_model()->ItemIndexByAppID(app_id)] - .title.empty()); - - // Flushing calls here simulates the fraction-of-seconds delay between the - // window appearing and its app being published. - app_service_proxy_->FlushMojoCallsForTesting(); - } - // Now that the app is published, it will have a name based on the window title EXPECT_EQ( "foo",
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_unittest.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_unittest.cc index 159aa05..0400ea7 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_unittest.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_unittest.cc
@@ -132,12 +132,8 @@ #include "components/prefs/pref_service.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/instance.h" #include "components/services/app_service/public/cpp/instance_registry.h" -#include "components/services/app_service/public/mojom/types.mojom-forward.h" -#include "components/services/app_service/public/mojom/types.mojom-shared.h" -#include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sync/base/model_type.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/sync_user_settings.h" @@ -392,19 +388,10 @@ apps.push_back(std::move(app)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kChromeApp, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(apps[0])); - apps::AppServiceProxyFactory::GetForProfile(profile) - ->AppRegistryCache() - .OnApps(std::move(mojom_apps), apps::mojom::AppType::kChromeApp, - false /* should_notify_initialized */); - } + apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kChromeApp, + false /* should_notify_initialized */); } } // namespace @@ -5145,19 +5132,10 @@ std::make_unique<apps::App>(apps::AppType::kChromeApp, extension1_->id()); app->show_in_shelf = false; apps.push_back(std::move(app)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - apps::AppServiceProxyFactory::GetForProfile(profile()) - ->AppRegistryCache() - .OnApps(std::move(apps), apps::AppType::kChromeApp, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(apps[0])); - apps::AppServiceProxyFactory::GetForProfile(profile()) - ->AppRegistryCache() - .OnApps(std::move(mojom_apps), apps::mojom::AppType::kChromeApp, - false /* should_notify_initialized */); - } + apps::AppServiceProxyFactory::GetForProfile(profile()) + ->AppRegistryCache() + .OnApps(std::move(apps), apps::AppType::kChromeApp, + false /* should_notify_initialized */); InitShelfController(); EXPECT_EQ("Chrome, App2", GetPinnedAppStatus());
diff --git a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.cc b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.cc index 4a9daea..51924f4 100644 --- a/chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.cc +++ b/chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.cc
@@ -106,7 +106,6 @@ // Eche application need context when launching. Pinning these creates an // item that does nothing. const char* kNoPinAppIds[] = { - file_manager::kAudioPlayerAppId, ash::eche_app::kEcheAppId, }; if (base::Contains(kNoPinAppIds, app_id))
diff --git a/chrome/browser/ui/ash/system_tray_client_impl.cc b/chrome/browser/ui/ash/system_tray_client_impl.cc index 0d03294d..f8193e6 100644 --- a/chrome/browser/ui/ash/system_tray_client_impl.cc +++ b/chrome/browser/ui/ash/system_tray_client_impl.cc
@@ -491,6 +491,11 @@ "?checkForUpdate=true"); } +void SystemTrayClientImpl::ShowAboutChromeOSDetails() { + ShowSettingsSubPageForActiveUser( + chromeos::settings::mojom::kDetailedBuildInfoSubpagePath); +} + void SystemTrayClientImpl::ShowAccessibilityHelp() { ash::AccessibilityManager::ShowAccessibilityHelp(); } @@ -806,6 +811,10 @@ //////////////////////////////////////////////////////////////////////////////// // UpgradeDetector::UpgradeObserver: +void SystemTrayClientImpl::OnUpdateDeferred() { + system_tray_->SetUpdateDeferred(true); +} + void SystemTrayClientImpl::OnUpdateOverCellularAvailable() { // Requests that ash show the update over cellular available icon. system_tray_->SetUpdateOverCellularAvailableIconVisible(true);
diff --git a/chrome/browser/ui/ash/system_tray_client_impl.h b/chrome/browser/ui/ash/system_tray_client_impl.h index a54724e..022f0b3 100644 --- a/chrome/browser/ui/ash/system_tray_client_impl.h +++ b/chrome/browser/ui/ash/system_tray_client_impl.h
@@ -81,6 +81,7 @@ void ShowTetherNetworkSettings() override; void ShowWifiSyncSettings() override; void ShowAboutChromeOS() override; + void ShowAboutChromeOSDetails() override; void ShowAccessibilityHelp() override; void ShowAccessibilitySettings() override; void ShowGestureEducationHelp() override; @@ -126,6 +127,7 @@ void OnSystemClockChanged(ash::system::SystemClock* clock) override; // UpgradeObserver implementation. + void OnUpdateDeferred() override; void OnUpdateOverCellularAvailable() override; void OnUpdateOverCellularOneTimePermissionGranted() override; void OnUpgradeRecommended() override;
diff --git a/chrome/browser/ui/ash/system_tray_client_impl_browsertest.cc b/chrome/browser/ui/ash/system_tray_client_impl_browsertest.cc index bf8f3d0..8d5ea92 100644 --- a/chrome/browser/ui/ash/system_tray_client_impl_browsertest.cc +++ b/chrome/browser/ui/ash/system_tray_client_impl_browsertest.cc
@@ -46,7 +46,6 @@ #include "components/prefs/pref_service.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/web_contents.h" @@ -442,20 +441,11 @@ apps::AppServiceProxyAsh* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> registry_deltas; - registry_deltas.push_back(MakeApp(app_id, name)); - proxy->AppRegistryCache().OnApps(std::move(registry_deltas), - apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(MakeApp(app_id, name))); - proxy->AppRegistryCache().OnApps(std::move(mojom_deltas), - apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + std::vector<apps::AppPtr> registry_deltas; + registry_deltas.push_back(MakeApp(app_id, name)); + proxy->AppRegistryCache().OnApps(std::move(registry_deltas), + apps::AppType::kUnknown, + /*should_notify_initialized=*/false); } protected:
diff --git a/chrome/browser/ui/browser_close_unittest.cc b/chrome/browser/ui/browser_close_unittest.cc index b53e4ca4..cb429a4 100644 --- a/chrome/browser/ui/browser_close_unittest.cc +++ b/chrome/browser/ui/browser_close_unittest.cc
@@ -74,7 +74,7 @@ ADD_FAILURE(); } - bool IsShelfEnabled() override { return true; } + bool IsDownloadUiEnabled() override { return true; } // KeyedService void Shutdown() override {}
diff --git a/chrome/browser/ui/browser_navigator_browsertest.cc b/chrome/browser/ui/browser_navigator_browsertest.cc index 6324510..53c6418 100644 --- a/chrome/browser/ui/browser_navigator_browsertest.cc +++ b/chrome/browser/ui/browser_navigator_browsertest.cc
@@ -12,7 +12,6 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/chrome_navigation_ui_data.h" @@ -703,30 +702,26 @@ EXPECT_EQ(2, browser()->tab_strip_model()->count()); } -// This test verifies that IsTabOpenWithURL() and GetIndexOfExistingTab() -// will not discriminate between http and https. +// This test verifies that SWITCH_TO_TAB will switch to a tab even if the scheme +// mismatches, as long as the rest of the URL does. IN_PROC_BROWSER_TEST_F(BrowserNavigatorTest, SchemeMismatchTabSwitchTest) { - GURL navigate_url("https://maps.google.com/"); - GURL search_url("http://maps.google.com/"); + GURL navigate_url("https://www.chromium.org/"); + GURL search_url("http://www.chromium.org/"); + GURL dino_url("chrome://dino"); - // Generate history so the tab isn't closed. - NavigateHelper(GURL("chrome://dino/"), browser(), - WindowOpenDisposition::CURRENT_TAB, true); - - NavigateHelper(navigate_url, browser(), - WindowOpenDisposition::NEW_BACKGROUND_TAB, true); + NavigateHelper(navigate_url, browser(), WindowOpenDisposition::CURRENT_TAB, + true); + NavigateHelper(dino_url, browser(), WindowOpenDisposition::NEW_FOREGROUND_TAB, + true); // We must be on another tab than the target for it to be found and - // switched to. - EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); - - ChromeAutocompleteProviderClient client(browser()->profile()); - EXPECT_TRUE(client.GetTabMatcher().IsTabOpenWithURL(search_url, nullptr)); + // switched to. To meet that requirement, ensure the dino tab is currently + // active. + EXPECT_EQ(1, browser()->tab_strip_model()->active_index()); NavigateHelper(search_url, browser(), WindowOpenDisposition::SWITCH_TO_TAB, false); - - EXPECT_EQ(1, browser()->tab_strip_model()->active_index()); + EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); } // Make sure that switching tabs preserves the post-focus state (of the @@ -757,49 +752,32 @@ OmniboxFocusState::OMNIBOX_FOCUS_NONE); } -#if BUILDFLAG(IS_LINUX) -// Flaky on Linux Ozone. See https://crbug.com/1230723. -#define MAYBE_SwitchToTabCorrectWindow DISABLED_SwitchToTabCorrectWindow -#elif BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN) -// Flaky on Lacros and Win. See https://crbug.com/674497. -#define MAYBE_SwitchToTabCorrectWindow DISABLED_SwitchToTabCorrectWindow -#else -#define MAYBE_SwitchToTabCorrectWindow SwitchToTabCorrectWindow -#endif // This test verifies that we're picking the correct browser and tab to // switch to. It verifies that we don't recommend the active tab, and that, -// when switching, we don't mistakenly pick the current browser. -IN_PROC_BROWSER_TEST_F(BrowserNavigatorTest, MAYBE_SwitchToTabCorrectWindow) { - const GURL singleton_url("http://maps.google.com/"); +// when switching, we don't mistakenly pick the current browser. Note that this +// test checks which window the new tab was created in, but does not check +// whether the target window was activated - that would require a much slower +// interactive UI test, since we'd have to wait for the async window activation +// to complete to avoid flakes. +IN_PROC_BROWSER_TEST_F(BrowserNavigatorTest, SwitchToTabCorrectWindow) { + const GURL url1("http://example1.chromium.org"); + const GURL url2("http://example2.chromium.org"); // Make singleton tab. - Browser* orig_browser = NavigateHelper( - singleton_url, browser(), WindowOpenDisposition::CURRENT_TAB, true); + Browser* browser1 = + NavigateHelper(url1, browser(), WindowOpenDisposition::CURRENT_TAB, true); // Make a new window with different URL. - Browser* middle_browser = - NavigateHelper(GURL("http://www.google.com/"), orig_browser, - WindowOpenDisposition::NEW_WINDOW, true); - EXPECT_NE(orig_browser, middle_browser); + Browser* browser2 = + NavigateHelper(url2, browser1, WindowOpenDisposition::NEW_WINDOW, true); + EXPECT_NE(browser1, browser2); - ChromeAutocompleteProviderClient client(browser()->profile()); - // We avoid recommending the active tab, because during navigation, we - // actively avoid it (because the user almost certainly doesn't want to - // switch to the tab they're already on). While we are not on the target - // tab, make sure the provider client recommends our other window. - EXPECT_TRUE(client.GetTabMatcher().IsTabOpenWithURL(singleton_url, nullptr)); - - // Navigate to the singleton again. - Browser* test_browser = - NavigateHelper(singleton_url, middle_browser, - WindowOpenDisposition::SWITCH_TO_TAB, false); - - // Make sure we chose the browser with the tab, not simply the current - // browser. - EXPECT_EQ(orig_browser, test_browser); - // Now that we're on the tab, make sure the provider client doesn't - // recommend it. - EXPECT_FALSE(client.GetTabMatcher().IsTabOpenWithURL(singleton_url, nullptr)); + EXPECT_EQ(browser1, + NavigateHelper(url1, browser2, WindowOpenDisposition::SWITCH_TO_TAB, + false)); + EXPECT_EQ(browser2, + NavigateHelper(url2, browser1, WindowOpenDisposition::SWITCH_TO_TAB, + false)); } // TODO(crbug/1272155): Reactivate the test.
diff --git a/chrome/browser/ui/global_media_controls/cast_media_notification_producer.cc b/chrome/browser/ui/global_media_controls/cast_media_notification_producer.cc index 0a23f3c..7fb6fa43 100644 --- a/chrome/browser/ui/global_media_controls/cast_media_notification_producer.cc +++ b/chrome/browser/ui/global_media_controls/cast_media_notification_producer.cc
@@ -33,8 +33,7 @@ if (media_router::GlobalMediaControlsCastStartStopEnabled(profile)) { // Hide a route if it's a mirroring route. if (route.media_source().IsTabMirroringSource() || - route.media_source().IsDesktopMirroringSource() || - route.media_source().IsLocalFileSource()) + route.media_source().IsDesktopMirroringSource()) return true; } else if (route.controller_type() != media_router::RouteControllerType::kGeneric) {
diff --git a/chrome/browser/ui/popup_browsertest.cc b/chrome/browser/ui/popup_browsertest.cc index 444ec3d..1587427 100644 --- a/chrome/browser/ui/popup_browsertest.cc +++ b/chrome/browser/ui/popup_browsertest.cc
@@ -259,7 +259,7 @@ .UpdateDisplay("100+100-801x802,901+100-802x802"); #elif BUILDFLAG(IS_MAC) if (!display::test::VirtualDisplayMacUtil::IsAPIAvailable()) { - GTEST_SKIP() << "Skipping test for MacOS 11.0 and older or Arm Macs."; + GTEST_SKIP() << "Skipping test for MacOS 11.0 and older."; } display::test::VirtualDisplayMacUtil virtual_display_mac_util; virtual_display_mac_util.AddDisplay(
diff --git a/chrome/browser/ui/toolbar/media_router_action_controller.cc b/chrome/browser/ui/toolbar/media_router_action_controller.cc index 8419b198..2e57b19 100644 --- a/chrome/browser/ui/toolbar/media_router_action_controller.cc +++ b/chrome/browser/ui/toolbar/media_router_action_controller.cc
@@ -82,8 +82,7 @@ // In other words, the Cast icon is shown when there are // mirroring or local file sources. return route.media_source().IsTabMirroringSource() || - route.media_source().IsDesktopMirroringSource() || - route.media_source().IsLocalFileSource(); + route.media_source().IsDesktopMirroringSource(); }) != routes.end(); MaybeAddOrRemoveAction(); }
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc index 9e898813..682d3b2e 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc
@@ -156,16 +156,17 @@ // Returns the current index or insert position of `extension_name` in // `parent_view`, based on alphabetical order. -int FindIndex(views::View* parent_view, const std::u16string extension_name) { +size_t FindIndex(views::View* parent_view, + const std::u16string extension_name) { const auto& children = parent_view->children(); - return std::find_if( - children.begin(), children.end(), - [extension_name](views::View* v) { - return base::i18n::ToLower(extension_name) <= - base::i18n::ToLower( - GetMenuItemViewController(v)->GetActionName()); - }) - - children.begin(); + return static_cast<size_t>( + std::find_if(children.begin(), children.end(), + [extension_name](views::View* v) { + return base::i18n::ToLower(extension_name) <= + base::i18n::ToLower( + GetMenuItemViewController(v)->GetActionName()); + }) - + children.begin()); } // Returns the current site pointed by `web_contents`. This method should only @@ -574,7 +575,7 @@ void ExtensionsTabbedMenuView::CreateAndInsertInstalledExtension( const ToolbarActionsModel::ActionId& id, - int index) { + size_t index) { std::unique_ptr<ExtensionActionViewController> controller = ExtensionActionViewController::Create(id, browser_, extensions_container_); @@ -606,7 +607,7 @@ SiteAccessSection* section) { DCHECK(section); - int index = + size_t index = FindIndex(section->items, item->view_controller()->GetActionName()); section->items->AddChildViewAt(std::move(item), index); } @@ -660,7 +661,7 @@ // Reorder item when it is in the same section. if (new_section == section) { item->Update(); - int new_index = + size_t new_index = FindIndex(section->items, item->view_controller()->GetActionName()); section->items->ReorderChildView(item, new_index); return;
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h index 6a8f29e..f665023a 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h
@@ -134,7 +134,7 @@ // newly-added extension. void CreateAndInsertInstalledExtension( const ToolbarActionsModel::ActionId& id, - int index); + size_t index); // Creates and adds a menu item for `id` in its corresponding site access // section if the associated extension has or requests access to the current
diff --git a/chrome/browser/ui/views/extensions/extensions_toolbar_container.cc b/chrome/browser/ui/views/extensions/extensions_toolbar_container.cc index 5a6c1f01..1e0f606 100644 --- a/chrome/browser/ui/views/extensions/extensions_toolbar_container.cc +++ b/chrome/browser/ui/views/extensions/extensions_toolbar_container.cc
@@ -558,7 +558,7 @@ ReorderChildView(GetViewForId(drop_info_->action_id), drop_info_->index); // The extension button is always last. - ReorderChildView(main_item(), -1); + ReorderChildView(main_item(), children().size()); } void ExtensionsToolbarContainer::CreateActions() { @@ -701,16 +701,16 @@ // to display the dragged extension before. We also mirror the event.x() so // that our calculations are consistent with left-to-right. const int offset_into_icon_area = GetMirroredXInView(event.x()); - const int before_icon_unclamped = WidthToIconCount(offset_into_icon_area); + const size_t before_icon_unclamped = WidthToIconCount(offset_into_icon_area); - int visible_icons = model_->pinned_action_ids().size(); + const size_t visible_icons = model_->pinned_action_ids().size(); // Because the user can drag outside the container bounds, we need to clamp // to the valid range. Note that the maximum allowable value is // |visible_icons|, not (|visible_icons| - 1), because we represent the // dragged extension being past the last icon as being "before the (last + 1) // icon". - before_icon = base::clamp(before_icon_unclamped, 0, visible_icons); + before_icon = std::min(before_icon_unclamped, visible_icons); if (!drop_info_.get() || drop_info_->index != before_icon) { drop_info_ = std::make_unique<DropInfo>(data.id(), before_icon);
diff --git a/chrome/browser/ui/views/frame/browser_view_layout.cc b/chrome/browser/ui/views/frame/browser_view_layout.cc index 432a9f3..24e3599 100644 --- a/chrome/browser/ui/views/frame/browser_view_layout.cc +++ b/chrome/browser/ui/views/frame/browser_view_layout.cc
@@ -497,7 +497,8 @@ loading_bar_->SetBounds(vertical_layout_rect_.x(), top - 2, vertical_layout_rect_.width(), separator_height + 2); - top_container_->ReorderChildView(loading_bar_, -1); + top_container_->ReorderChildView(loading_bar_, + top_container_->children().size()); } top += separator_height; } else {
diff --git a/chrome/browser/ui/views/infobars/infobar_view.cc b/chrome/browser/ui/views/infobars/infobar_view.cc index e4d95d5c..7a8b6be 100644 --- a/chrome/browser/ui/views/infobars/infobar_view.cc +++ b/chrome/browser/ui/views/infobars/infobar_view.cc
@@ -194,7 +194,7 @@ // Anything that needs to happen once after all subclasses add their children. if (details.is_add && (details.child == this)) { if (close_button_) - ReorderChildView(close_button_, -1); + ReorderChildView(close_button_, children().size()); RecalculateHeight(); } }
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 c2071bb..567c5e8a 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
@@ -39,12 +39,10 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/arc/test/fake_intent_helper_instance.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/icon_loader.h" #include "components/services/app_service/public/cpp/intent_filter_util.h" #include "components/services/app_service/public/cpp/intent_test_util.h" #include "components/services/app_service/public/cpp/intent_util.h" -#include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_test.h" #include "content/public/test/prerender_test_util.h" #include "content/public/test/test_navigation_observer.h" @@ -187,21 +185,11 @@ auto app = std::make_unique<apps::App>(apps::AppType::kArc, app_id); app->name = app_name; app->intent_filters.push_back(apps_util::MakeIntentFilterForUrlScope(url)); - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - std::vector<apps::AppPtr> apps; - apps.push_back(std::move(app)); - app_service_proxy_->AppRegistryCache().OnApps( - std::move(apps), apps::AppType::kArc, - false /* should_notify_initialized */); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(app)); - app_service_proxy_->AppRegistryCache().OnApps( - std::move(mojom_apps), apps::mojom::AppType::kArc, - false /* should_notify_initialized */); - WaitForAppService(); - } + std::vector<apps::AppPtr> apps; + apps.push_back(std::move(app)); + app_service_proxy_->AppRegistryCache().OnApps( + std::move(apps), apps::AppType::kArc, + false /* should_notify_initialized */); return app_id; }
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_coordinator.cc b/chrome/browser/ui/views/media_router/cast_dialog_coordinator.cc new file mode 100644 index 0000000..fe59a39 --- /dev/null +++ b/chrome/browser/ui/views/media_router/cast_dialog_coordinator.cc
@@ -0,0 +1,98 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" + +#include <memory> + +#include "base/time/time.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/media_router/cast_dialog_controller.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/frame/top_container_view.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_view.h" +#include "chrome/browser/ui/views/media_router/cast_toolbar_button.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "components/media_router/browser/media_router_metrics.h" +#include "ui/views/view.h" +#include "ui/views/view_tracker.h" +#include "ui/views/widget/widget.h" + +namespace media_router { + +void CastDialogCoordinator::ShowDialogWithToolbarAction( + CastDialogController* controller, + Browser* browser, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location) { + BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); + views::View* action_view = browser_view->toolbar()->cast_button(); + DCHECK(action_view); + Show(action_view, views::BubbleBorder::TOP_RIGHT, controller, + browser->profile(), start_time, activation_location); +} + +void CastDialogCoordinator::ShowDialogCenteredForBrowserWindow( + CastDialogController* controller, + Browser* browser, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location) { + Show(BrowserView::GetBrowserViewForBrowser(browser)->top_container(), + views::BubbleBorder::TOP_CENTER, controller, browser->profile(), + start_time, activation_location); +} + +void CastDialogCoordinator::ShowDialogCentered( + const gfx::Rect& bounds, + CastDialogController* controller, + Profile* profile, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location) { + Show(/* anchor_view */ nullptr, views::BubbleBorder::TOP_CENTER, controller, + profile, start_time, activation_location); + GetCastDialogView()->SetAnchorRect(bounds); +} + +void CastDialogCoordinator::Hide() { + if (IsShowing()) + cast_dialog_view_tracker_.view()->GetWidget()->Close(); + // Immediately set the view tracked to nullptr. Widget will be destroyed + // asynchronously. + cast_dialog_view_tracker_.SetView(nullptr); +} + +bool CastDialogCoordinator::IsShowing() const { + return cast_dialog_view_tracker_.view() != nullptr; +} + +void CastDialogCoordinator::Show( + views::View* anchor_view, + views::BubbleBorder::Arrow anchor_position, + CastDialogController* controller, + Profile* profile, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location) { + DCHECK(!start_time.is_null()); + // Hide the previous dialog instance if it exists, since there can only be one + // instance at a time. + Hide(); + auto cast_dialog_view = std::make_unique<CastDialogView>( + anchor_view, anchor_position, controller, profile, start_time, + activation_location); + cast_dialog_view_tracker_.SetView(cast_dialog_view.get()); + views::Widget* widget = views::BubbleDialogDelegateView::CreateBubble( + std::move(cast_dialog_view)); + widget->Show(); +} + +CastDialogView* CastDialogCoordinator::GetCastDialogView() { + return static_cast<CastDialogView*>(cast_dialog_view_tracker_.view()); +} + +views::Widget* CastDialogCoordinator::GetCastDialogWidget() { + return IsShowing() ? GetCastDialogView()->GetWidget() : nullptr; +} + +} // namespace media_router
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_coordinator.h b/chrome/browser/ui/views/media_router/cast_dialog_coordinator.h new file mode 100644 index 0000000..c684a73 --- /dev/null +++ b/chrome/browser/ui/views/media_router/cast_dialog_coordinator.h
@@ -0,0 +1,93 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CAST_DIALOG_COORDINATOR_H_ +#define CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CAST_DIALOG_COORDINATOR_H_ + +#include "base/time/time.h" +#include "components/media_router/browser/media_router_metrics.h" +#include "ui/views/bubble/bubble_border.h" +#include "ui/views/view_tracker.h" + +class Browser; +class Profile; + +namespace gfx { +class Rect; +} + +namespace views { +class View; +class Widget; +} // namespace views + +namespace media_router { + +class CastDialogController; +class CastDialogView; + +class CastDialogCoordinator { + public: + CastDialogCoordinator() = default; + CastDialogCoordinator(const CastDialogCoordinator&) = delete; + CastDialogCoordinator& operator=(const CastDialogCoordinator&) = delete; + ~CastDialogCoordinator() = default; + + // Shows the singleton dialog anchored to the Cast toolbar icon. Requires that + // BrowserActionsContainer exists for |browser|. + void ShowDialogWithToolbarAction( + CastDialogController* controller, + Browser* browser, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location); + + // Shows the singleton dialog anchored to the top-center of the browser + // window. + void ShowDialogCenteredForBrowserWindow( + CastDialogController* controller, + Browser* browser, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location); + + // Shows the singleton dialog anchored to the bottom of |bounds|, horizontally + // centered. + // TODO(crbug.com/1345683): This should be removed if there are no call paths + // in production that result in this method being called. Creating a bubble + // would DCHECK in the current code with a nullptr anchor view and no + // additional handling. + void ShowDialogCentered( + const gfx::Rect& bounds, + CastDialogController* controller, + Profile* profile, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location); + + // No-op if the dialog is currently not shown. + void Hide(); + + bool IsShowing() const; + + CastDialogView* GetCastDialogView(); + + views::Widget* GetCastDialogWidget(); + + private: + // TODO(crbug.com/1346127): Remove friend class. + friend class CastDialogViewTest; + + // Instantiates and shows the singleton dialog. The dialog must not be + // currently shown. + void Show(views::View* anchor_view, + views::BubbleBorder::Arrow anchor_position, + CastDialogController* controller, + Profile* profile, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location); + + views::ViewTracker cast_dialog_view_tracker_; +}; + +} // namespace media_router + +#endif // CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CAST_DIALOG_COORDINATOR_H_
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_coordinator_unittest.cc b/chrome/browser/ui/views/media_router/cast_dialog_coordinator_unittest.cc new file mode 100644 index 0000000..9cba903 --- /dev/null +++ b/chrome/browser/ui/views/media_router/cast_dialog_coordinator_unittest.cc
@@ -0,0 +1,73 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" + +#include <memory> + +#include "base/test/scoped_feature_list.h" +#include "base/time/time.h" +#include "chrome/browser/ui/media_router/cast_dialog_controller.h" +#include "chrome/browser/ui/media_router/media_cast_mode.h" +#include "chrome/browser/ui/media_router/media_route_starter.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/frame/test_with_browser_view.h" +#include "chrome/browser/ui/views/frame/top_container_view.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_view.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "content/public/browser/web_contents.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/test/widget_test.h" +#include "ui/views/widget/widget.h" + +using testing::_; +using testing::Mock; +using testing::NiceMock; + +namespace media_router { + +class MockCastDialogController : public CastDialogController { + public: + MOCK_METHOD(void, AddObserver, (CastDialogController::Observer * observer)); + MOCK_METHOD(void, + RemoveObserver, + (CastDialogController::Observer * observer)); + MOCK_METHOD(void, + StartCasting, + (const std::string& sink_id, MediaCastMode cast_mode)); + MOCK_METHOD(void, StopCasting, (const std::string& route_id)); + MOCK_METHOD(void, ClearIssue, (const Issue::Id& issue_id)); + MOCK_METHOD(content::WebContents*, GetInitiator, ()); + MOCK_METHOD(std::unique_ptr<MediaRouteStarter>, TakeMediaRouteStarter, ()); +}; + +class CastDialogCoordinatorTest : public TestWithBrowserView { + public: + void SetUp() override { TestWithBrowserView::SetUp(); } + + NiceMock<MockCastDialogController> controller_; + CastDialogCoordinator cast_dialog_coordinator_; +}; + +// Tests show and hide for ShowDialogCenteredForBrowserWindow. Defers +// ShowDialogWithToolbarAction to Media Router tests (already covered) since +// additional Media Router services setup is required. +TEST_F(CastDialogCoordinatorTest, ShowAndHideDialog) { + EXPECT_CALL(controller_, AddObserver(_)); + cast_dialog_coordinator_.ShowDialogCenteredForBrowserWindow( + &controller_, browser_view()->browser(), base::Time::Now(), + MediaRouterDialogActivationLocation::PAGE); + EXPECT_TRUE(cast_dialog_coordinator_.IsShowing()); + EXPECT_NE(nullptr, cast_dialog_coordinator_.GetCastDialogWidget()); + views::test::WidgetDestroyedWaiter waiter( + cast_dialog_coordinator_.GetCastDialogWidget()); + EXPECT_CALL(controller_, RemoveObserver(_)); + cast_dialog_coordinator_.Hide(); + waiter.Wait(); + EXPECT_FALSE(cast_dialog_coordinator_.IsShowing()); + EXPECT_EQ(nullptr, cast_dialog_coordinator_.GetCastDialogWidget()); +} + +} // namespace media_router
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_view.cc b/chrome/browser/ui/views/media_router/cast_dialog_view.cc index e2acf87e1..2b0ce82 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_view.cc +++ b/chrome/browser/ui/views/media_router/cast_dialog_view.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/media/router/discovery/access_code/access_code_cast_feature.h" #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/media_router/cast_dialog_controller.h" #include "chrome/browser/ui/media_router/cast_dialog_model.h" #include "chrome/browser/ui/media_router/media_cast_mode.h" @@ -28,8 +27,6 @@ #include "chrome/browser/ui/views/media_router/cast_dialog_access_code_cast_button.h" #include "chrome/browser/ui/views/media_router/cast_dialog_no_sinks_view.h" #include "chrome/browser/ui/views/media_router/cast_dialog_sink_button.h" -#include "chrome/browser/ui/views/media_router/cast_toolbar_button.h" -#include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/browser/ui/webui/access_code_cast/access_code_cast_dialog.h" #include "chrome/grit/generated_resources.h" #include "components/access_code_cast/common/access_code_cast_metrics.h" @@ -53,66 +50,36 @@ namespace media_router { -// static -void CastDialogView::ShowDialogWithToolbarAction( - CastDialogController* controller, - Browser* browser, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location) { - BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); - views::View* action_view = browser_view->toolbar()->cast_button(); - DCHECK(action_view); - ShowDialog(action_view, views::BubbleBorder::TOP_RIGHT, controller, - browser->profile(), start_time, activation_location); -} - -// static -void CastDialogView::ShowDialogCenteredForBrowserWindow( - CastDialogController* controller, - Browser* browser, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location) { - ShowDialog(BrowserView::GetBrowserViewForBrowser(browser)->top_container(), - views::BubbleBorder::TOP_CENTER, controller, browser->profile(), - start_time, activation_location); -} - -// static -void CastDialogView::ShowDialogCentered( - const gfx::Rect& bounds, +CastDialogView::CastDialogView( + views::View* anchor_view, + views::BubbleBorder::Arrow anchor_position, CastDialogController* controller, Profile* profile, const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location) { - ShowDialog(/* anchor_view */ nullptr, views::BubbleBorder::TOP_CENTER, - controller, profile, start_time, activation_location); - instance_->SetAnchorRect(bounds); + MediaRouterDialogActivationLocation activation_location) + : BubbleDialogDelegateView(anchor_view, anchor_position), + controller_(controller), + profile_(profile), + metrics_(start_time, activation_location, profile) { + DCHECK(profile); + SetShowCloseButton(true); + SetButtons(ui::DIALOG_BUTTON_NONE); + set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric( + views::DISTANCE_BUBBLE_PREFERRED_WIDTH)); + sources_button_ = + SetExtraView(std::make_unique<views::MdTextButtonWithDownArrow>( + base::BindRepeating(&CastDialogView::ShowSourcesMenu, + base::Unretained(this)), + l10n_util::GetStringUTF16( + IDS_MEDIA_ROUTER_ALTERNATIVE_SOURCES_BUTTON))); + sources_button_->SetEnabled(false); + ShowNoSinksView(); + MaybeShowAccessCodeCastButton(); } -// static -void CastDialogView::HideDialog() { - if (IsShowing()) - instance_->GetWidget()->Close(); - // We set |instance_| to null here because IsShowing() should be false after - // HideDialog() is called. Not all paths to close the dialog go through - // HideDialog(), so we also set it to null in WindowClosing(), which always - // gets called asynchronously. - instance_ = nullptr; -} - -// static -bool CastDialogView::IsShowing() { - return instance_ != nullptr; -} - -// static -CastDialogView* CastDialogView::GetInstance() { - return instance_; -} - -// static -views::Widget* CastDialogView::GetCurrentDialogWidget() { - return instance_ ? instance_->GetWidget() : nullptr; +CastDialogView::~CastDialogView() { + if (controller_) + controller_->RemoveObserver(this); } std::u16string CastDialogView::GetWindowTitle() const { @@ -160,7 +127,7 @@ void CastDialogView::OnControllerInvalidated() { controller_ = nullptr; - // We don't call HideDialog() here because if the invalidation was caused by + // We don't destroy the dialog here because if the invalidation was caused by // activating the toolbar icon in order to close the dialog, then it would // cause the dialog to immediately open again. } @@ -195,57 +162,6 @@ set_close_on_deactivate(false); } -// static -void CastDialogView::ShowDialog( - views::View* anchor_view, - views::BubbleBorder::Arrow anchor_position, - CastDialogController* controller, - Profile* profile, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location) { - DCHECK(!start_time.is_null()); - // Hide the previous dialog instance if it exists, since there can only be one - // instance at a time. - HideDialog(); - instance_ = new CastDialogView(anchor_view, anchor_position, controller, - profile, start_time, activation_location); - views::Widget* widget = - views::BubbleDialogDelegateView::CreateBubble(instance_); - widget->Show(); -} - -CastDialogView::CastDialogView( - views::View* anchor_view, - views::BubbleBorder::Arrow anchor_position, - CastDialogController* controller, - Profile* profile, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location) - : BubbleDialogDelegateView(anchor_view, anchor_position), - controller_(controller), - profile_(profile), - metrics_(start_time, activation_location, profile) { - DCHECK(profile); - SetShowCloseButton(true); - SetButtons(ui::DIALOG_BUTTON_NONE); - set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric( - views::DISTANCE_BUBBLE_PREFERRED_WIDTH)); - sources_button_ = - SetExtraView(std::make_unique<views::MdTextButtonWithDownArrow>( - base::BindRepeating(&CastDialogView::ShowSourcesMenu, - base::Unretained(this)), - l10n_util::GetStringUTF16( - IDS_MEDIA_ROUTER_ALTERNATIVE_SOURCES_BUTTON))); - sources_button_->SetEnabled(false); - ShowNoSinksView(); - MaybeShowAccessCodeCastButton(); -} - -CastDialogView::~CastDialogView() { - if (controller_) - controller_->RemoveObserver(this); -} - void CastDialogView::Init() { auto* provider = ChromeLayoutProvider::Get(); set_margins(gfx::Insets::TLBR( @@ -264,8 +180,6 @@ void CastDialogView::WindowClosing() { for (Observer& observer : observers_) observer.OnDialogWillClose(this); - if (instance_ == this) - instance_ = nullptr; metrics_.OnCloseDialog(base::Time::Now()); } @@ -497,9 +411,6 @@ GetAccessCodeCastEnabledPref(profile_->GetPrefs()); } -// static -CastDialogView* CastDialogView::instance_ = nullptr; - BEGIN_METADATA(CastDialogView, views::BubbleDialogDelegateView) END_METADATA
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_view.h b/chrome/browser/ui/views/media_router/cast_dialog_view.h index 5ca4d93..d985b61 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_view.h +++ b/chrome/browser/ui/views/media_router/cast_dialog_view.h
@@ -22,7 +22,6 @@ #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/menu/menu_runner.h" -class Browser; class Profile; namespace gfx { @@ -52,44 +51,16 @@ enum SourceType { kTab, kDesktop }; + CastDialogView(views::View* anchor_view, + views::BubbleBorder::Arrow anchor_position, + CastDialogController* controller, + Profile* profile, + const base::Time& start_time, + MediaRouterDialogActivationLocation activation_location); + ~CastDialogView() override; CastDialogView(const CastDialogView&) = delete; CastDialogView& operator=(const CastDialogView&) = delete; - // Shows the singleton dialog anchored to the Cast toolbar icon. Requires that - // BrowserActionsContainer exists for |browser|. - static void ShowDialogWithToolbarAction( - CastDialogController* controller, - Browser* browser, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location); - - // Shows the singleton dialog anchored to the top-center of the browser - // window. - static void ShowDialogCenteredForBrowserWindow( - CastDialogController* controller, - Browser* browser, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location); - - // Shows the singleton dialog anchored to the bottom of |bounds|, horizontally - // centered. - static void ShowDialogCentered( - const gfx::Rect& bounds, - CastDialogController* controller, - Profile* profile, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location); - - // No-op if the dialog is currently not shown. - static void HideDialog(); - - static bool IsShowing(); - - static CastDialogView* GetInstance(); - - // Returns nullptr if the dialog is currently not shown. - static views::Widget* GetCurrentDialogWidget(); - // views::WidgetDelegate: std::u16string GetWindowTitle() const override; @@ -131,30 +102,13 @@ } private: + // TODO(crbug.com/1346127): Remove friend classes. friend class CastDialogViewTest; friend class MediaRouterCastUiForTest; FRIEND_TEST_ALL_PREFIXES(CastDialogViewTest, DisableUnsupportedSinks); FRIEND_TEST_ALL_PREFIXES(CastDialogViewTest, ShowAndHideDialog); FRIEND_TEST_ALL_PREFIXES(CastDialogViewTest, ShowSourcesMenu); - // Instantiates and shows the singleton dialog. The dialog must not be - // currently shown. - static void ShowDialog( - views::View* anchor_view, - views::BubbleBorder::Arrow anchor_position, - CastDialogController* controller, - Profile* profile, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location); - - CastDialogView(views::View* anchor_view, - views::BubbleBorder::Arrow anchor_position, - CastDialogController* controller, - Profile* profile, - const base::Time& start_time, - MediaRouterDialogActivationLocation activation_location); - ~CastDialogView() override; - // views::BubbleDialogDelegateView: void Init() override; void WindowClosing() override; @@ -204,10 +158,6 @@ // has been enabled for this user. bool IsAccessCodeCastingEnabled() const; - // The singleton dialog instance. This is a nullptr when a dialog is not - // shown. - static CastDialogView* instance_; - // Title shown at the top of the dialog. std::u16string dialog_title_;
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_view_browsertest.cc b/chrome/browser/ui/views/media_router/cast_dialog_view_browsertest.cc index 4f97e3a..41a7322 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/media_router/cast_dialog_view_browsertest.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/ui/media_router/ui_media_sink.h" #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "components/media_router/browser/presentation/start_presentation_context.h" #include "components/media_router/common/mojom/media_router.mojom.h" #include "content/public/test/browser_test.h" @@ -85,7 +86,7 @@ // DialogBrowserTest: void PreShow() override { - media_router::CastDialogView::ShowDialogCenteredForBrowserWindow( + cast_dialog_coordinator_.ShowDialogCenteredForBrowserWindow( controller_.get(), browser(), base::Time::Now(), media_router::MediaRouterDialogActivationLocation::TOOLBAR); } @@ -110,11 +111,12 @@ NOTREACHED() << "Unexpected test name " << name; } media_router::CastDialogView* dialog = - media_router::CastDialogView::GetInstance(); + cast_dialog_coordinator_.GetCastDialogView(); dialog->OnModelUpdated(model); } private: + media_router::CastDialogCoordinator cast_dialog_coordinator_; std::unique_ptr<MockCastDialogController> controller_; };
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc b/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc index 9e698dd..ae3f925 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/hover_button.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "chrome/browser/ui/views/media_router/cast_dialog_sink_button.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/testing_profile.h" @@ -109,16 +110,13 @@ } void InitializeDialogWithModel(const CastDialogModel& model) { - EXPECT_CALL(controller_, AddObserver(_)) - .WillOnce( - WithArg<0>(Invoke([this](CastDialogController::Observer* observer) { - dialog_ = static_cast<CastDialogView*>(observer); - }))); - CastDialogView::ShowDialog(anchor_widget_->GetContentsView(), - views::BubbleBorder::TOP_RIGHT, &controller_, - &profile_, base::Time::Now(), - MediaRouterDialogActivationLocation::PAGE); + EXPECT_CALL(controller_, AddObserver(_)); + cast_dialog_coordinator_.Show(anchor_widget_->GetContentsView(), + views::BubbleBorder::TOP_RIGHT, &controller_, + &profile_, base::Time::Now(), + MediaRouterDialogActivationLocation::PAGE); + dialog_ = cast_dialog_coordinator_.GetCastDialogView(); dialog_->OnModelUpdated(model); } @@ -156,30 +154,11 @@ std::unique_ptr<views::Widget> anchor_widget_; NiceMock<MockCastDialogController> controller_; + CastDialogCoordinator cast_dialog_coordinator_; raw_ptr<CastDialogView> dialog_ = nullptr; TestingProfile profile_; }; -TEST_F(CastDialogViewTest, ShowAndHideDialog) { - EXPECT_FALSE(CastDialogView::IsShowing()); - EXPECT_EQ(nullptr, CastDialogView::GetCurrentDialogWidget()); - - EXPECT_CALL(controller_, AddObserver(_)); - CastDialogView::ShowDialog(anchor_widget_->GetContentsView(), - views::BubbleBorder::TOP_RIGHT, &controller_, - &profile_, base::Time::Now(), - MediaRouterDialogActivationLocation::PAGE); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(CastDialogView::IsShowing()); - EXPECT_NE(nullptr, CastDialogView::GetCurrentDialogWidget()); - - EXPECT_CALL(controller_, RemoveObserver(_)); - CastDialogView::HideDialog(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(CastDialogView::IsShowing()); - EXPECT_EQ(nullptr, CastDialogView::GetCurrentDialogWidget()); -} - TEST_F(CastDialogViewTest, PopulateDialog) { CastDialogModel model = CreateModelWithSinks({CreateAvailableSink()}); InitializeDialogWithModel(model);
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc index e2d9b7b..59d8143 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/ui/views/frame/top_container_view.h" #include "chrome/browser/ui/views/global_media_controls/media_dialog_view.h" #include "chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "chrome/browser/ui/views/media_router/cast_dialog_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "components/media_router/browser/presentation/start_presentation_context.h" @@ -70,10 +71,10 @@ if (browser_view) { // Show the Cast dialog anchored to the Cast toolbar button. if (browser_view->toolbar()->cast_button()) { - CastDialogView::ShowDialogWithToolbarAction( + cast_dialog_coordinator_.ShowDialogWithToolbarAction( ui_.get(), browser, dialog_creation_time, activation_location); } else { - CastDialogView::ShowDialogCenteredForBrowserWindow( + cast_dialog_coordinator_.ShowDialogCenteredForBrowserWindow( ui_.get(), browser, dialog_creation_time, activation_location); } } else { @@ -82,12 +83,12 @@ // Set the height to 0 so that the dialog gets anchored to the top of the // window. anchor_bounds.set_height(0); - CastDialogView::ShowDialogCentered(anchor_bounds, ui_.get(), profile, - dialog_creation_time, - activation_location); + cast_dialog_coordinator_.ShowDialogCentered(anchor_bounds, ui_.get(), + profile, dialog_creation_time, + activation_location); } scoped_widget_observations_.AddObservation( - CastDialogView::GetCurrentDialogWidget()); + cast_dialog_coordinator_.GetCastDialogWidget()); if (dialog_creation_callback_) dialog_creation_callback_.Run(); @@ -97,11 +98,12 @@ } void MediaRouterDialogControllerViews::CloseMediaRouterDialog() { - CastDialogView::HideDialog(); + if (IsShowingMediaRouterDialog()) + cast_dialog_coordinator_.Hide(); } bool MediaRouterDialogControllerViews::IsShowingMediaRouterDialog() const { - return CastDialogView::IsShowing(); + return cast_dialog_coordinator_.IsShowing(); } void MediaRouterDialogControllerViews::Reset() {
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h index 0cb51a0..119fe3bc 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h
@@ -10,6 +10,7 @@ #include "base/memory/raw_ptr.h" #include "base/scoped_multi_source_observation.h" #include "chrome/browser/ui/media_router/media_router_ui_service.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "components/media_router/browser/media_router_dialog_controller.h" #include "content/public/browser/web_contents_user_data.h" #include "ui/views/widget/widget.h" @@ -53,6 +54,10 @@ void SetHideMediaButtonForTesting(bool hide); + CastDialogCoordinator& GetCastDialogCoordinatorForTesting() { + return cast_dialog_coordinator_; + } + private: friend class content::WebContentsUserData<MediaRouterDialogControllerViews>; friend class MediaRouterCastUiForTest; @@ -91,6 +96,8 @@ // GlobalMediaControlsCastStartStopEnabled() returns true. std::unique_ptr<MediaRouterUI> ui_; + CastDialogCoordinator cast_dialog_coordinator_; + base::RepeatingClosure dialog_creation_callback_; base::ScopedMultiSourceObservation<views::Widget, views::WidgetObserver>
diff --git a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc index 3a27dc4..93410f4 100644 --- a/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc +++ b/chrome/browser/ui/views/media_router/media_router_dialog_controller_views_browsertest.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/top_container_view.h" #include "chrome/browser/ui/views/global_media_controls/media_dialog_view.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "chrome/browser/ui/views/media_router/cast_dialog_view.h" #include "chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h" #include "chrome/test/base/in_process_browser_test.h" @@ -90,12 +91,16 @@ IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerViewsTest, OpenCloseMediaRouterDialog) { OpenMediaRouterDialog(); - views::Widget* widget = CastDialogView::GetCurrentDialogWidget(); + views::Widget* widget = + dialog_controller_->GetCastDialogCoordinatorForTesting() + .GetCastDialogWidget(); ASSERT_TRUE(widget); EXPECT_TRUE(widget->HasObserver(dialog_controller_)); dialog_controller_->CloseMediaRouterDialog(); EXPECT_FALSE(dialog_controller_->IsShowingMediaRouterDialog()); - EXPECT_EQ(CastDialogView::GetCurrentDialogWidget(), nullptr); + EXPECT_EQ(dialog_controller_->GetCastDialogCoordinatorForTesting() + .GetCastDialogWidget(), + nullptr); } // Regression test for crbug.com/1308341. @@ -103,13 +108,15 @@ MediaBubbleClosedByPlatform) { OpenMediaRouterDialog(); base::RunLoop().RunUntilIdle(); - views::Widget* widget = CastDialogView::GetCurrentDialogWidget(); + CastDialogCoordinator& cast_dialog_coordinator = + dialog_controller_->GetCastDialogCoordinatorForTesting(); + views::Widget* widget = cast_dialog_coordinator.GetCastDialogWidget(); ASSERT_TRUE(widget); EXPECT_TRUE(widget->HasObserver(dialog_controller_)); // The media bubble usually will close itself on deactivation, but // crbug.com/1308341 shows a state where the browser is not responsive // to activation change. Simulate that. - CastDialogView::GetInstance()->set_close_on_deactivate(false); + cast_dialog_coordinator.GetCastDialogView()->set_close_on_deactivate(false); views::test::WidgetDestroyedWaiter waiter(widget); widget->native_widget_private()->Close(); waiter.Wait();
diff --git a/chrome/browser/ui/views/media_router/media_router_ui_interactive_uitest.cc b/chrome/browser/ui/views/media_router/media_router_ui_interactive_uitest.cc index 513c7992..d0f78b9 100644 --- a/chrome/browser/ui/views/media_router/media_router_ui_interactive_uitest.cc +++ b/chrome/browser/ui/views/media_router/media_router_ui_interactive_uitest.cc
@@ -18,8 +18,10 @@ #include "chrome/browser/ui/toolbar/media_router_action_controller.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/media_router/app_menu_test_api.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "chrome/browser/ui/views/media_router/cast_dialog_view.h" #include "chrome/browser/ui/views/media_router/cast_toolbar_button.h" +#include "chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" @@ -51,7 +53,12 @@ } views::Widget* GetDialogWidget() { - return CastDialogView::GetCurrentDialogWidget(); + // interactive_ui_tests are not run on android, so + // MediaRouterDialogControllerViews is the only implementation of + // MediaRouterDialogController. + return static_cast<MediaRouterDialogControllerViews*>(GetDialogController()) + ->GetCastDialogCoordinatorForTesting() + .GetCastDialogWidget(); } ui::SimpleMenuModel* GetIconContextMenu() {
diff --git a/chrome/browser/ui/views/overlay/document_overlay_window_views.cc b/chrome/browser/ui/views/overlay/document_overlay_window_views.cc index 27e776f..be17e30 100644 --- a/chrome/browser/ui/views/overlay/document_overlay_window_views.cc +++ b/chrome/browser/ui/views/overlay/document_overlay_window_views.cc
@@ -512,7 +512,8 @@ resize_handle_view_->SetQuadrant(quadrant); controls_container_view_->ReorderChildView(close_controls_view_, 0); controls_container_view_->ReorderChildView(back_to_tab_image_button_, 1); - controls_container_view_->ReorderChildView(resize_handle_view_, -1); + controls_container_view_->ReorderChildView( + resize_handle_view_, controls_container_view_->children().size()); // FIXME: controls_container_view_->InvalidateLayout() isn't sufficient? controls_container_view_->Layout(); } @@ -526,8 +527,11 @@ // +-------------------------------------------+ if (controls_container_view_->GetIndexOf(resize_handle_view_) != 0) { resize_handle_view_->SetQuadrant(quadrant); - controls_container_view_->ReorderChildView(back_to_tab_image_button_, -1); - controls_container_view_->ReorderChildView(close_controls_view_, -1); + controls_container_view_->ReorderChildView( + back_to_tab_image_button_, + controls_container_view_->children().size()); + controls_container_view_->ReorderChildView( + close_controls_view_, controls_container_view_->children().size()); controls_container_view_->ReorderChildView(resize_handle_view_, 0); // FIXME: controls_container_view_->InvalidateLayout() isn't sufficient? controls_container_view_->Layout();
diff --git a/chrome/browser/ui/views/side_panel/side_panel.cc b/chrome/browser/ui/views/side_panel/side_panel.cc index 523959d..b780cec 100644 --- a/chrome/browser/ui/views/side_panel/side_panel.cc +++ b/chrome/browser/ui/views/side_panel/side_panel.cc
@@ -212,7 +212,7 @@ UpdateVisibility(); // Reorder `border_view_` to be last so that it gets painted on top, even if // an added child also paints to a layer. - ReorderChildView(border_view_, -1); + ReorderChildView(border_view_, children().size()); } void SidePanel::OnChildViewRemoved(View* observed_view, View* child) {
diff --git a/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator_unittest.cc b/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator_unittest.cc index 20083d2c..94cb3190 100644 --- a/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator_unittest.cc +++ b/chrome/browser/ui/views/side_panel/user_note/user_note_ui_coordinator_unittest.cc
@@ -37,13 +37,13 @@ class MockUserNoteStorage : public user_notes::UserNoteStorage { public: void GetNoteMetadataForUrls( - const std::vector<GURL>& urls, + const user_notes::UserNoteStorage::UrlSet& urls, base::OnceCallback<void(user_notes::UserNoteMetadataSnapshot)> callback) override { std::move(callback).Run(user_notes::UserNoteMetadataSnapshot()); } - void GetNotesById(const std::vector<base::UnguessableToken>& ids, + void GetNotesById(const user_notes::UserNoteStorage::IdSet& ids, base::OnceCallback<void( std::vector<std::unique_ptr<user_notes::UserNote>>)> callback) override {
diff --git a/chrome/browser/ui/views/side_search/unified_side_search_controller_interactive_uitest.cc b/chrome/browser/ui/views/side_search/unified_side_search_controller_interactive_uitest.cc index 5766873..385a887 100644 --- a/chrome/browser/ui/views/side_search/unified_side_search_controller_interactive_uitest.cc +++ b/chrome/browser/ui/views/side_search/unified_side_search_controller_interactive_uitest.cc
@@ -247,7 +247,14 @@ EXPECT_FALSE(side_panel->GetVisible()); } -IN_PROC_BROWSER_TEST_F(SideSearchV2Test, SidePanelCrashesCloseSidePanel) { +#if BUILDFLAG(IS_MAC) +// TODO(crbug.com/1347306): This test is flakey on macOS. +#define MAYBE_SidePanelCrashesCloseSidePanel \ + DISABLED_SidePanelCrashesCloseSidePanel +#else +#define MAYBE_SidePanelCrashesCloseSidePanel SidePanelCrashesCloseSidePanel +#endif +IN_PROC_BROWSER_TEST_F(SideSearchV2Test, MAYBE_SidePanelCrashesCloseSidePanel) { auto* browser_view = BrowserViewFor(browser()); auto* coordinator = browser_view->side_panel_coordinator(); coordinator->SetNoDelaysForTesting();
diff --git a/chrome/browser/ui/views/tabs/tab_container.cc b/chrome/browser/ui/views/tabs/tab_container.cc index 2cbcaf4f..a1308b9 100644 --- a/chrome/browser/ui/views/tabs/tab_container.cc +++ b/chrome/browser/ui/views/tabs/tab_container.cc
@@ -1172,13 +1172,13 @@ std::find(slots.begin(), slots.end(), slot_view) - slots.begin(); // Find the index in children() that corresponds to |target_slot_index|. size_t view_index = 0; - for (size_t slot_index = 0; slot_index < target_slot_index; slot_index++) { + for (size_t slot_index = 0; slot_index < target_slot_index; ++slot_index) { // If we don't own this view, skip it *without* advancing in children(). if (slots[slot_index]->parent() != this) continue; if (view_index == children().size()) break; - view_index++; + ++view_index; } ReorderChildView(slot_view, view_index);
diff --git a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view_browsertest.cc b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view_browsertest.cc index 6a98955..036e70af 100644 --- a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view_browsertest.cc +++ b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view_browsertest.cc
@@ -125,8 +125,9 @@ // This test verifies that the App Identity Update dialog closes if the app that // was asking for an identity change is uninstalled while the dialog is open. +// Disabled due to flake. https://crbug.com/1347280 IN_PROC_BROWSER_TEST_F(WebAppIdentityUpdateConfirmationViewBrowserTest, - CloseAppIdUpdateDialogOnUninstall) { + DISABLED_CloseAppIdUpdateDialogOnUninstall) { views::NamedWidgetShownWaiter app_id_waiter( views::test::AnyWidgetTestPasskey(), "WebAppIdentityUpdateConfirmationView");
diff --git a/chrome/browser/ui/webui/chromeos/cloud_upload/cloud_upload_dialog.cc b/chrome/browser/ui/webui/chromeos/cloud_upload/cloud_upload_dialog.cc index 204533d8..46d2eac 100644 --- a/chrome/browser/ui/webui/chromeos/cloud_upload/cloud_upload_dialog.cc +++ b/chrome/browser/ui/webui/chromeos/cloud_upload/cloud_upload_dialog.cc
@@ -6,9 +6,13 @@ #include "base/logging.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/webui_url_constants.h" +#include "chrome/grit/cloud_upload_resources.h" +#include "chrome/grit/cloud_upload_resources_map.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" +#include "services/network/public/mojom/content_security_policy.mojom.h" namespace chromeos::cloud_upload { @@ -40,8 +44,11 @@ CloudUploadDialogUI::CloudUploadDialogUI(content::WebUI* web_ui) : ui::WebDialogUI(web_ui) { - content::WebUIDataSource::CreateAndAdd(Profile::FromWebUI(web_ui), - chrome::kChromeUICloudUploadHost); + content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd( + Profile::FromWebUI(web_ui), chrome::kChromeUICloudUploadHost); + webui::SetupWebUIDataSource( + source, base::make_span(kCloudUploadResources, kCloudUploadResourcesSize), + IDR_CLOUD_UPLOAD_MAIN_HTML); } CloudUploadDialogUI::~CloudUploadDialogUI() = default;
diff --git a/chrome/browser/ui/webui/settings/ash/os_apps_page/app_notification_handler_unittest.cc b/chrome/browser/ui/webui/settings/ash/os_apps_page/app_notification_handler_unittest.cc index 08d155b28..eff757e 100644 --- a/chrome/browser/ui/webui/settings/ash/os_apps_page/app_notification_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/ash/os_apps_page/app_notification_handler_unittest.cc
@@ -16,7 +16,6 @@ #include "chrome/test/base/testing_profile.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" -#include "components/services/app_service/public/cpp/features.h" #include "components/services/app_service/public/cpp/permission.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -146,17 +145,8 @@ void UpdateAppRegistryCache(std::vector<apps::AppPtr>& fake_apps, apps::AppType app_type) { - if (base::FeatureList::IsEnabled( - apps::kAppServiceOnAppUpdateWithoutMojom)) { - app_service_proxy_->AppRegistryCache().OnApps(std::move(fake_apps), - app_type, false); - } else { - std::vector<apps::mojom::AppPtr> mojom_apps; - mojom_apps.push_back(apps::ConvertAppToMojomApp(fake_apps[0])); - app_service_proxy_->AppRegistryCache().OnApps( - std::move(mojom_apps), apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + app_service_proxy_->AppRegistryCache().OnApps(std::move(fake_apps), + app_type, false); } bool CheckIfFakeAppInList(std::string fake_id) {
diff --git a/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc b/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc index 1517811..101f560b 100644 --- a/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc
@@ -27,6 +27,7 @@ #include "chromeos/ash/components/network/network_state_handler.h" #include "components/onc/onc_constants.h" #include "components/prefs/pref_service.h" +#include "components/services/app_service/public/cpp/features.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "third_party/cros_system_api/dbus/service_constants.h"
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 14cea68..0ddcc77 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
@@ -61,8 +61,6 @@ #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" -#include "components/services/app_service/public/cpp/features.h" -#include "components/services/app_service/public/mojom/types.mojom.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/ukm/test_ukm_recorder.h" #include "content/public/browser/browsing_data_remover.h" @@ -140,15 +138,8 @@ MakeApp(web_app::GenerateAppId(/*manifest_id=*/absl::nullopt, start_url), apps::AppType::kWeb, start_url.spec(), apps::Readiness::kReady, apps::InstallReason::kSync)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - cache.OnApps(std::move(deltas), apps::AppType::kWeb, - /*should_notify_initialized=*/true); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - mojom_deltas.push_back(apps::ConvertAppToMojomApp(deltas[0])); - cache.OnApps(std::move(mojom_deltas), apps::mojom::AppType::kWeb, - /*should_notify_initialized=*/true); - } + cache.OnApps(std::move(deltas), apps::AppType::kWeb, + /*should_notify_initialized=*/true); } } // namespace
diff --git a/chrome/browser/ui/webui/signin/profile_picker_ui.cc b/chrome/browser/ui/webui/signin/profile_picker_ui.cc index bd84023..afc6539 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_ui.cc +++ b/chrome/browser/ui/webui/signin/profile_picker_ui.cc
@@ -51,6 +51,9 @@ constexpr int kMinimumPickerSizePx = 620; bool IsBrowserSigninAllowed() { +#if BUILDFLAG(IS_CHROMEOS) + return true; +#else policy::PolicyService* policy_service = g_browser_process->policy_service(); DCHECK(policy_service); const policy::PolicyMap& policies = policy_service->GetPolicies( @@ -65,6 +68,7 @@ return static_cast<policy::BrowserSigninMode>( browser_signin_value->GetInt()) != policy::BrowserSigninMode::kDisabled; +#endif } std::string GetManagedDeviceDisclaimer() {
diff --git a/chrome/browser/ui/zoom/chrome_zoom_level_prefs.cc b/chrome/browser/ui/zoom/chrome_zoom_level_prefs.cc index 5004f8a..ae4c873 100644 --- a/chrome/browser/ui/zoom/chrome_zoom_level_prefs.cc +++ b/chrome/browser/ui/zoom/chrome_zoom_level_prefs.cc
@@ -239,4 +239,14 @@ zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback(base::BindRepeating( &ChromeZoomLevelPrefs::OnZoomLevelChanged, base::Unretained(this))); + +// On Android, the default zoom level is controlled by the Java-side UI and not +// the settings flow as it is with other platforms. For Android, we will pass an +// extra callback to the HostZoomMapImpl for setting the default zoom Pref when +// Java sends an update through the JNI. The HostZoomMapImpl cannot directly +// depend on this file, which will save the Pref to the storage partition. +#if BUILDFLAG(IS_ANDROID) + host_zoom_map_->SetDefaultZoomLevelPrefCallback(base::BindRepeating( + &ChromeZoomLevelPrefs::SetDefaultZoomLevelPref, base::Unretained(this))); +#endif }
diff --git a/chrome/browser/upgrade_detector/upgrade_detector.cc b/chrome/browser/upgrade_detector/upgrade_detector.cc index 9ceebe4..a27879a 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector.cc +++ b/chrome/browser/upgrade_detector/upgrade_detector.cc
@@ -347,6 +347,15 @@ observer.OnCriticalUpgradeInstalled(); } +void UpgradeDetector::NotifyUpdateDeferred() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (observer_list_.empty()) + return; + + for (auto& observer : observer_list_) + observer.OnUpdateDeferred(); +} + void UpgradeDetector::NotifyUpdateOverCellularAvailable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (observer_list_.empty())
diff --git a/chrome/browser/upgrade_detector/upgrade_detector.h b/chrome/browser/upgrade_detector/upgrade_detector.h index c5a5869..3f5c4a41 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector.h +++ b/chrome/browser/upgrade_detector/upgrade_detector.h
@@ -254,6 +254,9 @@ // expected. void NotifyCriticalUpgradeInstalled(); + // Notifies that an update is downloaded but deferred. + void NotifyUpdateDeferred(); + // The function that sends out a notification that lets the rest of the UI // know we should notify the user that a new update is available to download // over cellular connection.
diff --git a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc index 1371a5b..248f2ba4e 100644 --- a/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc +++ b/chrome/browser/upgrade_detector/upgrade_detector_chromeos.cc
@@ -208,6 +208,11 @@ // Update engine broadcasts this state only when update is available but // downloading over cellular connection requires user's agreement. NotifyUpdateOverCellularAvailable(); + } else if (status.current_operation() == + update_engine::Operation::UPDATED_BUT_DEFERRED) { + // Update engine broadcasts this state when update is downloaded but + // deferred. + NotifyUpdateDeferred(); } else if (!update_in_progress_ && status.current_operation() == update_engine::Operation::DOWNLOADING) {
diff --git a/chrome/browser/upgrade_detector/upgrade_observer.h b/chrome/browser/upgrade_detector/upgrade_observer.h index 234a019..c5699ab 100644 --- a/chrome/browser/upgrade_detector/upgrade_observer.h +++ b/chrome/browser/upgrade_detector/upgrade_observer.h
@@ -7,6 +7,9 @@ class UpgradeObserver { public: + // Triggered when a software update is downloaded but deferred. + virtual void OnUpdateDeferred() {} + // Triggered when a software update is available, but downloading requires // user's agreement as current connection is cellular. virtual void OnUpdateOverCellularAvailable() {}
diff --git a/chrome/browser/web_applications/BUILD.gn b/chrome/browser/web_applications/BUILD.gn index 3b1a77d..987a646 100644 --- a/chrome/browser/web_applications/BUILD.gn +++ b/chrome/browser/web_applications/BUILD.gn
@@ -87,8 +87,6 @@ "policy/web_app_policy_constants.h", "policy/web_app_policy_manager.cc", "policy/web_app_policy_manager.h", - "policy/web_app_settings_policy_handler.cc", - "policy/web_app_settings_policy_handler.h", "preinstalled_app_install_features.cc", "preinstalled_app_install_features.h", "preinstalled_web_app_config_utils.cc", @@ -246,6 +244,13 @@ ] } + if (!is_android && !is_chromeos) { + sources += [ + "policy/web_app_settings_policy_handler.cc", + "policy/web_app_settings_policy_handler.h", + ] + } + # Enable the "exit_time_destructors" warning here to avoid accidentally # adding exit time destructors and because the flag is not enabled by default. # TODO(http://crbug.com/101600): Remove once exit_time_destructors is enabled @@ -551,11 +556,14 @@ if (is_win || is_mac || is_linux) { sources += [ "os_integration/url_handler_manager_impl_unittest.cc", - "policy/web_app_settings_policy_handler_unittest.cc", "url_handler_prefs_unittest.cc", ] } + if (!is_android && !is_chromeos) { + sources += [ "policy/web_app_settings_policy_handler_unittest.cc" ] + } + deps = [ ":web_applications", ":web_applications_test_support",
diff --git a/chrome/browser/web_applications/adjustments/preinstalled_web_app_duplication_fixer.cc b/chrome/browser/web_applications/adjustments/preinstalled_web_app_duplication_fixer.cc index cbda14a..388697e9 100644 --- a/chrome/browser/web_applications/adjustments/preinstalled_web_app_duplication_fixer.cc +++ b/chrome/browser/web_applications/adjustments/preinstalled_web_app_duplication_fixer.cc
@@ -101,7 +101,7 @@ std::vector<std::string> installed_chrome_apps; apps::AppServiceProxyFactory::GetForProfile(&profile_) ->AppRegistryCache() - .ForAllApps([&installed_web_apps, + .ForEachApp([&installed_web_apps, &installed_chrome_apps](const apps::AppUpdate& update) { if (update.Readiness() != apps::Readiness::kReady) return;
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 8954379d..fdc6e96 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1658771855-3ac45034f7eba4c709606006fb28cba1b88dd52c.profdata +chrome-linux-main-1658793396-2b3e91d50dec89dc5f964c378ad2211d69f34f79.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index a3b5106..cef17f8 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1658750173-3b01b102cd09d7441b13144d51ecd6f95eff3fdd.profdata +chrome-mac-main-1658771855-538ceb72d7f9bdf56917ebcb768fe5e716b0ac83.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index fd5ffc8b..73eaa8a 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1658750173-b3c397c9a7c1ec5f404c07bf0d4e1a693698978c.profdata +chrome-win32-main-1658782695-800f94790381496901cbb518b4b29339c2060272.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index fb31e4ec..1a85403 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1658750173-15ad2fd38d13b30fa368a653c0d4a3d23f97b8af.profdata +chrome-win64-main-1658782695-1e7ad3e3542b9180a1af0f81cfcbaa527a0ed821.profdata
diff --git a/chrome/chrome_paks.gni b/chrome/chrome_paks.gni index 5691ef5..67ac969 100644 --- a/chrome/chrome_paks.gni +++ b/chrome/chrome_paks.gni
@@ -246,6 +246,7 @@ "$root_gen_dir/chrome/audio_resources.pak", "$root_gen_dir/chrome/bluetooth_pairing_dialog_resources.pak", "$root_gen_dir/chrome/browser/supervised_user/supervised_user_unscaled_resources.pak", + "$root_gen_dir/chrome/cloud_upload_resources.pak", "$root_gen_dir/chrome/common/chromeos/extensions/chromeos_system_extensions_resources.pak", "$root_gen_dir/chrome/emoji_picker_resources.pak", "$root_gen_dir/chrome/gaia_action_buttons_resources.pak", @@ -309,6 +310,7 @@ "//chrome/browser/resources/chromeos/arc_account_picker:resources", "//chrome/browser/resources/chromeos/assistant_optin:resources", "//chrome/browser/resources/chromeos/audio:resources", + "//chrome/browser/resources/chromeos/cloud_upload:resources", "//chrome/browser/resources/chromeos/emoji_picker:resources", "//chrome/browser/resources/chromeos/gaia_action_buttons:resources", "//chrome/browser/resources/chromeos/launcher_internals:resources",
diff --git a/chrome/common/extensions/api/autotest_private.idl b/chrome/common/extensions/api/autotest_private.idl index df3b1e6f..6ed0469 100644 --- a/chrome/common/extensions/api/autotest_private.idl +++ b/chrome/common/extensions/api/autotest_private.idl
@@ -261,9 +261,24 @@ callback IsLacrosPrimaryBrowserCallback = void (boolean primary); + // crosapi::BrowserManager::State + enum LacrosState { + NotInitialized, + Mounting, + Unavailable, + Stopped, + CreatingLogFile, + Starting, + Running, + Terminating + }; + dictionary LacrosInfo { - // True iff lacros is running currently. + // True iff lacros is running currently. TODO(neis): Remove once the Tast + // use has been eliminated. boolean isRunning; + // The state of lacros. + LacrosState state; // True iff keepalive is enabled for lacros. boolean isKeepAlive; // Path to lacros-chrome directory. Note that this may change over time if
diff --git a/chrome/common/media/cdm_registration.cc b/chrome/common/media/cdm_registration.cc index 7a1d144..16f338a3 100644 --- a/chrome/common/media/cdm_registration.cc +++ b/chrome/common/media/cdm_registration.cc
@@ -207,7 +207,7 @@ // We currently support VP9, H264 and HEVC video formats with // decrypt-and-decode. Not specifying any profiles to indicate that all // relevant profiles should be considered supported. - const std::vector<media::VideoCodecProfile> kAllProfiles = {}; + const media::VideoCodecInfo kAllProfiles; capability.video_codecs.emplace(media::VideoCodec::kVP9, kAllProfiles); #if BUILDFLAG(USE_PROPRIETARY_CODECS) capability.video_codecs.emplace(media::VideoCodec::kH264, kAllProfiles);
diff --git a/chrome/renderer/cart/commerce_hint_agent.cc b/chrome/renderer/cart/commerce_hint_agent.cc index 1cc9efe1..0ae3e3f5 100644 --- a/chrome/renderer/cart/commerce_hint_agent.cc +++ b/chrome/renderer/cart/commerce_hint_agent.cc
@@ -209,7 +209,7 @@ #if !BUILDFLAG(IS_ANDROID) return base::GetFieldTrialParamByFeatureAsBool( ntp_features::kNtpChromeCartModule, - ntp_features::kNtpChromeCartModuleHeuristicsImprovementParam, false); + ntp_features::kNtpChromeCartModuleHeuristicsImprovementParam, true); #else return base::GetFieldTrialParamByFeatureAsBool( commerce::kCommerceHintAndroid,
diff --git a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc index 7327b91c..fa53e3d 100644 --- a/chrome/renderer/cart/commerce_hint_agent_browsertest.cc +++ b/chrome/renderer/cart/commerce_hint_agent_browsertest.cc
@@ -136,6 +136,11 @@ const cart_db::ChromeCartContentProto kMockAmazonProto = BuildProto(kMockAmazon, kMockAmazonURL); +const char kMockWalmart[] = "walmart.com"; +const char kMockWalmartURL[] = "https://www.walmart.com/cart"; +const cart_db::ChromeCartContentProto kMockWalmartProto = + BuildProto(kMockWalmart, kMockWalmartURL); + using ShoppingCarts = std::vector<SessionProtoDB<cart_db::ChromeCartContentProto>::KeyAndValue>; const ShoppingCarts kExpectedExampleFallbackCart = { @@ -148,6 +153,7 @@ const ShoppingCarts kExpectedExampleWithProductsWithoutSaved = { {kMockExample, kMockExampleProtoWithProductsWithoutSaved}}; const ShoppingCarts kExpectedAmazon = {{kMockAmazon, kMockAmazonProto}}; +const ShoppingCarts kExpectedWalmart = {{kMockWalmart, kMockWalmartProto}}; const ShoppingCarts kEmptyExpected = {}; #endif @@ -480,11 +486,11 @@ #if !BUILDFLAG(IS_ANDROID) IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByForm_WithWrongLink) { // Mismatching eTLD+1 domain uses cart URL in the look-up table. - NavigateToURL("https://amazon.com/product.html"); + NavigateToURL("https://walmart.com/product.html"); SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart"); WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1); - WaitForCartCount(kExpectedAmazon); + WaitForCartCount(kExpectedWalmart); ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1); } #endif @@ -576,7 +582,7 @@ // This page has three products. NavigateToURL("https://www.guitarcenter.com/cart.html"); #if !BUILDFLAG(IS_ANDROID) - WaitForProductCount(kExpectedExampleWithProducts); + WaitForProductCount(kExpectedExampleWithProductsWithoutSaved); #endif WaitForUmaCount("Commerce.Carts.ExtractionExecutionTime", 1); WaitForUmaCount("Commerce.Carts.ExtractionLongestTaskTime", 1); @@ -1109,35 +1115,6 @@ WaitForCartCount(kExpectedExampleFallbackCart); } - -class CommerceHintImprovementTest : public CommerceHintAgentTest { - public: - void SetUpInProcessBrowserTestFixture() override { - scoped_feature_list_.InitWithFeaturesAndParameters( - {{ntp_features::kNtpChromeCartModule, - {{ntp_features::kNtpChromeCartModuleHeuristicsImprovementParam, - "true"}, - {"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"}, - // These two are for manual testing only. - // Use --vmodule='commerce_*=2'. - {"cart-extraction-min-task-time", "1s"}, - {"cart-extraction-duty-cycle", "0.5"}, - // Extend timeout to avoid flakiness. - {"cart-extraction-timeout", "1m"}}}}, - {optimization_guide::features::kOptimizationHints}); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(CommerceHintImprovementTest, ExtractCart) { - // This page has three products but should ignore the one in saved for later - // section. - NavigateToURL("https://www.guitarcenter.com/cart.html"); - - WaitForProductCount(kExpectedExampleWithProductsWithoutSaved); -} #endif // !BUILDFLAG(IS_ANDROID) // Product extraction would always timeout and return empty results.
diff --git a/chrome/renderer/media/chrome_key_systems.cc b/chrome/renderer/media/chrome_key_systems.cc index f3cf849..b11360e 100644 --- a/chrome/renderer/media/chrome_key_systems.cc +++ b/chrome/renderer/media/chrome_key_systems.cc
@@ -58,7 +58,7 @@ #if BUILDFLAG(ENABLE_WIDEVINE) SupportedCodecs GetVP9Codecs( - const std::vector<media::VideoCodecProfile>& profiles) { + const base::flat_set<media::VideoCodecProfile>& profiles) { if (profiles.empty()) { // If no profiles are specified, then all are supported. return media::EME_CODEC_VP9_PROFILE0 | media::EME_CODEC_VP9_PROFILE2; @@ -85,7 +85,7 @@ #if BUILDFLAG(ENABLE_PLATFORM_HEVC) SupportedCodecs GetHevcCodecs( - const std::vector<media::VideoCodecProfile>& profiles) { + const base::flat_set<media::VideoCodecProfile>& profiles) { #if BUILDFLAG(IS_CHROMEOS_LACROS) if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kLacrosEnablePlatformHevc)) { @@ -152,13 +152,13 @@ // For compatibility with older CDMs different profiles are only used // with some video codecs. - for (const auto& codec : capability.video_codecs) { - switch (codec.first) { + for (const auto& [codec, video_codec_info] : capability.video_codecs) { + switch (codec) { case media::VideoCodec::kVP8: supported_codecs |= media::EME_CODEC_VP8; break; case media::VideoCodec::kVP9: - supported_codecs |= GetVP9Codecs(codec.second); + supported_codecs |= GetVP9Codecs(video_codec_info.video_codec_profiles); break; case media::VideoCodec::kAV1: supported_codecs |= media::EME_CODEC_AV1; @@ -170,11 +170,12 @@ #endif // BUILDFLAG(USE_PROPRIETARY_CODECS) #if BUILDFLAG(ENABLE_PLATFORM_HEVC) case media::VideoCodec::kHEVC: - supported_codecs |= GetHevcCodecs(codec.second); + supported_codecs |= + GetHevcCodecs(video_codec_info.video_codec_profiles); break; #endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) default: - DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec.first); + DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec); break; } }
diff --git a/chrome/services/sharing/nearby/platform.cc b/chrome/services/sharing/nearby/platform.cc index ba9e403..e3dcb9781 100644 --- a/chrome/services/sharing/nearby/platform.cc +++ b/chrome/services/sharing/nearby/platform.cc
@@ -169,8 +169,9 @@ std::unique_ptr<BluetoothClassicMedium> ImplementationPlatform::CreateBluetoothClassicMedium( api::BluetoothAdapter& adapter) { - // Ignore the provided |adapter| argument. It provides no interface useful - // to implement chrome::BluetoothClassicMedium. + // Ignore the provided |adapter| argument; it is a reference to the object + // created by ImplementationPlatform::CreateBluetoothAdapter(). Instead, + // directly use the cached bluetooth::mojom::Adapter. auto& connections = connections::NearbyConnections::GetInstance(); const mojo::SharedRemote<bluetooth::mojom::Adapter>& bluetooth_adapter = @@ -184,8 +185,9 @@ std::unique_ptr<BleMedium> ImplementationPlatform::CreateBleMedium( api::BluetoothAdapter& adapter) { - // Ignore the provided |adapter| argument. It provides no interface useful - // to implement chrome::BleMedium. + // Ignore the provided |adapter| argument; it is a reference to the object + // created by ImplementationPlatform::CreateBluetoothAdapter(). Instead, + // directly use the cached bluetooth::mojom::Adapter. auto& connections = connections::NearbyConnections::GetInstance(); const mojo::SharedRemote<bluetooth::mojom::Adapter>& bluetooth_adapter =
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 37d3772..6a37722c 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2439,7 +2439,10 @@ deps += [ "//components/safe_browsing/content/common/proto:download_file_types_proto" ] } - if (enable_basic_printing && enable_pdf) { + # TODO(crbug.com/1240796): Page.printToPdf is currently available only when + # Chrome is running in headless mode and native headless mode is currently + # available only on Linux, Windows and Mac platforms. + if (enable_basic_printing && enable_pdf && (is_linux || is_win || is_mac)) { sources += [ "../browser/devtools/protocol/devtools_printtopdf_browsertest.cc" ] } @@ -7927,6 +7930,8 @@ "//chrome/browser/chromeos/extensions/contact_center_insights/contact_center_insights_extension_manager_unittest.cc", ] deps += [ "//chromeos/dbus/missive:missive" ] + } else { + sources += [ "../browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc" ] } if (is_chromeos_ash) { @@ -7973,10 +7978,7 @@ "//net:test_support", ] } else { - sources += [ - "../browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc", - "../browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc", - ] + sources += [ "../browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc" ] deps += [ "//components/enterprise:test_support" ] } @@ -8032,7 +8034,6 @@ } else { sources += [ "../browser/lifetime/switch_utils_unittest.cc", - "../browser/net/disk_cache_dir_policy_handler_unittest.cc", "../browser/profiles/profile_list_desktop_unittest.cc", "../browser/profiles/profile_statistics_unittest.cc", "../browser/ui/signin/profile_colors_util_unittest.cc", @@ -8242,9 +8243,17 @@ if (is_linux || is_mac || is_win) { sources += [ "../browser/accessibility/soda_installer_impl_unittest.cc", + "../browser/browser_switcher/alternative_browser_driver_unittest.cc", + "../browser/browser_switcher/browser_switcher_navigation_throttle_unittest.cc", + "../browser/browser_switcher/browser_switcher_prefs_unittest.cc", + "../browser/browser_switcher/browser_switcher_sitelist_unittest.cc", + "../browser/browser_switcher/ieem_sitelist_parser_unittest.cc", + "../browser/browser_switcher/mock_alternative_browser_driver.cc", + "../browser/browser_switcher/mock_alternative_browser_driver.h", "../browser/enterprise/connectors/device_trust/attestation/desktop/desktop_attestation_service_unittest.cc", "../browser/enterprise/remote_commands/rotate_attestation_credential_job_unittest.cc", "../browser/enterprise/signals/user_delegate_impl_unittest.cc", + "../browser/net/disk_cache_dir_policy_handler_unittest.cc", "../browser/ui/webui/ntp/app_launcher_handler_unittest.cc", ] @@ -8509,6 +8518,7 @@ "../browser/ui/views/location_bar/icon_label_bubble_view_unittest.cc", "../browser/ui/views/location_bar/location_icon_view_unittest.cc", "../browser/ui/views/media_router/cast_dialog_access_code_cast_button_unittest.cc", + "../browser/ui/views/media_router/cast_dialog_coordinator_unittest.cc", "../browser/ui/views/media_router/cast_dialog_metrics_unittest.cc", "../browser/ui/views/media_router/cast_dialog_no_sinks_view_unittest.cc", "../browser/ui/views/media_router/cast_dialog_sink_button_unittest.cc", @@ -8658,13 +8668,6 @@ if (is_win || is_mac || is_linux || is_chromeos_lacros) { sources += [ - "../browser/browser_switcher/alternative_browser_driver_unittest.cc", - "../browser/browser_switcher/browser_switcher_navigation_throttle_unittest.cc", - "../browser/browser_switcher/browser_switcher_prefs_unittest.cc", - "../browser/browser_switcher/browser_switcher_sitelist_unittest.cc", - "../browser/browser_switcher/ieem_sitelist_parser_unittest.cc", - "../browser/browser_switcher/mock_alternative_browser_driver.cc", - "../browser/browser_switcher/mock_alternative_browser_driver.h", "../browser/ui/profile_picker_unittest.cc", "../browser/ui/webui/signin/enterprise_profile_welcome_handler_unittest.cc", "../browser/ui/webui/signin/turn_sync_on_helper_unittest.cc",
diff --git a/chrome/test/data/updater/puffin_patch_test/README.md b/chrome/test/data/updater/puffin_patch_test/README.md index ede3990a..ce5d3b6a 100644 --- a/chrome/test/data/updater/puffin_patch_test/README.md +++ b/chrome/test/data/updater/puffin_patch_test/README.md
@@ -12,6 +12,7 @@ *Be careful not to submit this change in the final cl!* **Linux commands** + autoninja -C out/Default puffin puffin_app_v1_crx puffin_app_v2_crx rm chrome/test/data/updater/puffin_patch_test/linux_v1_to_v2.puff rm chrome/test/data/updater/puffin_patch_test/linux_v2_to_v1.puff @@ -19,6 +20,7 @@ out/Default/puffin -puffdiff out/Default/puffin_app_v2.crx3 out/Default/puffin_app_v1.crx3 chrome/test/data/updater/puffin_patch_test/linux_v2_to_v1.puff **Mac commands** + autoninja -C out/Default puffin puffin_app_v1_crx puffin_app_v2_crx rm chrome/test/data/updater/puffin_patch_test/mac_v1_to_v2.puff rm chrome/test/data/updater/puffin_patch_test/mac_v2_to_v1.puff @@ -26,6 +28,7 @@ out/Default/puffin -puffdiff out/Default/puffin_app_v2.crx3 out/Default/puffin_app_v1.crx3 chrome/test/data/updater/puffin_patch_test/mac_v2_to_v1.puff **Windows commands** + autoninja -C out\Default puffin puffin_app_v1_crx puffin_app_v2_crx del /f chrome\test\data\updater\puffin_patch_test\win_v1_to_v2.puff del /f chrome\test\data\updater\puffin_patch_test\win_v2_to_v1.puff
diff --git a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js index a5ebd796..d055d03b 100644 --- a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js +++ b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_extension_test.js
@@ -17,6 +17,15 @@ return element.classList.contains(ACTIVE_CATEGORY_BUTTON); } +function categoryGroupSelector(category) { + return `emoji-group[category="${category}"]:not(.history)`; +} + +function historyGroupSelector(category) { + return `[data-group="${category}-history"] > ` + + `emoji-group[category="${category}"]`; +} + suite('emoji-picker-extension', () => { /** @type {!EmojiPicker} */ let emojiPicker; @@ -24,12 +33,8 @@ let findInEmojiPicker; /** @type {function(...!string): ?HTMLElement} */ let findEmojiFirstButton; - /** @type {string} */ - const emoticonGroupSelector = - 'emoji-group[category="emoticon"]:not(.history)'; - /** @type {string} */ - const emoticonHistoryGroupSelector = - '[data-group="emoticon-history"] > emoji-group[category="emoticon"]'; + /** @type {Array<string>} */ + const categoryList = ['emoji', 'symbol', 'emoticon']; setup(() => { // Reset DOM state. @@ -73,31 +78,173 @@ }); }); - test('emoji category button should be active by default.', () => { - const emojiCategoryButton = findInEmojiPicker( - 'emoji-search', 'emoji-category-button', 'cr-icon-button'); - assertTrue(isCategoryButtonActive(emojiCategoryButton)); - }); + categoryList.forEach((category, categoryIndex) => { + test(category + ' category button is initialized correctly', + () => { + const categoryButton = + findInEmojiPicker('emoji-search').shadowRoot + .querySelectorAll('emoji-category-button')[categoryIndex] + .shadowRoot.querySelector('cr-icon-button'); + if (categoryIndex === 0) { + assertTrue( + isCategoryButtonActive(categoryButton), + 'First button must be active.'); + } else { + assertFalse( + isCategoryButtonActive(categoryButton), + 'All buttons must be inactive except the first one.'); + } + }); - test('emoticon category button should be inactive by default.', () => { - const emoticonCategoryButton = findInEmojiPicker( - 'emoji-search', 'emoji-category-button:last-of-type', 'cr-icon-button'); - assertFalse(isCategoryButtonActive(emoticonCategoryButton)); - }); - - test( - 'emoticon category button should be active after clicking at it.', () => { - const emojiCategoryButton = findInEmojiPicker( - 'emoji-search', 'emoji-category-button', 'cr-icon-button'); - const emoticonCategoryButton = findInEmojiPicker( - 'emoji-search', 'emoji-category-button:last-of-type', - 'cr-icon-button'); - emoticonCategoryButton.click(); + test(category + ' category button should be active after clicking at it.', + () => { + const allCategoryButtons = + Array.from(findInEmojiPicker('emoji-search').shadowRoot + .querySelectorAll('emoji-category-button').values()) + .map(item => item.shadowRoot.querySelector('cr-icon-button')); + const categoryButton = allCategoryButtons[categoryIndex]; + categoryButton.click(); flush(); - assertTrue(isCategoryButtonActive(emoticonCategoryButton)); - assertFalse(isCategoryButtonActive(emojiCategoryButton)); + assertTrue(isCategoryButtonActive(categoryButton)); + allCategoryButtons.forEach((categoryButtonItem, index) => { + if (index !== categoryIndex) { + assertFalse(isCategoryButtonActive(categoryButtonItem)); + } + }); }); + test('category group elements should be rendered.', + () => { + const numGroups = emojiPicker.categoriesData.filter( + item => item.category === category).length; + const numRenderedGroups = emojiPicker.shadowRoot + .querySelectorAll(categoryGroupSelector(category)).length; + assertGT(numGroups, 0); + assertEquals(numGroups, numRenderedGroups); + }); + + test(`each ${category} group should have the correct heading and correct` + + `number of ${category} entries.`, + () => { + const allGroups = emojiPicker.shadowRoot + .querySelectorAll(categoryGroupSelector(category)); + + const data = emojiPicker.categoriesData.filter( + item => item.category === category); + const groupElements = + emojiPicker.categoriesGroupElements.filter( + item => item.category === category); + + // The first group element is 'Recently used'. + assertEquals(groupElements[0].name, 'Recently used'); + + // Emoticon group elements are created for all data + history. + assertEquals(groupElements.length, data.length + 1); + + for (let idx = 0; idx < allGroups.length; ++idx) { + const group = allGroups[idx]; + const actualFirstGroupName = (/** @type {string} */ ( + group.shadowRoot.querySelector('#heading-left') + .innerHTML.trim())).replace('&', '&'); + const expectedFirstGroupName = groupElements[idx+1].name; + assertEquals(expectedFirstGroupName, actualFirstGroupName); + assertEquals(groupElements[idx+1].emoji.length, + group.shadowRoot.querySelectorAll('.emoji-button').length); + } + }); + + test(`clicking at a ${category} button should trigger the clicking event` + + `correct ${category} string and name.`, + async () => { + const firstButton = await waitForCondition( + () => findEmojiFirstButton(categoryGroupSelector(category))); + const groupElements = + emojiPicker.categoriesGroupElements.filter( + item => item.category === category && !item.isHistory); + const expectedString = groupElements[0].emoji[0].base.string; + const expectedName = groupElements[0].emoji[0].base.name; + const buttonClickPromise = new Promise( + (resolve) => + emojiPicker.addEventListener(EMOJI_BUTTON_CLICK, (event) => { + assertEquals(expectedString, event.detail.text); + assertEquals(expectedName, event.detail.name); + resolve(); + })); + firstButton.click(); + await flush(); + await waitWithTimeout( + buttonClickPromise, 1000, + `Failed to receive ${category} button click event`); + }); + + test(`recently used ${category} group should be hidden when empty.`, + () => { + assertEquals(findInEmojiPicker(historyGroupSelector( + category)).style.display, ''); + }); + + test(`history tab button must be disabled when the ${category} history` + + ' is empty.', + () => { + // It is assumed that the order of categoryList is the same as buttons. + const categoryButton = + findInEmojiPicker('emoji-search').shadowRoot + .querySelectorAll('emoji-category-button')[categoryIndex] + .shadowRoot.querySelector('cr-icon-button'); + categoryButton.click(); + flush(); + const historyTab = findInEmojiPicker( + `#tabs emoji-group-button[data-group="${category}-history"]`, + 'cr-icon-button'); + assertTrue(historyTab.disabled); + }); + + test(`clicking at recently used ${category} buttons should trigger ` + + `${category} insertion.`, + async () => { + emojiPicker.updateIncognitoState(false); + + const emojiButton = findEmojiFirstButton( + categoryGroupSelector(category)); + emojiButton.click(); + + const recentlyUsedButton = await waitForCondition( + () => findEmojiFirstButton(historyGroupSelector(category))); + const buttonClickPromise = new Promise( + (resolve) => + emojiPicker.addEventListener(EMOJI_BUTTON_CLICK, (event) => { + assertEquals( + emojiButton.innerHTML.trim(), event.detail.text); + resolve(); + })); + + recentlyUsedButton.click(); + await waitWithTimeout( + buttonClickPromise, 1000, + `Clicking at recently used ${category} buttons does not ` + + `trigger ${category} insertion.`); + }); + + test(`recently used ${category} group should contain the ` + + `correct ${category} after it is clicked.`, + async () => { + emojiPicker.updateIncognitoState(false); + + const emojiButton = findEmojiFirstButton( + categoryGroupSelector(category)); + emojiButton.click(); + + const recentEmojiButton = await waitForCondition( + () => findEmojiFirstButton(historyGroupSelector(category))); + assert(recentEmojiButton); + + const recentlyUsedEmoji = + findInEmojiPicker(historyGroupSelector(category)) + .shadowRoot.querySelectorAll('.emoji-button'); + assertEquals(1, recentlyUsedEmoji.length); + }); + }); + test( `the first tab of the next pagination should be active when clicking at either chevron.`, @@ -125,140 +272,6 @@ isGroupButtonActive(firstEmoticonTabInFirstPage)); }); - test('all emoticon groups should be rendered.', () => { - const numEmoticons = emojiPicker.categoriesData.filter( - item => item.category === 'emoticon').length; - assertGT(numEmoticons, 0); - assertEquals( - numEmoticons, - emojiPicker.shadowRoot.querySelectorAll( - emoticonGroupSelector).length); - }); - - test( - 'each emoticon group should have the correct heading and correct' + - 'number of emoticon entries.', - async () => { - const allEmoticonGroups = - emojiPicker.shadowRoot.querySelectorAll(emoticonGroupSelector); - - const emoticonData = emojiPicker.categoriesData.filter( - item => item.category === 'emoticon'); - const emoticonGroupElements = - emojiPicker.categoriesGroupElements.filter( - item => item.category === 'emoticon'); - - // The first group element is 'Recently used'. - assertEquals(emoticonGroupElements[0].name, 'Recently used'); - - // Emoticon group elements are created for all data + history. - assertEquals(emoticonGroupElements.length, emoticonData.length + 1); - - for (let idx = 0; idx < allEmoticonGroups.length; ++idx) { - const group = allEmoticonGroups[idx]; - const actualFirstGroupName = - group.shadowRoot.querySelector('#heading-left').innerHTML.trim(); - const expectedFirstGroupName = emoticonGroupElements[idx+1].name; - assertEquals(expectedFirstGroupName, actualFirstGroupName); - - const expectedNumberOfEmoticons = - emoticonGroupElements[idx+1].emoji.length; - await waitForCondition( - () => expectedNumberOfEmoticons === - group.shadowRoot.querySelectorAll('.emoji-button').length); - } - }); - - test( - 'clicking at an emoticon button should trigger the clicking event with ' + - 'correct emoticon string and name.', - async () => { - const firstEmoticonButton = await waitForCondition( - () => findEmojiFirstButton(emoticonGroupSelector)); - const emoticonGroupElements = - emojiPicker.categoriesGroupElements.filter( - item => item.category === 'emoticon' && !item.isHistory); - const expectedEmoticonString = - emoticonGroupElements[0].emoji[0].base.string; - const expectedEmoticonName = - emoticonGroupElements[0].emoji[0].base.name; - const buttonClickPromise = new Promise( - (resolve) => - emojiPicker.addEventListener(EMOJI_BUTTON_CLICK, (event) => { - assertEquals(expectedEmoticonString, event.detail.text); - assertEquals(expectedEmoticonName, event.detail.name); - resolve(); - })); - firstEmoticonButton.click(); - await flush(); - await waitWithTimeout( - buttonClickPromise, 1000, - 'Failed to receive emoticon button click event'); - }); - - test('there should be no recently used emoticon group when empty.', () => { - assert(!findInEmojiPicker('[data-group=emoticon-history] emoticon-group')); - }); - - test( - 'history tab button must be disabled when the emoticon history is empty.', - () => { - const emoticonCategoryButton = findInEmojiPicker( - 'emoji-search', 'emoji-category-button:last-of-type', - 'cr-icon-button'); - emoticonCategoryButton.click(); - flush(); - const emoticonHistoryTab = findInEmojiPicker( - '.pagination [data-group=emoticon-history]', 'cr-icon-button'); - assertTrue(emoticonHistoryTab.disabled); - }); - - test( - 'clicking at recently used emoticon buttons should trigger emoticon ' + - 'insertion.', - async () => { - emojiPicker.updateIncognitoState(false); - - const emoticonButton = findEmojiFirstButton(emoticonGroupSelector); - emoticonButton.click(); - - const recentlyUsedEmoticonButton = await waitForCondition( - () => findEmojiFirstButton(emoticonHistoryGroupSelector)); - const buttonClickPromise = new Promise( - (resolve) => - emojiPicker.addEventListener(EMOJI_BUTTON_CLICK, (event) => { - assertEquals( - emoticonButton.innerHTML.trim(), event.detail.text); - resolve(); - })); - - recentlyUsedEmoticonButton.click(); - await waitWithTimeout( - buttonClickPromise, 1000, - 'Clicking at recently used emoticon buttons does not trigger ' + - 'emoticon insertion.'); - }); - - test( - 'recently used emoticon group should contain the correct emoticon ' + - 'after it is clicked.', - async () => { - emojiPicker.updateIncognitoState(false); - const emoticonButton = findEmojiFirstButton(emoticonGroupSelector); - emoticonButton.click(); - - const recentEmoticonButton = await waitForCondition( - () => findEmojiFirstButton(emoticonHistoryGroupSelector)); - assert(recentEmoticonButton); - - const recentlyUsedEmoticons = - findInEmojiPicker( - emoticonHistoryGroupSelector, - ) - .shadowRoot.querySelectorAll('.emoji-button'); - assertEquals(1, recentlyUsedEmoticons.length); - }); - test( 'Scrolling to an emoticon group should activate the emoticon category ' + 'button.', @@ -276,6 +289,7 @@ () => isCategoryButtonActive(emoticonCategoryButton) && !isCategoryButtonActive(emojiCategoryButton)); }); + test( 'Scrolling to an emoticon group should activate the corresponding ' + 'subcategory tab.',
diff --git a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_search_test.js b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_search_test.js index 528542e..74284ae 100644 --- a/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_search_test.js +++ b/chrome/test/data/webui/chromeos/emoji_picker/emoji_picker_search_test.js
@@ -67,8 +67,9 @@ () => { emojiSearch.search = 'face'; flush(); - const emojiResults = findInEmojiPicker('emoji-search', 'emoji-group') - .shadowRoot.querySelectorAll('.emoji-button'); + const emojiResults = + findInEmojiPicker('emoji-search', 'emoji-group[category="emoji"]') + .shadowRoot.querySelectorAll('.emoji-button'); assertGT(emojiResults.length, 0); const emoticonResults = findInEmojiPicker(
diff --git a/chrome/test/data/webui/chromeos/shimless_rma/reimaging_firmware_update_page_test.js b/chrome/test/data/webui/chromeos/shimless_rma/reimaging_firmware_update_page_test.js index 74f62ab..fa468d9 100644 --- a/chrome/test/data/webui/chromeos/shimless_rma/reimaging_firmware_update_page_test.js +++ b/chrome/test/data/webui/chromeos/shimless_rma/reimaging_firmware_update_page_test.js
@@ -87,6 +87,12 @@ test('RoFirmwareUpdateEnablesNext', async () => { const resolver = new PromiseResolver(); await initializeReimagingFirmwareUpdatePage(); + + const firmwareTitle = component.shadowRoot.querySelector('#titleText'); + assertEquals( + loadTimeData.getString('firmwareUpdateInstallImageTitleText'), + firmwareTitle.textContent.trim()); + service.triggerUpdateRoFirmwareObserver( UpdateRoFirmwareStatus.kComplete, 0); await flushTasks(); @@ -94,6 +100,11 @@ return resolver.promise; }; + // Confirm the page title changes after firmware install completes. + assertEquals( + loadTimeData.getString('firmwareUpdateInstallCompleteTitleText'), + firmwareTitle.textContent.trim()); + const expectedResult = {foo: 'bar'}; let savedResult; component.onNextButtonClick().then((result) => savedResult = result);
diff --git a/chrome/test/data/webui/chromeos/shimless_rma/wrapup_repair_complete_page_test.js b/chrome/test/data/webui/chromeos/shimless_rma/wrapup_repair_complete_page_test.js index e38e288c..92926a5 100644 --- a/chrome/test/data/webui/chromeos/shimless_rma/wrapup_repair_complete_page_test.js +++ b/chrome/test/data/webui/chromeos/shimless_rma/wrapup_repair_complete_page_test.js
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js'; import {FakeShimlessRmaService} from 'chrome://shimless-rma/fake_shimless_rma_service.js'; import {setShimlessRmaServiceForTesting} from 'chrome://shimless-rma/mojo_interface_provider.js'; @@ -350,7 +351,8 @@ // Attempt to save the logs. await clickButton('#saveLogDialogButton'); - resolver.resolve({savePath: 'save/path', error: RmadErrorCode.kOk}); + const savePath = 'save/path'; + resolver.resolve({savePath: {path: savePath}, error: RmadErrorCode.kOk}); await flushTasks(); assertEquals(1, callCount); @@ -360,6 +362,10 @@ isVisible(component.shadowRoot.querySelector('#saveLogDialogButton'))); assertTrue(isVisible( component.shadowRoot.querySelector('#logSaveDoneDialogButton'))); + assertEquals( + loadTimeData.getStringF('rmaLogsSaveSuccessText', savePath), + component.shadowRoot.querySelector('#logSavedStatusText') + .textContent.trim()); // Close the logs dialog. await clickButton('#logSaveDoneDialogButton'); @@ -373,6 +379,40 @@ isVisible(component.shadowRoot.querySelector('#saveLogDialogButton'))); }); + test('SaveLogFails', async () => { + const resolver = new PromiseResolver(); + await initializeRepairCompletePage(); + + let callCount = 0; + service.saveLog = () => { + callCount++; + return resolver.promise; + }; + + // Open the logs dialog. + await clickButton('#rmaLogButton'); + assertTrue( + isVisible(component.shadowRoot.querySelector('#saveLogDialogButton'))); + + // Attempt to save the logs but it fails. + await clickButton('#saveLogDialogButton'); + resolver.resolve( + {savePath: 'save/path', error: RmadErrorCode.kCannotSaveLog}); + await flushTasks(); + + assertEquals(1, callCount); + + // The save log button should be replaced by the done button. + assertFalse( + isVisible(component.shadowRoot.querySelector('#saveLogDialogButton'))); + assertTrue(isVisible( + component.shadowRoot.querySelector('#logSaveDoneDialogButton'))); + assertEquals( + loadTimeData.getString('rmaLogsSaveFailText'), + component.shadowRoot.querySelector('#logSavedStatusText') + .textContent.trim()); + }); + test('BatteryCutButtonDisabledByDefault', async () => { await initializeRepairCompletePage(); const button = component.shadowRoot.querySelector('#batteryCutButton');
diff --git a/chrome/test/data/webui/js/cr/ui/BUILD.gn b/chrome/test/data/webui/js/cr/ui/BUILD.gn index be600a7..6680ec52 100644 --- a/chrome/test/data/webui/js/cr/ui/BUILD.gn +++ b/chrome/test/data/webui/js/cr/ui/BUILD.gn
@@ -24,7 +24,7 @@ deps = [ "../../..:chai_assert", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } @@ -32,8 +32,8 @@ deps = [ "../../..:chai_assert", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:context_menu_handler", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -82,8 +82,8 @@ deps = [ "../../..:chai_assert", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_button.m", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_button", ] } @@ -91,16 +91,16 @@ deps = [ "../../..:chai_assert", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:command", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_item", ] } js_library("position_util_test") { deps = [ "../../..:chai_assert", - "//ui/webui/resources/js/cr/ui:position_util.m", + "//ui/webui/resources/js/cr/ui:position_util", ] }
diff --git a/chrome/test/data/webui/js/cr/ui/command_test.js b/chrome/test/data/webui/js/cr/ui/command_test.js index 186480d..ad28f2b 100644 --- a/chrome/test/data/webui/js/cr/ui/command_test.js +++ b/chrome/test/data/webui/js/cr/ui/command_test.js
@@ -4,7 +4,7 @@ // clang-format off import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {assertEquals, assertFalse, assertTrue} from '../../../chai_assert.js';
diff --git a/chrome/test/data/webui/js/cr/ui/context_menu_handler_test.js b/chrome/test/data/webui/js/cr/ui/context_menu_handler_test.js index 8c1bb44..99d62ea 100644 --- a/chrome/test/data/webui/js/cr/ui/context_menu_handler_test.js +++ b/chrome/test/data/webui/js/cr/ui/context_menu_handler_test.js
@@ -4,8 +4,8 @@ // clang-format off import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {assertEquals} from '../../../chai_assert.js';
diff --git a/chrome/test/data/webui/js/cr/ui/menu_button_test.js b/chrome/test/data/webui/js/cr/ui/menu_button_test.js index a19ff60..69c968a 100644 --- a/chrome/test/data/webui/js/cr/ui/menu_button_test.js +++ b/chrome/test/data/webui/js/cr/ui/menu_button_test.js
@@ -4,8 +4,8 @@ // clang-format off import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuButton} from 'chrome://resources/js/cr/ui/menu_button.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuButton} from 'chrome://resources/js/cr/ui/menu_button.js'; import {assertEquals, assertFalse, assertTrue} from '../../../chai_assert.js';
diff --git a/chrome/test/data/webui/js/cr/ui/menu_test.js b/chrome/test/data/webui/js/cr/ui/menu_test.js index 145b481..589ee08 100644 --- a/chrome/test/data/webui/js/cr/ui/menu_test.js +++ b/chrome/test/data/webui/js/cr/ui/menu_test.js
@@ -4,9 +4,9 @@ // clang-format off import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {assertEquals, assertFalse, assertTrue} from '../../../chai_assert.js'; // clang-format on
diff --git a/chrome/test/data/webui/js/cr/ui/position_util_test.js b/chrome/test/data/webui/js/cr/ui/position_util_test.js index 9dce1884..6667b78 100644 --- a/chrome/test/data/webui/js/cr/ui/position_util_test.js +++ b/chrome/test/data/webui/js/cr/ui/position_util_test.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. // clang-format off -import {AnchorType, positionPopupAroundElement, positionPopupAtPoint} from 'chrome://resources/js/cr/ui/position_util.m.js'; +import {AnchorType, positionPopupAroundElement, positionPopupAtPoint} from 'chrome://resources/js/cr/ui/position_util.js'; import {assertEquals} from '../../../chai_assert.js'; // clang-format on
diff --git a/chrome/test/media_router/media_router_cast_ui_for_test.cc b/chrome/test/media_router/media_router_cast_ui_for_test.cc index 139f45a9..b653f14 100644 --- a/chrome/test/media_router/media_router_cast_ui_for_test.cc +++ b/chrome/test/media_router/media_router_cast_ui_for_test.cc
@@ -8,6 +8,7 @@ #include "base/run_loop.h" #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/browser/ui/media_router/media_router_ui.h" +#include "chrome/browser/ui/views/media_router/cast_dialog_coordinator.h" #include "chrome/browser/ui/views/media_router/cast_dialog_sink_button.h" #include "chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h" #include "ui/events/base_event_utils.h" @@ -62,7 +63,7 @@ void MediaRouterCastUiForTest::ChooseSourceType( CastDialogView::SourceType source_type) { - CastDialogView* dialog_view = CastDialogView::GetInstance(); + CastDialogView* dialog_view = GetDialogView(); CHECK(dialog_view); views::test::ButtonTestApi(dialog_view->sources_button_for_test()) @@ -81,7 +82,7 @@ CastDialogView::SourceType MediaRouterCastUiForTest::GetChosenSourceType() const { - CastDialogView* dialog_view = CastDialogView::GetInstance(); + const CastDialogView* dialog_view = GetDialogView(); CHECK(dialog_view); return dialog_view->selected_source_; } @@ -121,7 +122,7 @@ void MediaRouterCastUiForTest::OnDialogCreated() { MediaRouterUiForTestBase::OnDialogCreated(); - CastDialogView::GetInstance()->KeepShownForTesting(); + GetDialogView()->KeepShownForTesting(); } MediaRouterCastUiForTest::MediaRouterCastUiForTest( @@ -182,7 +183,7 @@ CastDialogSinkButton* MediaRouterCastUiForTest::GetSinkButton( const std::string& sink_name) const { - CastDialogView* dialog_view = CastDialogView::GetInstance(); + const CastDialogView* dialog_view = GetDialogView(); CHECK(dialog_view); const std::vector<CastDialogSinkButton*>& sink_buttons = dialog_view->sink_buttons_for_test(); @@ -200,7 +201,7 @@ watch_callback_ = run_loop.QuitClosure(); watch_type_ = watch_type; - CastDialogView* dialog_view = CastDialogView::GetInstance(); + CastDialogView* dialog_view = GetDialogView(); CHECK(dialog_view); dialog_view->AddObserver(this); // Check if the current dialog state already meets the condition that we are @@ -210,6 +211,16 @@ run_loop.Run(); } +const CastDialogView* MediaRouterCastUiForTest::GetDialogView() const { + return dialog_controller_->GetCastDialogCoordinatorForTesting() + .GetCastDialogView(); +} + +CastDialogView* MediaRouterCastUiForTest::GetDialogView() { + return dialog_controller_->GetCastDialogCoordinatorForTesting() + .GetCastDialogView(); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(MediaRouterCastUiForTest); } // namespace media_router
diff --git a/chrome/test/media_router/media_router_cast_ui_for_test.h b/chrome/test/media_router/media_router_cast_ui_for_test.h index 1b022b7..0fb1e53 100644 --- a/chrome/test/media_router/media_router_cast_ui_for_test.h +++ b/chrome/test/media_router/media_router_cast_ui_for_test.h
@@ -64,6 +64,9 @@ WatchType watch_type, absl::optional<std::string> sink_name = absl::nullopt) override; + const CastDialogView* GetDialogView() const; + CastDialogView* GetDialogView(); + WEB_CONTENTS_USER_DATA_KEY_DECL(); };
diff --git a/chrome/updater/app/server/win/com_classes_legacy.cc b/chrome/updater/app/server/win/com_classes_legacy.cc index 5eff06e..cd9e45f 100644 --- a/chrome/updater/app/server/win/com_classes_legacy.cc +++ b/chrome/updater/app/server/win/com_classes_legacy.cc
@@ -927,25 +927,37 @@ return PolicyStatusValueImpl::Create(policy_status, value); } -// TODO(crbug.com/1293203): Implement this method. STDMETHODIMP PolicyStatusImpl::get_proxyMode(IPolicyStatusValue** value) { DCHECK(value); - return E_NOTIMPL; + PolicyStatus<std::string> policy_status; + if (!policy_service_->GetProxyMode(&policy_status, nullptr)) { + return E_FAIL; + } + + return PolicyStatusValueImpl::Create(policy_status, value); } -// TODO(crbug.com/1293203): Implement this method. STDMETHODIMP PolicyStatusImpl::get_proxyPacUrl(IPolicyStatusValue** value) { DCHECK(value); - return E_NOTIMPL; + PolicyStatus<std::string> policy_status; + if (!policy_service_->GetProxyPacUrl(&policy_status, nullptr)) { + return E_FAIL; + } + + return PolicyStatusValueImpl::Create(policy_status, value); } -// TODO(crbug.com/1293203): Implement this method. STDMETHODIMP PolicyStatusImpl::get_proxyServer(IPolicyStatusValue** value) { DCHECK(value); - return E_NOTIMPL; + PolicyStatus<std::string> policy_status; + if (!policy_service_->GetProxyServer(&policy_status, nullptr)) { + return E_FAIL; + } + + return PolicyStatusValueImpl::Create(policy_status, value); } STDMETHODIMP PolicyStatusImpl::get_effectivePolicyForAppInstalls(
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 161783f..ae76520 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
@@ -274,7 +274,7 @@ public void testStopDoesNotCauseFinish() { mActivityLifecycle.create().start().resume(); mActivityLifecycle.pause().stop(); - Assert.assertFalse(mShadowActivity.isFinishing()); + Assert.assertFalse(mActivity.isFinishing()); } @Test @@ -292,7 +292,7 @@ public void testBackButtonDoesNotCauseFinish() { mActivityLifecycle.create().start().resume(); mActivity.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); - Assert.assertFalse(mShadowActivity.isFinishing()); + Assert.assertFalse(mActivity.isFinishing()); } @Test @@ -375,7 +375,7 @@ verifyBroadcastedIntent( filterFor(CastWebContentsIntentUtils.ACTION_ACTIVITY_STOPPED), () -> { mActivityLifecycle.pause().stop(); - assertFalse(mShadowActivity.isFinishing()); + assertFalse(mActivity.isFinishing()); }, false); } @@ -390,7 +390,7 @@ verifyBroadcastedIntent( filterFor(CastWebContentsIntentUtils.ACTION_ACTIVITY_STOPPED), () -> { mActivityLifecycle.pause().stop(); - assertTrue(mShadowActivity.isFinishing()); + assertTrue(mActivity.isFinishing()); }, true); } @@ -417,7 +417,7 @@ verifyBroadcastedIntent( filterFor(CastWebContentsIntentUtils.ACTION_ACTIVITY_STOPPED), () -> { mActivityLifecycle.pause().stop(); - assertFalse(mShadowActivity.isFinishing()); + assertFalse(mActivity.isFinishing()); }, false); } @@ -428,7 +428,7 @@ verifyBroadcastedIntent( filterFor(CastWebContentsIntentUtils.ACTION_ACTIVITY_STOPPED), () -> { mActivityLifecycle.pause().stop(); - assertTrue(mShadowActivity.isFinishing()); + assertTrue(mActivity.isFinishing()); }, true); } @@ -439,7 +439,7 @@ verifyBroadcastedIntent( filterFor(CastWebContentsIntentUtils.ACTION_ACTIVITY_STOPPED), () -> { mActivityLifecycle.pause().stop(); - assertTrue(mShadowActivity.isFinishing()); + assertTrue(mActivity.isFinishing()); }, true); }
diff --git a/chromeos/ash/components/dbus/arc/arc_data_snapshotd_client.h b/chromeos/ash/components/dbus/arc/arc_data_snapshotd_client.h index 724dff9..3a41a12 100644 --- a/chromeos/ash/components/dbus/arc/arc_data_snapshotd_client.h +++ b/chromeos/ash/components/dbus/arc/arc_data_snapshotd_client.h
@@ -38,7 +38,7 @@ using LoadSnapshotMethodCallback = base::OnceCallback<void(bool, bool)>; // Factory function, creates a new instance and returns ownership. - // For normal usage, access the singleton via DBusThreadManager::Get(). + // For normal usage, access the singleton via Get(). static std::unique_ptr<ArcDataSnapshotdClient> Create(); // Generate key pair for an upcoming session.
diff --git a/chromeos/ash/components/dbus/seneschal/seneschal_client.h b/chromeos/ash/components/dbus/seneschal/seneschal_client.h index 5b9bb07..56099fb4 100644 --- a/chromeos/ash/components/dbus/seneschal/seneschal_client.h +++ b/chromeos/ash/components/dbus/seneschal/seneschal_client.h
@@ -38,7 +38,7 @@ ~SeneschalClient() override; // Factory function, creates a new instance and returns ownership. - // For normal usage, access the singleton via DBusThreadManager::Get(). + // For normal usage, access the singleton via Get(). static std::unique_ptr<SeneschalClient> Create(); // Registers |callback| to run when the Concierge service becomes available.
diff --git a/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.cc b/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.cc index 7391a89..447c094 100644 --- a/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.cc +++ b/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.cc
@@ -121,6 +121,9 @@ : absl::nullopt); } +void FakeUpdateEngineClient::ApplyDeferredUpdate( + base::OnceClosure failure_callback) {} + void FakeUpdateEngineClient::set_default_status( const update_engine::StatusResult& status) { default_status_ = status;
diff --git a/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.h b/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.h index e6c7832..fc9e378 100644 --- a/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.h +++ b/chromeos/ash/components/dbus/update_engine/fake_update_engine_client.h
@@ -57,6 +57,7 @@ void ToggleFeature(const std::string& feature, bool enable) override; void IsFeatureEnabled(const std::string& feature, IsFeatureEnabledCallback callback) override; + void ApplyDeferredUpdate(base::OnceClosure failure_callback) override; // Pushes update_engine::StatusResult in the queue to test changing status. // GetLastStatus() returns the status set by this method in FIFO order. // See set_default_status().
diff --git a/chromeos/ash/components/dbus/update_engine/update_engine_client.cc b/chromeos/ash/components/dbus/update_engine/update_engine_client.cc index 7be0b57ec..aced4560 100644 --- a/chromeos/ash/components/dbus/update_engine/update_engine_client.cc +++ b/chromeos/ash/components/dbus/update_engine/update_engine_client.cc
@@ -264,6 +264,22 @@ std::move(callback))); } + void ApplyDeferredUpdate(base::OnceClosure failure_callback) override { + dbus::MethodCall method_call(update_engine::kUpdateEngineInterface, + update_engine::kApplyDeferredUpdate); + dbus::MessageWriter writer(&method_call); + + VLOG(1) << "Requesting UpdateEngine to apply deferred update."; + + // TODO(yuanpengni): Add an option to shutdown after applied deferred + // update. + update_engine_proxy_->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::BindOnce(&UpdateEngineClientImpl::OnApplyDeferredUpdate, + weak_ptr_factory_.GetWeakPtr(), + std::move(failure_callback))); + } + void Init(dbus::Bus* bus) override { update_engine_proxy_ = bus->GetObjectProxy( update_engine::kUpdateEngineServiceName, @@ -532,6 +548,18 @@ std::move(callback).Run(success); } + // Called when a response for `ApplyDeferredUpdate()` is received. + void OnApplyDeferredUpdate(base::OnceClosure failure_callback, + dbus::Response* response) { + if (!response) { + LOG(ERROR) << update_engine::kApplyDeferredUpdate << " call failed."; + std::move(failure_callback).Run(); + return; + } + + VLOG(1) << "Update is applied."; + } + // Called when a status update signal is received. void StatusUpdateReceived(dbus::Signal* signal) { VLOG(1) << "Status update signal received: " << signal->ToString(); @@ -679,6 +707,10 @@ std::move(callback).Run(absl::nullopt); } + void ApplyDeferredUpdate(base::OnceClosure failure_callback) override { + VLOG(1) << "Applying deferred update."; + } + private: void StateTransition(bool apply_update) { update_engine::Operation next_operation = update_engine::Operation::ERROR;
diff --git a/chromeos/ash/components/dbus/update_engine/update_engine_client.h b/chromeos/ash/components/dbus/update_engine/update_engine_client.h index 9516a62..d7376059 100644 --- a/chromeos/ash/components/dbus/update_engine/update_engine_client.h +++ b/chromeos/ash/components/dbus/update_engine/update_engine_client.h
@@ -189,6 +189,9 @@ virtual void IsFeatureEnabled(const std::string& feature, IsFeatureEnabledCallback callback) = 0; + // Apply a downloaded but deferred update. Runs callback on failure. + virtual void ApplyDeferredUpdate(base::OnceClosure failure_callback) = 0; + protected: // Initialize() should be used instead. UpdateEngineClient();
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index 755e5f2..a24a6007 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -3016,6 +3016,9 @@ <message name="IDS_SHIMLESS_RMA_LOGS_SAVE_SUCCESS" desc="The text telling the user that saving the logs to a external USB was successful and showing them the saved file location."> Saved to "<ph name="FILE_LOCATION">$1<ex>/USB/Home/MyFiles</ex></ph>" </message> + <message name="IDS_SHIMLESS_RMA_LOGS_SAVE_FAIL" desc="The text telling the user that saving the logs to a external USB failed. The expectation would be for the user to try a different external storage device."> + File couldn't be saved. Try plugging in a different external storage, or try again later. + </message> <!-- Powerwash dialog --> <message name="IDS_SHIMLESS_RMA_POWERWASH_DIALOG_TITLE" desc="Title for the powerwash dialog displayed on the repair complete page and on the restock page"> Powerwash (factory reset) required @@ -3126,9 +3129,12 @@ DRAM part number </message> <!-- RO firmware reimaging page --> - <message name="IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_TITLE" desc="The title for the page when reimaging is in progress."> + <message name="IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_IMAGE_TITLE" desc="The title for the page when the device firmware is expected to be installed."> Install firmware image </message> + <message name="IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_COMPLETE_TITLE" desc="The title for the page when the device firmware installation is complete."> + Install complete + </message> <message name="IDS_SHIMLESS_RMA_FIRMWARE_WAIT_FOR_USB" desc="The prompt to insert a thumb drive with the recovery image for this device."> Insert external storage, such as a USB drive or an SD card, with the downloaded Chromebook Recovery Utility image </message>
diff --git a/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_COMPLETE_TITLE.png.sha1 b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_COMPLETE_TITLE.png.sha1 new file mode 100644 index 0000000..f46366b --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_COMPLETE_TITLE.png.sha1
@@ -0,0 +1 @@ +ae9c6e3faa11effc28a8d7473706f0ee1677c550 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_IMAGE_TITLE.png.sha1 b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_IMAGE_TITLE.png.sha1 new file mode 100644 index 0000000..d5d2dd697 --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_INSTALL_IMAGE_TITLE.png.sha1
@@ -0,0 +1 @@ +4e4c20ad5008a55e24d7039536bf4f8376eff0a9 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_TITLE.png.sha1 b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_TITLE.png.sha1 deleted file mode 100644 index 030ed992..0000000 --- a/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_FIRMWARE_UPDATE_TITLE.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -7b480e0ce5a6ada4df55eca10915bbe92c652d70 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_LOGS_SAVE_FAIL.png.sha1 b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_LOGS_SAVE_FAIL.png.sha1 new file mode 100644 index 0000000..e63d1c2 --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_SHIMLESS_RMA_LOGS_SAVE_FAIL.png.sha1
@@ -0,0 +1 @@ +ca11665bf89584caab63ebc05c605a081365f1f8 \ No newline at end of file
diff --git a/chromeos/tast_control.gni b/chromeos/tast_control.gni index fe74a2c..b064a39 100644 --- a/chromeos/tast_control.gni +++ b/chromeos/tast_control.gni
@@ -226,31 +226,9 @@ "health.DiagnosticsRun.dns_resolution", "health.DiagnosticsRun.dns_resolver_present", - # http://b234699971 - "crostini.AppGeditUnshareFolder", - # b/235279574 "wmp.DragAndDropWindow", - # http://b/236312054 - "crostini.AppGeditFilesharing", - "crostini.AppGeditFilesharing.stable", - "crostini.AppGeditFilesharing.clamshell_stable", - - # http://b/236710501 - "crostini.AppAndroidStudio.stable", - "crostini.AppGeditUnshareFolder.stable", - "crostini.AppGeditUnshareFolder.clamshell_stable", - - # http://crbug.com/1339132 - "crostini.AppEclipse", - "crostini.AppEmacs", - "crostini.AppVscode", - "crostini.BasicLxdNext.stable", - "crostini.RestartApp", - "crostini.RestartApp.stable", - "crostini.RestartApp.clamshell_stable", - # http://b/238600197 "crostini.FilesAppWatch.buster_stable", @@ -271,6 +249,9 @@ # https://crbug.com/1236234 "lacros.AudioPlay", + + # https://crbug.com/1346149 + "apps.Sharesheet", ] # To create filters to be used on specific builders add them like this:
diff --git a/chromeos/ui/frame/caption_buttons/frame_size_button.cc b/chromeos/ui/frame/caption_buttons/frame_size_button.cc index 8f9b900..0e6b28fc 100644 --- a/chromeos/ui/frame/caption_buttons/frame_size_button.cc +++ b/chromeos/ui/frame/caption_buttons/frame_size_button.cc
@@ -63,16 +63,13 @@ const bool is_primary_display_layout = chromeos::IsDisplayLayoutPrimary( display::Screen::GetScreen()->GetDisplayNearestWindow( to_hover->GetWidget()->GetNativeWindow())); - const bool is_primary_snap = - is_primary_display_layout || - !chromeos::wm::features::IsVerticalSnapEnabled(); switch (to_hover->GetIcon()) { case views::CAPTION_BUTTON_ICON_LEFT_TOP_SNAPPED: - return is_primary_snap ? SnapDirection::kPrimary - : SnapDirection::kSecondary; + return is_primary_display_layout ? SnapDirection::kPrimary + : SnapDirection::kSecondary; case views::CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED: - return is_primary_snap ? SnapDirection::kSecondary - : SnapDirection::kPrimary; + return is_primary_display_layout ? SnapDirection::kSecondary + : SnapDirection::kPrimary; case views::CAPTION_BUTTON_ICON_FLOAT: case views::CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE: case views::CAPTION_BUTTON_ICON_MINIMIZE:
diff --git a/chromeos/ui/frame/frame_header.cc b/chromeos/ui/frame/frame_header.cc index c0033206..eeb22f33 100644 --- a/chromeos/ui/frame/frame_header.cc +++ b/chromeos/ui/frame/frame_header.cc
@@ -474,16 +474,14 @@ const bool is_horizontal_display = chromeos::IsDisplayLayoutHorizontal( display::Screen::GetScreen()->GetDisplayNearestWindow( target_widget_->GetNativeWindow())); - const bool is_horizontal_snap = - is_horizontal_display || !chromeos::wm::features::IsVerticalSnapEnabled(); caption_button_container()->SetButtonImage( views::CAPTION_BUTTON_ICON_LEFT_TOP_SNAPPED, - is_horizontal_snap ? chromeos::kWindowControlLeftSnappedIcon - : chromeos::kWindowControlTopSnappedIcon); + is_horizontal_display ? chromeos::kWindowControlLeftSnappedIcon + : chromeos::kWindowControlTopSnappedIcon); caption_button_container()->SetButtonImage( views::CAPTION_BUTTON_ICON_RIGHT_BOTTOM_SNAPPED, - is_horizontal_snap ? chromeos::kWindowControlRightSnappedIcon - : chromeos::kWindowControlBottomSnappedIcon); + is_horizontal_display ? chromeos::kWindowControlRightSnappedIcon + : chromeos::kWindowControlBottomSnappedIcon); } } // namespace chromeos
diff --git a/chromeos/ui/wm/features.cc b/chromeos/ui/wm/features.cc index 570ea99..e8e01d4 100644 --- a/chromeos/ui/wm/features.cc +++ b/chromeos/ui/wm/features.cc
@@ -13,20 +13,10 @@ const base::Feature kFloatWindow{"CrOSLabsFloatWindow", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enables vertical snap for clamshell mode. This allows users to snap top and -// bottom when the screen is in portrait orientation, while snap left and right -// when the screen is in landscape orientation. -const base::Feature kVerticalSnap{"VerticalSnap", - base::FEATURE_ENABLED_BY_DEFAULT}; - bool IsFloatWindowEnabled() { return base::FeatureList::IsEnabled(kFloatWindow); } -bool IsVerticalSnapEnabled() { - return base::FeatureList::IsEnabled(kVerticalSnap); -} - } // namespace features } // namespace wm } // namespace chromeos
diff --git a/chromeos/ui/wm/features.h b/chromeos/ui/wm/features.h index 3ca4c37..0e0eca0 100644 --- a/chromeos/ui/wm/features.h +++ b/chromeos/ui/wm/features.h
@@ -14,12 +14,8 @@ COMPONENT_EXPORT(CHROMEOS_UI_WM) extern const base::Feature kFloatWindow; -// Enable Vertical Snap. -COMPONENT_EXPORT(CHROMEOS_UI_WM) -extern const base::Feature kVerticalSnap; COMPONENT_EXPORT(CHROMEOS_UI_WM) bool IsFloatWindowEnabled(); -COMPONENT_EXPORT(CHROMEOS_UI_WM) bool IsVerticalSnapEnabled(); } // namespace features } // namespace wm
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 6c1e879..2f2ed19 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -188,8 +188,6 @@ "form_parsing/field_candidates.h", "form_parsing/form_field.cc", "form_parsing/form_field.h", - "form_parsing/iban_field.cc", - "form_parsing/iban_field.h", "form_parsing/merchant_promo_code_field.cc", "form_parsing/merchant_promo_code_field.h", "form_parsing/name_field.cc", @@ -819,7 +817,6 @@ "form_parsing/credit_card_field_unittest.cc", "form_parsing/field_candidates_unittest.cc", "form_parsing/form_field_unittest.cc", - "form_parsing/iban_field_unittest.cc", "form_parsing/merchant_promo_code_field_unittest.cc", "form_parsing/name_field_unittest.cc", "form_parsing/parsing_test_utils.cc",
diff --git a/components/autofill/core/browser/autofill_regex_constants.cc b/components/autofill/core/browser/autofill_regex_constants.cc index 62db1f71..b09c8608 100644 --- a/components/autofill/core/browser/autofill_regex_constants.cc +++ b/components/autofill/core/browser/autofill_regex_constants.cc
@@ -576,7 +576,7 @@ u"yesbankltd" u")$"; -const char16_t kInternationalBankAccountNumberValueRe[] = +const char16_t kInternationalBankAccountNumberRe[] = u"^[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}$"; // Matches all 3 and 4 digit numbers. @@ -616,10 +616,4 @@ const char16_t kPhoneValueRe[] = u"^[0-9()+-]{6,25}$"; const char16_t kUsernameLikeValueRe[] = u"[A-Za-z0-9_\\-.]{7,30}"; -///////////////////////////////////////////////////////////////////////////// -// iban_field.cc -///////////////////////////////////////////////////////////////////////////// -const char16_t kIbanRe[] = - u"(\\biban(\\b|_)|international bank account number)"; - } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_regex_constants.h b/components/autofill/core/browser/autofill_regex_constants.h index 8458a20..639a768 100644 --- a/components/autofill/core/browser/autofill_regex_constants.h +++ b/components/autofill/core/browser/autofill_regex_constants.h
@@ -81,22 +81,18 @@ extern const char16_t kPhoneValueRe[]; extern const char16_t kUsernameLikeValueRe[]; -// Used to match the HTML name and label for International Bank Account Number -// (IBAN). -extern const char16_t kIbanRe[]; - // Used to match field data that might be a UPI Virtual Payment Address. // See: // - http://crbug.com/702220 // - https://upipayments.co.in/virtual-payment-address-vpa/ extern const char16_t kUPIVirtualPaymentAddressRe[]; -// Used to match field value that might be an International Bank Account Number. +// Used to match field data that might be an International Bank Account Number. // TODO(crbug.com/977377): The regex doesn't match IBANs for Saint Lucia (LC), // Kazakhstan (KZ) and Romania (RO). Consider replace the regex with something // like "(?:IT|SM)\d{2}[A-Z]\d{22}|CY\d{2}[A-Z]\d{23}...". For reference: // - https://www.swift.com/resource/iban-registry-pdf -extern const char16_t kInternationalBankAccountNumberValueRe[]; +extern const char16_t kInternationalBankAccountNumberRe[]; // Match the path values for form actions that look like generic search: // e.g. /search
diff --git a/components/autofill/core/browser/field_types.cc b/components/autofill/core/browser/field_types.cc index b480089..20ee50f8e 100644 --- a/components/autofill/core/browser/field_types.cc +++ b/components/autofill/core/browser/field_types.cc
@@ -101,8 +101,9 @@ case UPI_VPA: return base::FeatureList::IsEnabled(features::kAutofillSaveAndFillVPA); + // TODO(crbug/1335549) to return true when the flag is enabled. case IBAN_VALUE: - return base::FeatureList::IsEnabled(features::kAutofillParseIbanFields); + return false; case COMPANY_NAME: return true;
diff --git a/components/autofill/core/browser/field_types.h b/components/autofill/core/browser/field_types.h index ecdfd82..b68b3ef 100644 --- a/components/autofill/core/browser/field_types.h +++ b/components/autofill/core/browser/field_types.h
@@ -238,9 +238,7 @@ PHONE_HOME_NUMBER_PREFIX = 123, PHONE_HOME_NUMBER_SUFFIX = 124, - // International Bank Account Number (IBAN) details are usually entered on - // banking and merchant websites used to make international transactions. - // See [ https://en.wikipedia.org/wiki/International_Bank_Account_Number ]. + // IBAN data. IBAN_VALUE = 125, // No new types can be added without a corresponding change to the Autofill // server.
diff --git a/components/autofill/core/browser/form_parsing/form_field.cc b/components/autofill/core/browser/form_parsing/form_field.cc index 07f20fa5c..903b72c 100644 --- a/components/autofill/core/browser/form_parsing/form_field.cc +++ b/components/autofill/core/browser/form_parsing/form_field.cc
@@ -25,7 +25,6 @@ #include "components/autofill/core/browser/form_parsing/birthdate_field.h" #include "components/autofill/core/browser/form_parsing/credit_card_field.h" #include "components/autofill/core/browser/form_parsing/email_field.h" -#include "components/autofill/core/browser/form_parsing/iban_field.h" #include "components/autofill/core/browser/form_parsing/merchant_promo_code_field.h" #include "components/autofill/core/browser/form_parsing/name_field.h" #include "components/autofill/core/browser/form_parsing/phone_field.h" @@ -183,12 +182,6 @@ field_candidates, page_language, pattern_source, log_manager); } - - // IBAN pass. - if (base::FeatureList::IsEnabled(features::kAutofillParseIbanFields)) { - ParseFormFieldsPass(IbanField::Parse, processed_fields, field_candidates, - page_language, pattern_source, log_manager); - } } // static @@ -497,7 +490,7 @@ // static bool FormField::IsSingleFieldParseableType(ServerFieldType field_type) { - return (field_type == MERCHANT_PROMO_CODE || field_type == IBAN_VALUE); + return field_type == MERCHANT_PROMO_CODE; } } // namespace autofill
diff --git a/components/autofill/core/browser/form_parsing/form_field.h b/components/autofill/core/browser/form_parsing/form_field.h index 2985d65..fcd90f4 100644 --- a/components/autofill/core/browser/form_parsing/form_field.h +++ b/components/autofill/core/browser/form_parsing/form_field.h
@@ -92,14 +92,13 @@ // Initial values assigned to FieldCandidates by their corresponding parsers. // There's an implicit precedence determined by the values assigned here. // Email is currently the most important followed by Phone, Travel, Address, - // Birthdate, Credit Card, IBAN, Price, Name, Merchant promo code, and Search. + // Birthdate, Credit Card, Price, Name, Merchant promo code, and Search. static constexpr float kBaseEmailParserScore = 1.4f; static constexpr float kBasePhoneParserScore = 1.3f; static constexpr float kBaseTravelParserScore = 1.2f; static constexpr float kBaseAddressParserScore = 1.1f; static constexpr float kBaseBirthdateParserScore = 1.05f; static constexpr float kBaseCreditCardParserScore = 1.0f; - static constexpr float kBaseIbanParserScore = 0.975f; static constexpr float kBasePriceParserScore = 0.95f; static constexpr float kBaseNameParserScore = 0.9f; static constexpr float kBaseMerchantPromoCodeParserScore = 0.85f;
diff --git a/components/autofill/core/browser/form_parsing/form_field_unittest.cc b/components/autofill/core/browser/form_parsing/form_field_unittest.cc index 785d809..3c5e8e45 100644 --- a/components/autofill/core/browser/form_parsing/form_field_unittest.cc +++ b/components/autofill/core/browser/form_parsing/form_field_unittest.cc
@@ -196,7 +196,7 @@ } // Test that `ParseSingleFieldForms` parses single field promo codes. -TEST_P(FormFieldTest, ParseFormFieldsForSingleFieldPromoCode) { +TEST_P(FormFieldTest, ParseSingleFieldFormsPromoCode) { base::test::ScopedFeatureList scoped_feature; scoped_feature.InitAndEnableFeature( features::kAutofillParseMerchantPromoCodeFields); @@ -214,24 +214,6 @@ TestClassificationExpectations(); } -// Test that `ParseSingleFieldForms` parses single field IBAN. -TEST_P(FormFieldTest, ParseFormFieldsForSingleFieldIban) { - base::test::ScopedFeatureList scoped_feature; - scoped_feature.InitAndEnableFeature(features::kAutofillParseIbanFields); - - // Parse single field IBAN. - AddTextFormFieldData("", "IBAN", IBAN_VALUE); - EXPECT_EQ(1, ParseSingleFieldForms()); - TestClassificationExpectations(); - - // Don't parse other fields. - // UNKNOWN_TYPE is used as the expected type, which prevents it from being - // part of the expectations in `TestClassificationExpectations()`. - AddTextFormFieldData("", "Address line 1", UNKNOWN_TYPE); - EXPECT_EQ(1, ParseSingleFieldForms()); - TestClassificationExpectations(); -} - struct ParseInAnyOrderTestcase { // An nxn matrix, describing that field i is matched by parser j. std::vector<std::vector<bool>> field_matches_parser;
diff --git a/components/autofill/core/browser/form_parsing/iban_field.cc b/components/autofill/core/browser/form_parsing/iban_field.cc deleted file mode 100644 index 510b5aa..0000000 --- a/components/autofill/core/browser/form_parsing/iban_field.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/autofill/core/browser/form_parsing/iban_field.h" - -#include "components/autofill/core/browser/autofill_field.h" -#include "components/autofill/core/browser/autofill_regex_constants.h" -#include "components/autofill/core/browser/form_parsing/autofill_scanner.h" -#include "components/autofill/core/common/autofill_payments_features.h" - -namespace autofill { - -// static -std::unique_ptr<FormField> IbanField::Parse(AutofillScanner* scanner, - const LanguageCode& page_language, - PatternSource pattern_source, - LogManager* log_manager) { - if (!base::FeatureList::IsEnabled(features::kAutofillParseIbanFields)) { - return nullptr; - } - - AutofillField* field; - base::span<const MatchPatternRef> iban_patterns = - GetMatchPatterns("IBAN", page_language, pattern_source); - - if (ParseFieldSpecifics(scanner, kIbanRe, - kDefaultMatchParamsWith<MatchFieldType::kNumber, - MatchFieldType::kTextArea>, - iban_patterns, &field, {log_manager, "kIbanRe"})) { - return std::make_unique<IbanField>(field); - } - - return nullptr; -} - -IbanField::IbanField(const AutofillField* field) : field_(field) {} - -void IbanField::AddClassifications(FieldCandidatesMap* field_candidates) const { - AddClassification(field_, IBAN_VALUE, kBaseIbanParserScore, field_candidates); -} - -} // namespace autofill
diff --git a/components/autofill/core/browser/form_parsing/iban_field.h b/components/autofill/core/browser/form_parsing/iban_field.h deleted file mode 100644 index 9719230..0000000 --- a/components/autofill/core/browser/form_parsing/iban_field.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PARSING_IBAN_FIELD_H_ -#define COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PARSING_IBAN_FIELD_H_ - -#include <memory> - -#include "base/memory/raw_ptr.h" -#include "components/autofill/core/browser/form_parsing/form_field.h" -#include "components/autofill/core/common/language_code.h" - -namespace autofill { - -class AutofillField; -class AutofillScanner; -class LogManager; - -// A form field that accepts International Bank Account Number (IBAN). -class IbanField : public FormField { - public: - static std::unique_ptr<FormField> Parse(AutofillScanner* scanner, - const LanguageCode& page_language, - PatternSource pattern_source, - LogManager* log_manager); - explicit IbanField(const AutofillField* field); - - IbanField(const IbanField&) = delete; - IbanField& operator=(const IbanField&) = delete; - - protected: - void AddClassifications(FieldCandidatesMap* field_candidates) const override; - - private: - raw_ptr<const AutofillField> field_; -}; - -} // namespace autofill - -#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_PARSING_IBAN_FIELD_H_
diff --git a/components/autofill/core/browser/form_parsing/iban_field_unittest.cc b/components/autofill/core/browser/form_parsing/iban_field_unittest.cc deleted file mode 100644 index cc1bb879..0000000 --- a/components/autofill/core/browser/form_parsing/iban_field_unittest.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/autofill/core/browser/form_parsing/iban_field.h" - -#include "base/test/scoped_feature_list.h" -#include "components/autofill/core/browser/form_parsing/parsing_test_utils.h" -#include "components/autofill/core/common/autofill_payments_features.h" - -namespace autofill { - -class IbanFieldTest - : public FormFieldTestBase, - public testing::TestWithParam<PatternProviderFeatureState> { - public: - IbanFieldTest() : FormFieldTestBase(GetParam()) {} - IbanFieldTest(const IbanFieldTest&) = delete; - IbanFieldTest& operator=(const IbanFieldTest&) = delete; - - void SetUp() override { - scoped_feature_list_.InitAndEnableFeature( - features::kAutofillParseIbanFields); - } - - protected: - std::unique_ptr<FormField> Parse( - AutofillScanner* scanner, - const LanguageCode& page_language = LanguageCode("en")) override { - return IbanField::Parse(scanner, page_language, GetActivePatternSource(), - /*log_manager=*/nullptr); - } - - base::test::ScopedFeatureList scoped_feature_list_; -}; - -INSTANTIATE_TEST_SUITE_P( - IbanFieldTest, - IbanFieldTest, - ::testing::ValuesIn(PatternProviderFeatureState::All())); - -// Match IBAN -TEST_P(IbanFieldTest, ParseIban) { - AddTextFormFieldData("iban-field", "Enter account number", IBAN_VALUE); - - ClassifyAndVerify(ParseResult::PARSED); -} - -// Match IBAN on banks -TEST_P(IbanFieldTest, ParseIbanBanks) { - AddTextFormFieldData("accountNumber", "IBAN*", IBAN_VALUE); - - ClassifyAndVerify(ParseResult::PARSED); -} - -TEST_P(IbanFieldTest, ParseNonIban) { - AddTextFormFieldData("other-field", "Field for Account Number", UNKNOWN_TYPE); - - ClassifyAndVerify(ParseResult::NOT_PARSED); -} - -TEST_P(IbanFieldTest, ParseIbanFlagOff) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndDisableFeature(features::kAutofillParseIbanFields); - AddTextFormFieldData("iban-field", "Enter IBAN here", IBAN_VALUE); - - ClassifyAndVerify(ParseResult::NOT_PARSED); -} - -} // namespace autofill
diff --git a/components/autofill/core/browser/form_parsing/resources/legacy_regex_patterns.json b/components/autofill/core/browser/form_parsing/resources/legacy_regex_patterns.json index 8f1d4068..a4217b5a 100644 --- a/components/autofill/core/browser/form_parsing/resources/legacy_regex_patterns.json +++ b/components/autofill/core/browser/form_parsing/resources/legacy_regex_patterns.json
@@ -3315,17 +3315,5 @@ "match_field_input_types": [0] } ] - }, - "IBAN": { - "en": [ - { - "pattern_identifier": "en_iban_preserving", - "positive_pattern": "(\\biban(\\b|_)|international bank account number)", - "positive_score": 0.975, - "negative_pattern": null, - "match_field_attributes": [0, 1], - "match_field_input_types": [0] - } - ] } }
diff --git a/components/autofill/core/browser/validation.cc b/components/autofill/core/browser/validation.cc index a0dce14..7477247b 100644 --- a/components/autofill/core/browser/validation.cc +++ b/components/autofill/core/browser/validation.cc
@@ -350,7 +350,7 @@ std::u16string no_spaces; base::RemoveChars(value, u" ", &no_spaces); return MatchesPatternInMainThread(no_spaces, - kInternationalBankAccountNumberValueRe); + kInternationalBankAccountNumberRe); } bool IsPlausibleCreditCardCVCNumber(const std::u16string& value) {
diff --git a/components/bookmarks/managed/managed_bookmark_service.cc b/components/bookmarks/managed/managed_bookmark_service.cc index f74cd84..97d8578 100644 --- a/components/bookmarks/managed/managed_bookmark_service.cc +++ b/components/bookmarks/managed/managed_bookmark_service.cc
@@ -29,13 +29,12 @@ class BookmarkPermanentNodeLoader { public: BookmarkPermanentNodeLoader(std::unique_ptr<BookmarkPermanentNode> node, - base::Value initial_bookmarks, + base::Value::List initial_bookmarks, int title_id) : node_(std::move(node)), initial_bookmarks_(std::move(initial_bookmarks)), title_id_(title_id) { DCHECK(node_); - DCHECK(initial_bookmarks_.is_list()); } BookmarkPermanentNodeLoader(const BookmarkPermanentNodeLoader&) = delete; @@ -50,14 +49,14 @@ std::unique_ptr<BookmarkPermanentNode> Load(int64_t* next_node_id) { node_->set_id(*next_node_id); *next_node_id = ManagedBookmarksTracker::LoadInitial( - node_.get(), &initial_bookmarks_, node_->id() + 1); + node_.get(), initial_bookmarks_, node_->id() + 1); node_->SetTitle(l10n_util::GetStringUTF16(title_id_)); return std::move(node_); } private: std::unique_ptr<BookmarkPermanentNode> node_; - base::Value initial_bookmarks_; + base::Value::List initial_bookmarks_; int title_id_; };
diff --git a/components/bookmarks/managed/managed_bookmarks_policy_handler.cc b/components/bookmarks/managed/managed_bookmarks_policy_handler.cc index 5eef062c..45ff17a 100644 --- a/components/bookmarks/managed/managed_bookmarks_policy_handler.cc +++ b/components/bookmarks/managed/managed_bookmarks_policy_handler.cc
@@ -39,21 +39,21 @@ if (!value || !value->is_list()) return; - prefs->SetString(prefs::kManagedBookmarksFolderName, GetFolderName(*value)); + prefs->SetString(prefs::kManagedBookmarksFolderName, + GetFolderName(value->GetList())); base::Value::List filtered(FilterBookmarks(std::move(value->GetList()))); prefs->SetValue(prefs::kManagedBookmarks, base::Value(std::move(filtered))); } std::string ManagedBookmarksPolicyHandler::GetFolderName( - const base::Value& list) { - DCHECK(list.is_list()); + const base::Value::List& list) { // Iterate over the list, and try to find the FolderName. - for (const auto& el : list.GetListDeprecated()) { + for (const auto& el : list) { if (!el.is_dict()) continue; const std::string* name = - el.FindStringKey(ManagedBookmarksTracker::kFolderName); + el.GetDict().FindString(ManagedBookmarksTracker::kFolderName); if (name) return *name; }
diff --git a/components/bookmarks/managed/managed_bookmarks_policy_handler.h b/components/bookmarks/managed/managed_bookmarks_policy_handler.h index b565058f..e3cec725 100644 --- a/components/bookmarks/managed/managed_bookmarks_policy_handler.h +++ b/components/bookmarks/managed/managed_bookmarks_policy_handler.h
@@ -27,7 +27,7 @@ PrefValueMap* prefs) override; private: - std::string GetFolderName(const base::Value& list); + std::string GetFolderName(const base::Value::List& list); base::Value::List FilterBookmarks(base::Value::List bookmarks); };
diff --git a/components/bookmarks/managed/managed_bookmarks_tracker.cc b/components/bookmarks/managed/managed_bookmarks_tracker.cc index 6f831d9f..604ab3aa 100644 --- a/components/bookmarks/managed/managed_bookmarks_tracker.cc +++ b/components/bookmarks/managed/managed_bookmarks_tracker.cc
@@ -42,21 +42,21 @@ ManagedBookmarksTracker::~ManagedBookmarksTracker() {} -base::Value ManagedBookmarksTracker::GetInitialManagedBookmarks() { - const base::Value* list = prefs_->GetList(prefs::kManagedBookmarks); - return list->Clone(); +base::Value::List ManagedBookmarksTracker::GetInitialManagedBookmarks() { + const base::Value::List& list = + prefs_->GetValueList(prefs::kManagedBookmarks); + return list.Clone(); } // static int64_t ManagedBookmarksTracker::LoadInitial(BookmarkNode* folder, - const base::Value* list, + const base::Value::List& list, int64_t next_node_id) { - DCHECK(list->is_list()); - for (size_t i = 0; i < list->GetListDeprecated().size(); ++i) { + for (size_t i = 0; i < list.size(); ++i) { // Extract the data for the next bookmark from the |list|. std::u16string title; GURL url; - const base::Value* children = nullptr; + const base::Value::List* children = nullptr; if (!LoadBookmark(list, i, &title, &url, &children)) continue; @@ -65,7 +65,7 @@ child->SetTitle(title); if (children) { child->set_date_folder_modified(base::Time::Now()); - next_node_id = LoadInitial(child, children, next_node_id); + next_node_id = LoadInitial(child, *children, next_node_id); } else { child->set_date_added(base::Time::Now()); } @@ -108,19 +108,19 @@ model_->SetTitle(managed_node_, GetBookmarksFolderTitle()); // Recursively update all the managed bookmarks and folders. - const base::Value* list = prefs_->GetList(prefs::kManagedBookmarks); + const base::Value::List& list = + prefs_->GetValueList(prefs::kManagedBookmarks); UpdateBookmarks(managed_node_, list); } void ManagedBookmarksTracker::UpdateBookmarks(const BookmarkNode* folder, - const base::Value* list) { - DCHECK(list->is_list()); + const base::Value::List& list) { size_t folder_index = 0; - for (size_t i = 0; i < list->GetListDeprecated().size(); ++i) { + for (size_t i = 0; i < list.size(); ++i) { // Extract the data for the next bookmark from the |list|. std::u16string title; GURL url; - const base::Value* children = nullptr; + const base::Value::List* children = nullptr; if (!LoadBookmark(list, i, &title, &url, &children)) { // Skip this bookmark from |list| but don't advance |folder_index|. continue; @@ -140,9 +140,10 @@ const BookmarkNode* existing = j->get(); model_->Move(existing, folder, folder_index); if (children) - UpdateBookmarks(existing, children); + UpdateBookmarks(existing, *children); } else if (children) { - UpdateBookmarks(model_->AddFolder(folder, folder_index, title), children); + UpdateBookmarks(model_->AddFolder(folder, folder_index, title), + *children); } else { model_->AddURL(folder, folder_index, title, url); } @@ -157,24 +158,23 @@ } // static -bool ManagedBookmarksTracker::LoadBookmark(const base::Value* list, +bool ManagedBookmarksTracker::LoadBookmark(const base::Value::List& list, size_t index, std::u16string* title, GURL* url, - const base::Value** children) { - DCHECK(list->is_list()); + const base::Value::List** children) { *url = GURL(); *children = nullptr; - const base::Value& dict = list->GetListDeprecated()[index]; - if (!dict.is_dict()) { + const base::Value::Dict* dict = list[index].GetIfDict(); + if (!dict) { // Should never happen after policy validation. NOTREACHED(); return false; } - const std::string* name = dict.FindStringKey(kName); - const std::string* spec = dict.FindStringKey(kUrl); - const base::Value* children_list = dict.FindListKey(kChildren); - if (!dict.is_dict() || !name || (!spec && !children_list)) { + const std::string* name = dict->FindString(kName); + const std::string* spec = dict->FindString(kUrl); + const base::Value::List* children_list = dict->FindList(kChildren); + if (!name || (!spec && !children_list)) { // Should never happen after policy validation. NOTREACHED(); return false;
diff --git a/components/bookmarks/managed/managed_bookmarks_tracker.h b/components/bookmarks/managed/managed_bookmarks_tracker.h index 871bf8744..fc2b27c 100644 --- a/components/bookmarks/managed/managed_bookmarks_tracker.h +++ b/components/bookmarks/managed/managed_bookmarks_tracker.h
@@ -13,15 +13,12 @@ #include "base/callback_forward.h" #include "base/memory/raw_ptr.h" +#include "base/values.h" #include "components/prefs/pref_change_registrar.h" class GURL; class PrefService; -namespace base { -class Value; -} - namespace bookmarks { class BookmarkModel; @@ -51,13 +48,13 @@ // Returns the initial list of managed bookmarks, which can be passed to // LoadInitial() to do the initial load. - base::Value GetInitialManagedBookmarks(); + base::Value::List GetInitialManagedBookmarks(); // Loads the initial managed bookmarks in |list| into |folder|. // New nodes will be assigned IDs starting at |next_node_id|. // Returns the next node ID to use. static int64_t LoadInitial(BookmarkNode* folder, - const base::Value* list, + const base::Value::List& list, int64_t next_node_id); // Starts tracking the pref for updates to the managed bookmarks. @@ -69,12 +66,13 @@ void ReloadManagedBookmarks(); - void UpdateBookmarks(const BookmarkNode* folder, const base::Value* list); - static bool LoadBookmark(const base::Value* list, + void UpdateBookmarks(const BookmarkNode* folder, + const base::Value::List& list); + static bool LoadBookmark(const base::Value::List& list, size_t index, std::u16string* title, GURL* url, - const base::Value** children); + const base::Value::List** children); raw_ptr<BookmarkModel> model_; raw_ptr<BookmarkPermanentNode> managed_node_;
diff --git a/components/bookmarks/managed/managed_bookmarks_tracker_unittest.cc b/components/bookmarks/managed/managed_bookmarks_tracker_unittest.cc index 3d1d8563..8f4d50a 100644 --- a/components/bookmarks/managed/managed_bookmarks_tracker_unittest.cc +++ b/components/bookmarks/managed/managed_bookmarks_tracker_unittest.cc
@@ -57,7 +57,7 @@ auto client = std::make_unique<TestBookmarkClient>(); managed_node_ = client->EnableManagedNode(); ManagedBookmarksTracker::LoadInitial( - managed_node_, prefs_.GetList(prefs::kManagedBookmarks), 101); + managed_node_, prefs_.GetValueList(prefs::kManagedBookmarks), 101); managed_node_->SetTitle(l10n_util::GetStringUTF16( IDS_BOOKMARK_BAR_MANAGED_FOLDER_DEFAULT_NAME)); @@ -83,33 +83,33 @@ return node && node->HasAncestor(managed_node_.get()); } - void SetManagedPref(const std::string& path, const base::Value& value) { - prefs_.SetManagedPref(path, base::Value::ToUniquePtrValue(value.Clone())); + void SetManagedPref(const std::string& path, const base::Value::List& list) { + prefs_.SetManagedPref(path, base::Value(list.Clone())); } - static base::Value CreateBookmark(const std::string& title, - const std::string& url) { + static base::Value::Dict CreateBookmark(const std::string& title, + const std::string& url) { EXPECT_TRUE(GURL(url).is_valid()); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("name", title); - dict.SetStringKey("url", GURL(url).spec()); + base::Value::Dict dict; + dict.Set("name", title); + dict.Set("url", GURL(url).spec()); return dict; } - static base::Value CreateFolder(const std::string& title, - base::Value children) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("name", title); - dict.SetKey("children", std::move(children)); + static base::Value::Dict CreateFolder(const std::string& title, + base::Value::List children) { + base::Value::Dict dict; + dict.Set("name", title); + dict.Set("children", std::move(children)); return dict; } - static base::Value CreateTestTree() { - base::Value folder(base::Value::Type::LIST); - folder.Append(CreateFolder("Empty", base::Value(base::Value::Type::LIST))); + static base::Value::List CreateTestTree() { + base::Value::List folder; + folder.Append(CreateFolder("Empty", base::Value::List())); folder.Append(CreateBookmark("Youtube", "http://youtube.com/")); - base::Value list(base::Value::Type::LIST); + base::Value::List list; list.Append(CreateBookmark("Google", "http://google.com/")); list.Append(CreateFolder("Folder", std::move(folder))); @@ -125,34 +125,32 @@ IDS_BOOKMARK_BAR_MANAGED_FOLDER_DEFAULT_NAME); } - static base::Value CreateExpectedTree() { + static base::Value::Dict CreateExpectedTree() { return CreateFolder(GetManagedFolderTitle(), CreateTestTree()); } static bool NodeMatchesValue(const BookmarkNode* node, - const base::Value& dict) { - DCHECK(dict.is_dict()); - const std::string* title = dict.FindStringKey("name"); + const base::Value::Dict& dict) { + const std::string* title = dict.FindString("name"); if (!title || node->GetTitle() != base::UTF8ToUTF16(*title)) return false; if (node->is_folder()) { - const base::Value* children = dict.FindListKey("children"); - if (!children || - node->children().size() != children->GetListDeprecated().size()) + const base::Value::List* children = dict.FindList("children"); + if (!children || node->children().size() != children->size()) return false; size_t i = 0; return std::all_of(node->children().cbegin(), node->children().cend(), [children, &i](const auto& child_node) { - const base::Value& child = - children->GetListDeprecated()[i++]; + const base::Value& child = (*children)[i++]; return child.is_dict() && - NodeMatchesValue(child_node.get(), child); + NodeMatchesValue(child_node.get(), + child.GetDict()); }); } if (!node->is_url()) return false; - const std::string* url = dict.FindStringKey("url"); + const std::string* url = dict.FindString("url"); return url && node->url() == *url; } @@ -182,7 +180,7 @@ EXPECT_FALSE(managed_node()->children().empty()); EXPECT_TRUE(managed_node()->IsVisible()); - base::Value expected(CreateExpectedTree()); + base::Value::Dict expected(CreateExpectedTree()); EXPECT_TRUE(NodeMatchesValue(managed_node(), expected)); } @@ -198,7 +196,8 @@ EXPECT_FALSE(managed_node()->children().empty()); EXPECT_TRUE(managed_node()->IsVisible()); - base::Value expected(CreateFolder(kExpectedFolderName, CreateTestTree())); + base::Value::Dict expected( + CreateFolder(kExpectedFolderName, CreateTestTree())); EXPECT_TRUE(NodeMatchesValue(managed_node(), expected)); } @@ -207,11 +206,10 @@ CreateModel(); // Swap the Google bookmark with the Folder. - base::Value updated(CreateTestTree()); - base::Value::ListView updated_listview = updated.GetListDeprecated(); - ASSERT_FALSE(updated_listview.empty()); - base::Value removed = std::move(updated_listview[0]); - ASSERT_TRUE(updated.EraseListIter(updated_listview.begin())); + base::Value::List updated(CreateTestTree()); + ASSERT_FALSE(updated.empty()); + base::Value removed = std::move(updated[0]); + updated.erase(updated.begin()); updated.Append(std::move(removed)); // These two nodes should just be swapped. @@ -221,7 +219,7 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - base::Value expected( + base::Value::Dict expected( CreateFolder(GetManagedFolderTitle(), std::move(updated))); EXPECT_TRUE(NodeMatchesValue(managed_node(), expected)); } @@ -231,8 +229,8 @@ CreateModel(); // Remove the Folder. - base::Value updated(CreateTestTree()); - ASSERT_TRUE(updated.EraseListIter(updated.GetListDeprecated().begin() + 1)); + base::Value::List updated(CreateTestTree()); + updated.erase(updated.begin() + 1); const BookmarkNode* parent = managed_node(); EXPECT_CALL(observer_, BookmarkNodeRemoved(model_.get(), parent, 1, _, _)); @@ -240,7 +238,7 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - base::Value expected( + base::Value::Dict expected( CreateFolder(GetManagedFolderTitle(), std::move(updated))); EXPECT_TRUE(NodeMatchesValue(managed_node(), expected)); } @@ -250,7 +248,7 @@ CreateModel(); // Put all the nodes inside another folder. - base::Value updated(base::Value::Type::LIST); + base::Value::List updated; updated.Append(CreateFolder("Container", CreateTestTree())); EXPECT_CALL(observer_, BookmarkNodeAdded(model_.get(), _, _)).Times(5); @@ -263,7 +261,7 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - base::Value expected( + base::Value::Dict expected( CreateFolder(GetManagedFolderTitle(), std::move(updated))); EXPECT_TRUE(NodeMatchesValue(managed_node(), expected)); }
diff --git a/components/browser_ui/accessibility/android/java/src/org/chromium/components/browser_ui/accessibility/PageZoomCoordinator.java b/components/browser_ui/accessibility/android/java/src/org/chromium/components/browser_ui/accessibility/PageZoomCoordinator.java index 3961d05..d3954dd 100644 --- a/components/browser_ui/accessibility/android/java/src/org/chromium/components/browser_ui/accessibility/PageZoomCoordinator.java +++ b/components/browser_ui/accessibility/android/java/src/org/chromium/components/browser_ui/accessibility/PageZoomCoordinator.java
@@ -9,7 +9,11 @@ import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; +import org.chromium.content_public.browser.GestureListenerManager; +import org.chromium.content_public.browser.GestureStateListener; +import org.chromium.content_public.browser.LoadCommittedDetails; import org.chromium.content_public.browser.WebContents; +import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; @@ -22,6 +26,9 @@ private final Delegate mDelegate; private final PropertyModel mModel; private final PageZoomMediator mMediator; + private WebContentsObserver mWebContentsObserver; + private GestureListenerManager mGestureListenerManager; + private GestureStateListener mGestureListener; private View mView; private static Boolean sShouldShowMenuItemForTesting; @@ -60,10 +67,42 @@ } else { mView.setVisibility(View.VISIBLE); } - mMediator.setWebContents(webContents); - // TODO(mschillaci): Remove this when proper dismiss conditions are added. - mView.postDelayed(this::hide, 50000); + mMediator.setWebContents(webContents); + mWebContentsObserver = new WebContentsObserver(webContents) { + @Override + public void navigationEntryCommitted(LoadCommittedDetails details) { + // When navigation occurs (i.e. navigate to another link, forward/backward + // navigation), hide the dialog + // Only on navigationEntryCommitted to avoid premature dismissal during transient + // didStartNavigation events + hide(); + } + + @Override + public void wasHidden() { + // When the web contents are hidden (i.e. navigate to another tab), hide the dialog + hide(); + } + + @Override + public void onWebContentsLostFocus() { + // When the web contents loses focus (i.e. omnibox selected), hide the dialog + hide(); + } + }; + + mGestureListenerManager = GestureListenerManager.fromWebContents(webContents); + mGestureListener = new GestureStateListener() { + @Override + public void onScrollStarted( + int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) { + // On scroll, hide the dialog + hide(); + } + }; + + mGestureListenerManager.addListener(mGestureListener); } /** @@ -77,7 +116,15 @@ /** * Clean-up views and children during destruction. */ - public void destroy() {} + public void destroy() { + if (mWebContentsObserver != null) { + mWebContentsObserver.destroy(); + } + + if (mGestureListenerManager != null && mGestureListener != null) { + mGestureListenerManager.removeListener(mGestureListener); + } + } /** * Used for testing only, allows a mocked value for the {@link shouldShowMenuItem} method.
diff --git a/components/browser_ui/strings/android/browser_ui_strings.grd b/components/browser_ui/strings/android/browser_ui_strings.grd index 6182dfd7..6aaf643 100644 --- a/components/browser_ui/strings/android/browser_ui_strings.grd +++ b/components/browser_ui/strings/android/browser_ui_strings.grd
@@ -952,6 +952,12 @@ <message name="IDS_SEARCH_RESUMPTION_MODULE_SUBTITLE" desc="Subtitle of the search resumption module on NTP or Start surface."> Based on your last tab </message> + <message name="IDS_ACCESSIBILITY_EXPANDED" is_accessibility_with_no_ui="true" desc="Content description when the search resumption module is expanded."> + Expanded + </message> + <message name="IDS_ACCESSIBILITY_COLLAPSED" is_accessibility_with_no_ui="true" desc="Content description when the search resumption module is collapsed."> + Collapsed + </message> </messages> </release> </grit>
diff --git a/components/cdm/common/cdm_manifest.cc b/components/cdm/common/cdm_manifest.cc index 614942d..192e3da 100644 --- a/components/cdm/common/cdm_manifest.cc +++ b/components/cdm/common/cdm_manifest.cc
@@ -229,7 +229,7 @@ // As the manifest string does not include profiles, specify {} to indicate // that all relevant profiles should be considered supported. media::CdmCapability::VideoCodecMap result; - const std::vector<media::VideoCodecProfile> kAllProfiles = {}; + const media::VideoCodecInfo kAllProfiles; for (const auto& codec : supported_codecs) { if (codec == kCdmSupportedCodecVp8) { result.emplace(media::VideoCodec::kVP8, kAllProfiles);
diff --git a/components/cdm/common/cdm_manifest_unittest.cc b/components/cdm/common/cdm_manifest_unittest.cc index 18087bc..251eefdc5 100644 --- a/components/cdm/common/cdm_manifest_unittest.cc +++ b/components/cdm/common/cdm_manifest_unittest.cc
@@ -99,12 +99,12 @@ void CheckVideoCodecs(const media::CdmCapability::VideoCodecMap& actual, const std::vector<media::VideoCodec>& expected) { EXPECT_EQ(expected.size(), actual.size()); - for (const auto& codec : actual) { - EXPECT_TRUE(base::Contains(expected, codec.first)); + for (const auto& [video_codec, video_codec_info] : actual) { + EXPECT_TRUE(base::Contains(expected, video_codec)); // As the manifest only specifies codecs and not profiles, the list of // profiles should be empty to indicate that all profiles are supported. - EXPECT_TRUE(codec.second.empty()); + EXPECT_TRUE(video_codec_info.video_codec_profiles.empty()); } }
diff --git a/components/desks_storage/core/desk_test_util.cc b/components/desks_storage/core/desk_test_util.cc index d4aa25f7..90ac08ff 100644 --- a/components/desks_storage/core/desk_test_util.cc +++ b/components/desks_storage/core/desk_test_util.cc
@@ -46,17 +46,8 @@ deltas.push_back(MakeApp(kTestLacrosChromeAppId, "Test Chrome App", apps::AppType::kStandaloneBrowserChromeApp)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - cache->OnApps(std::move(deltas), apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - for (const auto& delta : deltas) { - mojom_deltas.push_back(apps::ConvertAppToMojomApp(delta)); - } - cache->OnApps(std::move(mojom_deltas), apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + cache->OnApps(std::move(deltas), apps::AppType::kUnknown, + /*should_notify_initialized=*/false); cache->SetAccountId(account_id); @@ -73,17 +64,8 @@ // all app_id to it. deltas.push_back(MakeApp(app_id, "Arc app", apps::AppType::kArc)); - if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { - cache->OnApps(std::move(deltas), apps::AppType::kUnknown, - /*should_notify_initialized=*/false); - } else { - std::vector<apps::mojom::AppPtr> mojom_deltas; - for (const auto& delta : deltas) { - mojom_deltas.push_back(apps::ConvertAppToMojomApp(delta)); - } - cache->OnApps(std::move(mojom_deltas), apps::mojom::AppType::kUnknown, - /*should_notify_initialized=*/false); - } + cache->OnApps(std::move(deltas), apps::AppType::kUnknown, + /*should_notify_initialized=*/false); cache->SetAccountId(account_id);
diff --git a/components/exo/client_controlled_shell_surface.cc b/components/exo/client_controlled_shell_surface.cc index e9403ae..43fb519 100644 --- a/components/exo/client_controlled_shell_surface.cc +++ b/components/exo/client_controlled_shell_surface.cc
@@ -1186,8 +1186,8 @@ // Animate PIP window movement unless it is being dragged. client_controlled_state_->set_next_bounds_change_animation_type( window_state->IsPip() && !window_state->is_dragged() - ? ash::ClientControlledState::kAnimationAnimated - : ash::ClientControlledState::kAnimationNone); + ? ash::WindowState::BoundsChangeAnimationType::kAnimate + : ash::WindowState::BoundsChangeAnimationType::kNone); return true; } @@ -1196,18 +1196,20 @@ return true; } - auto animation_type = ash::ClientControlledState::kAnimationNone; + auto animation_type = ash::WindowState::BoundsChangeAnimationType::kNone; switch (pending_window_state_) { case chromeos::WindowStateType::kNormal: if (widget_->IsMaximized() || widget_->IsFullscreen()) { - animation_type = ash::ClientControlledState::kAnimationCrossFade; + animation_type = + ash::WindowState::BoundsChangeAnimationType::kCrossFade; } break; case chromeos::WindowStateType::kMaximized: case chromeos::WindowStateType::kFullscreen: if (!window_state->IsPip()) - animation_type = ash::ClientControlledState::kAnimationCrossFade; + animation_type = + ash::WindowState::BoundsChangeAnimationType::kCrossFade; break; default:
diff --git a/components/guest_view/browser/guest_view_base.cc b/components/guest_view/browser/guest_view_base.cc index 408c9c71..6cb5ce8 100644 --- a/components/guest_view/browser/guest_view_base.cc +++ b/components/guest_view/browser/guest_view_base.cc
@@ -326,13 +326,6 @@ } // static -void GuestViewBase::CleanUp(content::BrowserContext* browser_context, - int embedder_process_id, - int view_instance_id) { - // TODO(paulmeyer): Add in any general GuestView cleanup work here. -} - -// static GuestViewBase* GuestViewBase::FromWebContents(const WebContents* web_contents) { WebContentsGuestViewMap* guest_map = g_webcontents_guestview_map.Pointer(); auto it = guest_map->find(web_contents);
diff --git a/components/guest_view/browser/guest_view_base.h b/components/guest_view/browser/guest_view_base.h index bdfecfa..af7b8f1 100644 --- a/components/guest_view/browser/guest_view_base.h +++ b/components/guest_view/browser/guest_view_base.h
@@ -53,15 +53,6 @@ public content::WebContentsObserver, public zoom::ZoomObserver { public: - // Cleans up state when this GuestView is being destroyed. - // Note that this cannot be done in the destructor since a GuestView could - // potentially be created and destroyed in JavaScript before getting a - // GuestViewBase instance. This method can be hidden by a CleanUp() method in - // a derived class, in which case the derived method should call this one. - static void CleanUp(content::BrowserContext* browser_context, - int embedder_process_id, - int view_instance_id); - static GuestViewBase* FromWebContents( const content::WebContents* web_contents);
diff --git a/components/guest_view/browser/guest_view_manager.cc b/components/guest_view/browser/guest_view_manager.cc index c5d3a2a..1e4c46d 100644 --- a/components/guest_view/browser/guest_view_manager.cc +++ b/components/guest_view/browser/guest_view_manager.cc
@@ -72,10 +72,7 @@ GuestViewManager::GuestViewManager( content::BrowserContext* context, std::unique_ptr<GuestViewManagerDelegate> delegate) - : current_instance_id_(0), - last_instance_id_removed_(0), - context_(context), - delegate_(std::move(delegate)) {} + : context_(context), delegate_(std::move(delegate)) {} GuestViewManager::~GuestViewManager() { // It seems that ChromeOS OTR profiles may still have RenderProcessHosts at @@ -336,10 +333,12 @@ } // Register the cleanup callback for when this view is destroyed. - RegisterViewDestructionCallback( - embedder_process_id, view_instance_id, - base::BindOnce(view_it->second.cleanup_function, context_, - embedder_process_id, view_instance_id)); + if (view_it->second.cleanup_function) { + RegisterViewDestructionCallback( + embedder_process_id, view_instance_id, + base::BindOnce(view_it->second.cleanup_function, context_, + embedder_process_id, view_instance_id)); + } } void GuestViewManager::ViewGarbageCollected(int embedder_process_id, @@ -399,7 +398,23 @@ } void GuestViewManager::RegisterGuestViewTypes() { - delegate_->RegisterAdditionalGuestViewTypes(); + delegate_->RegisterAdditionalGuestViewTypes(this); +} + +void GuestViewManager::RegisterGuestViewType( + const std::string& type, + GuestViewCreateFunction create_function, + GuestViewCleanUpFunction cleanup_function) { + // If the GuestView type `type` is already registered, then there is nothing + // more to do. If an existing entry in the registry was created by this + // function for `type`, then registering again would have no effect, and + // if it was registered elsewhere, then we do not want to overwrite it. Note + // that it is possible for tests to have special test factory methods + // registered here. + if (base::Contains(guest_view_registry_, type)) + return; + + guest_view_registry_.insert({type, {create_function, cleanup_function}}); } void GuestViewManager::RegisterViewDestructionCallback( @@ -563,6 +578,6 @@ GuestViewManager::GuestViewData::GuestViewData(const GuestViewData& other) = default; -GuestViewManager::GuestViewData::~GuestViewData() {} +GuestViewManager::GuestViewData::~GuestViewData() = default; } // namespace guest_view
diff --git a/components/guest_view/browser/guest_view_manager.h b/components/guest_view/browser/guest_view_manager.h index 2f5931c..a50c8003 100644 --- a/components/guest_view/browser/guest_view_manager.h +++ b/components/guest_view/browser/guest_view_manager.h
@@ -83,21 +83,15 @@ int owner_process_id, int element_instance_id); - template <typename T> - void RegisterGuestViewType() { - // If the GuestView type |T| is already registered, then there is nothing - // more to do. If an existing entry in the registry was created by this - // function for type |T|, then registering again would have no effect, and - // if it was registered elsewhere, then we do not want to overwrite it. Note - // that it is possible for tests to have special test factory methods - // registered here. - if (guest_view_registry_.count(T::Type)) - return; - auto registry_entry = std::make_pair( - T::Type, GuestViewData(base::BindRepeating(&T::Create), - base::BindRepeating(&T::CleanUp))); - guest_view_registry_.insert(registry_entry); - } + using GuestViewCreateFunction = base::RepeatingCallback<GuestViewBase*( + content::WebContents* owner_web_contents)>; + using GuestViewCleanUpFunction = + base::RepeatingCallback<void(content::BrowserContext*, + int embedder_process_id, + int view_instance_id)>; + void RegisterGuestViewType(const std::string& type, + GuestViewCreateFunction create_function, + GuestViewCleanUpFunction cleanup_function); // Registers a callback to be called when the view identified by // |embedder_process_id| and |view_instance_id| is destroyed. @@ -227,10 +221,6 @@ using GuestInstanceIDReverseMap = std::map<int, ElementInstanceKey>; GuestInstanceIDReverseMap reverse_instance_id_map_; - using GuestViewCreateFunction = - base::RepeatingCallback<GuestViewBase*(content::WebContents*)>; - using GuestViewCleanUpFunction = - base::RepeatingCallback<void(content::BrowserContext*, int, int)>; struct GuestViewData { GuestViewData(const GuestViewCreateFunction& create_function, const GuestViewCleanUpFunction& cleanup_function); @@ -242,13 +232,13 @@ using GuestViewMethodMap = std::map<std::string, GuestViewData>; GuestViewMethodMap guest_view_registry_; - int current_instance_id_; + int current_instance_id_ = 0; // Any instance ID whose number not greater than this was removed via // RemoveGuest. // This is used so that we don't have store all removed instance IDs in // |removed_instance_ids_|. - int last_instance_id_removed_; + int last_instance_id_removed_ = 0; // The remaining instance IDs that are greater than // |last_instance_id_removed_| are kept here. std::set<int> removed_instance_ids_;
diff --git a/components/guest_view/browser/guest_view_manager_delegate.h b/components/guest_view/browser/guest_view_manager_delegate.h index 9747417..9566625 100644 --- a/components/guest_view/browser/guest_view_manager_delegate.h +++ b/components/guest_view/browser/guest_view_manager_delegate.h
@@ -21,6 +21,7 @@ namespace guest_view { class GuestViewBase; +class GuestViewManager; // A GuestViewManagerDelegate interface allows GuestViewManager to delegate // responsibilities to other modules in Chromium. Different builds of Chromium @@ -52,7 +53,7 @@ // Registers additional GuestView types the delegator (GuestViewManger) can // create. - virtual void RegisterAdditionalGuestViewTypes() {} + virtual void RegisterAdditionalGuestViewTypes(GuestViewManager* manager) {} }; } // namespace guest_view
diff --git a/components/guest_view/browser/test_guest_view_manager.h b/components/guest_view/browser/test_guest_view_manager.h index 5abf47e..8b424621 100644 --- a/components/guest_view/browser/test_guest_view_manager.h +++ b/components/guest_view/browser/test_guest_view_manager.h
@@ -49,15 +49,6 @@ // Returns the size of the set of removed instance IDs. size_t GetNumRemovedInstanceIDs() const; - template <typename T> - void RegisterTestGuestViewType( - const GuestViewCreateFunction& create_function) { - auto registry_entry = std::make_pair( - T::Type, - GuestViewData(create_function, base::BindRepeating(&T::CleanUp))); - guest_view_registry_.insert(registry_entry); - } - // Returns the number of times EmbedderWillBeDestroyed() was called. int num_embedder_processes_destroyed() const { return num_embedder_processes_destroyed_;
diff --git a/components/history_clusters/core/clusterer.cc b/components/history_clusters/core/clusterer.cc index cefec43d..402ce9a 100644 --- a/components/history_clusters/core/clusterer.cc +++ b/components/history_clusters/core/clusterer.cc
@@ -50,11 +50,10 @@ std::vector<history::Cluster> Clusterer::CreateInitialClustersFromVisits( std::vector<history::ClusterVisit>* visits) { - // Sort visits by visit ID. + // Sort visits by visit time. std::sort(visits->begin(), visits->end(), [](const history::ClusterVisit& a, const history::ClusterVisit& b) { - return a.annotated_visit.visit_row.visit_id < - b.annotated_visit.visit_row.visit_id; + return a.annotated_visit.visit_row < b.annotated_visit.visit_row; }); base::flat_map<std::string, size_t> url_to_cluster_map;
diff --git a/components/history_clusters/core/clusterer_unittest.cc b/components/history_clusters/core/clusterer_unittest.cc index 77e58fe2..899d543d 100644 --- a/components/history_clusters/core/clusterer_unittest.cc +++ b/components/history_clusters/core/clusterer_unittest.cc
@@ -34,8 +34,8 @@ std::vector<history::ClusterVisit> visits; // Fill in the visits vector with 1 visit. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit(visit)); std::vector<history::Cluster> result_clusters = @@ -48,12 +48,12 @@ std::vector<history::ClusterVisit> visits; // Visit2's referrer is visit 1 and are close together. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit(visit)); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/next")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/next"), base::Time::FromTimeT(2)); visit2.referring_visit_of_redirect_chain_start = 1; visits.push_back(testing::CreateClusterVisit(visit2)); @@ -67,20 +67,22 @@ TEST_F(ClustererTest, ClusterTwoVisitsTiedByOpenerVisit) { std::vector<history::ClusterVisit> visits; - // Visit2's referrer is visit 1 and are close together. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + // Visit2's referrer is visit 5 and are close together. Have the visit IDs be + // misordered to ensure that the visits are sorted by visit time rather than + // by ID. + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 5, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit(visit)); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/next")); - visit2.opener_visit_of_redirect_chain_start = 1; + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/next"), base::Time::FromTimeT(2)); + visit2.opener_visit_of_redirect_chain_start = 5; visits.push_back(testing::CreateClusterVisit(visit2)); std::vector<history::Cluster> result_clusters = CreateInitialClustersFromVisits(visits); EXPECT_THAT(testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(1, 1.0), + ElementsAre(ElementsAre(testing::VisitResult(5, 1.0), testing::VisitResult(2, 1.0)))); } @@ -88,12 +90,12 @@ std::vector<history::ClusterVisit> visits; // Visit2 has the same URL as Visit1. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit(visit)); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visits.push_back(testing::CreateClusterVisit(visit2)); std::vector<history::Cluster> result_clusters = @@ -108,12 +110,13 @@ // Visit2 has the same URL as Visit1. history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( - 1, GURL("https://example.com/normalized?q=whatever")); + 1, GURL("https://example.com/normalized?q=whatever"), + base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit( visit, GURL("https://example.com/normalized"))); history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( - 2, GURL("https://example.com/normalized")); + 2, GURL("https://example.com/normalized"), base::Time::FromTimeT(2)); visits.push_back(testing::CreateClusterVisit(visit2)); std::vector<history::Cluster> result_clusters = @@ -130,30 +133,30 @@ // Visit 3 is a different journey altogether. Visit 10 is referring to a // missing visit and should be considered as in its own cluster. // Also, make sure these aren't sorted so we test that we are sorting the - // visits by visit ID. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://github.com/")); + // visits by time. + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://github.com/"), base::Time::FromTimeT(1)); visits.push_back(testing::CreateClusterVisit(visit)); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visit2.referring_visit_of_redirect_chain_start = 1; // Set the visit duration to be 2x the default so it has the same duration // after |visit| and |visit4| are deduped. visit2.visit_row.visit_duration = base::Seconds(20); visits.push_back(testing::CreateClusterVisit(visit2)); - history::AnnotatedVisit visit4 = - testing::CreateDefaultAnnotatedVisit(4, GURL("https://github.com/")); + history::AnnotatedVisit visit4 = testing::CreateDefaultAnnotatedVisit( + 4, GURL("https://github.com/"), base::Time::FromTimeT(4)); visits.push_back(testing::CreateClusterVisit(visit4)); history::AnnotatedVisit visit5 = testing::CreateDefaultAnnotatedVisit( - 10, GURL("https://nonexistentreferrer.com/")); + 10, GURL("https://nonexistentreferrer.com/"), base::Time::FromTimeT(10)); visit5.referring_visit_of_redirect_chain_start = 6; visits.push_back(testing::CreateClusterVisit(visit5)); - history::AnnotatedVisit visit3 = - testing::CreateDefaultAnnotatedVisit(3, GURL("https://whatever.com/")); + history::AnnotatedVisit visit3 = testing::CreateDefaultAnnotatedVisit( + 3, GURL("https://whatever.com/"), base::Time::FromTimeT(3)); visits.push_back(testing::CreateClusterVisit(visit3)); std::vector<history::Cluster> result_clusters =
diff --git a/components/history_clusters/core/history_clusters_db_tasks.cc b/components/history_clusters/core/history_clusters_db_tasks.cc index 5d1b0f0..9a0545b 100644 --- a/components/history_clusters/core/history_clusters_db_tasks.cc +++ b/components/history_clusters/core/history_clusters_db_tasks.cc
@@ -162,7 +162,10 @@ // Filter out visits from sync. // TODO(manukh): Consider allowing the clustering backend to handle sync // visits. - const bool is_clustered = db->IsVisitClustered(visit.visit_row.visit_id); + const bool is_clustered = + GetConfig().persist_clusters_in_history_db + ? db->IsVisitClustered(visit.visit_row.visit_id) + : false; if (is_clustered && recent_first_) continuation_params_.exhausted_unclustered_visits = true; if (!is_clustered && visit.source != history::SOURCE_SYNCED)
diff --git a/components/history_clusters/core/history_clusters_service_task_get_most_recent_clusters.cc b/components/history_clusters/core/history_clusters_service_task_get_most_recent_clusters.cc index 80f3da1..59c194d 100644 --- a/components/history_clusters/core/history_clusters_service_task_get_most_recent_clusters.cc +++ b/components/history_clusters/core/history_clusters_service_task_get_most_recent_clusters.cc
@@ -174,16 +174,15 @@ void HistoryClustersServiceTaskGetMostRecentClusters:: ReturnMostRecentPersistedClusters(base::Time exclusive_max_time) { - if (GetConfig().persist_clusters_in_history_db) - OnGotMostRecentPersistedClusters({}); - - else { + if (GetConfig().persist_clusters_in_history_db) { history_service_->GetMostRecentClusters( begin_time_, exclusive_max_time, 1, base::BindOnce(&HistoryClustersServiceTaskGetMostRecentClusters:: OnGotMostRecentPersistedClusters, weak_ptr_factory_.GetWeakPtr()), &task_tracker_); + } else { + OnGotMostRecentPersistedClusters({}); } }
diff --git a/components/history_clusters/core/history_clusters_service_unittest.cc b/components/history_clusters/core/history_clusters_service_unittest.cc index 0b6ec7b8..cb7140bf 100644 --- a/components/history_clusters/core/history_clusters_service_unittest.cc +++ b/components/history_clusters/core/history_clusters_service_unittest.cc
@@ -355,6 +355,9 @@ public: HistoryClustersServiceTest() { scoped_feature_list_.InitAndEnableFeature(internal::kJourneys); + Config config; + config.persist_clusters_in_history_db = true; + SetConfigForTesting(config); } }; @@ -410,7 +413,7 @@ EXPECT_EQ(test_clustering_backend_->LastClusteredVisits().size(), 20U); } -TEST_F(HistoryClustersServiceTest, QueryClustersIncompleteAndPersistedVisits) { +TEST_F(HistoryClustersServiceTest, QueryClusters_IncompleteAndPersistedVisits) { // Create 5 persisted visits with visit times 2, 1, 1, 60, and 1 days ago. AddHardcodedTestDataToHistoryService(); @@ -463,7 +466,8 @@ } } -TEST_F(HistoryClustersServiceTest, QueryClustersPersistedClusters_NoMixedDays) { +TEST_F(HistoryClustersServiceTest, + QueryClusters_PersistedClusters_NoMixedDays) { // Test the case where there are persisted clusters but none on a day also // containing unclustered visits. @@ -545,7 +549,53 @@ } } -TEST_F(HistoryClustersServiceTest, QueryClustersPersistedClusters_MixedDay) { +TEST_F(HistoryClustersServiceTest, + QueryClusters_PersistedClusters_PersistenceDisabled) { + // Test the case where there are persisted clusters but persistence is + // disabled to check users who were in an enabled then disabled group + // don't encounter weirdness. + + Config config; + config.persist_clusters_in_history_db = false; + SetConfigForTesting(config); + + // Unclustered visit. + AddCompleteVisit(1, DaysAgo(1)); + + // Clustered visit; i.e. persisted cluster. + AddCompleteVisit(2, DaysAgo(2)); + AddCluster({2}); + + QueryClustersContinuationParams continuation_params = {}; + continuation_params.continuation_time = base::Time::Now(); + + // 2 queries should return the 2 visits and treat both as unclustered. + { + const auto [clusters, visits] = NextQueryClusters(continuation_params); + EXPECT_THAT(GetClusterIds(clusters), testing::ElementsAre()); + EXPECT_THAT(GetVisitIds(visits), testing::ElementsAre(1)); + EXPECT_FALSE(continuation_params.exhausted_unclustered_visits); + EXPECT_FALSE(continuation_params.exhausted_all_visits); + } + { + const auto [clusters, visits] = NextQueryClusters(continuation_params); + EXPECT_THAT(GetClusterIds(clusters), testing::ElementsAre()); + EXPECT_THAT(GetVisitIds(visits), testing::ElementsAre(2)); + EXPECT_FALSE(continuation_params.exhausted_unclustered_visits); + EXPECT_FALSE(continuation_params.exhausted_all_visits); + } + // 3rd query should consider history exhausted. + { + const auto [clusters, visits] = + NextQueryClusters(continuation_params, false); + EXPECT_THAT(GetClusterIds(clusters), testing::ElementsAre()); + EXPECT_THAT(GetVisitIds(visits), testing::ElementsAre()); + EXPECT_TRUE(continuation_params.exhausted_unclustered_visits); + EXPECT_TRUE(continuation_params.exhausted_all_visits); + } +} + +TEST_F(HistoryClustersServiceTest, QueryClusters_PersistedClusters_MixedDay) { // Test the case where there are persisted clusters on a day also containing // unclustered visits. @@ -617,7 +667,7 @@ } } -TEST_F(HistoryClustersServiceTest, QueryVisitsOldestFirst) { +TEST_F(HistoryClustersServiceTest, QueryVisits_OldestFirst) { // Create 5 persisted visits with visit times 2, 1, 1, 60, and 1 days ago. AddHardcodedTestDataToHistoryService();
diff --git a/components/history_clusters/core/on_device_clustering_backend_unittest.cc b/components/history_clusters/core/on_device_clustering_backend_unittest.cc index 1ecd4a0b..538c00cf 100644 --- a/components/history_clusters/core/on_device_clustering_backend_unittest.cc +++ b/components/history_clusters/core/on_device_clustering_backend_unittest.cc
@@ -202,14 +202,14 @@ std::vector<history::AnnotatedVisit> visits; // Visit2's referrer is visit 1 and are close together. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visit.content_annotations.model_annotations.categories = { {"google-category", 100}, {"com", 100}}; visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/next")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/next"), base::Time::FromTimeT(2)); visit2.content_annotations.model_annotations.entities = { {"google-entity", 100}, {"com", 100}}; visit2.referring_visit_of_redirect_chain_start = 1; @@ -218,8 +218,8 @@ std::vector<history::Cluster> result_clusters = ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); EXPECT_THAT(testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(1, 1.0), - testing::VisitResult(2, 1.0)))); + ElementsAre(ElementsAre(testing::VisitResult(2, 1.0), + testing::VisitResult(1, 1.0)))); ASSERT_EQ(result_clusters.size(), 1u); EXPECT_THAT(result_clusters.at(0).GetKeywords(), UnorderedElementsAre(std::u16string(u"google-category"), @@ -242,20 +242,20 @@ std::vector<history::AnnotatedVisit> visits; // Visit2's referrer is visit 1 and are close together. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/next")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/next"), base::Time::FromTimeT(2)); visit2.opener_visit_of_redirect_chain_start = 1; visits.push_back(visit2); std::vector<history::Cluster> result_clusters = ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); EXPECT_THAT(testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(1, 1.0), - testing::VisitResult(2, 1.0)))); + ElementsAre(ElementsAre(testing::VisitResult(2, 1.0), + testing::VisitResult(1, 1.0)))); histogram_tester.ExpectUniqueSample( "History.Clusters.Backend.ClusterSize.Min", 2, 1); histogram_tester.ExpectUniqueSample( @@ -271,12 +271,12 @@ std::vector<history::AnnotatedVisit> visits; // Visit2 has the same URL as Visit1. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visits.push_back(visit2); std::vector<history::Cluster> result_clusters = @@ -298,12 +298,12 @@ std::vector<history::AnnotatedVisit> visits; // Visit2 has the same URL as Visit1. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visits.push_back(visit2); std::vector<history::Cluster> result_clusters = @@ -318,20 +318,20 @@ std::vector<history::AnnotatedVisit> visits; // Visit2 has a different URL but is linked by referring id. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://google.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://google.com/"), base::Time::FromTimeT(1)); visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://foo.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://foo.com/"), base::Time::FromTimeT(2)); visit2.referring_visit_of_redirect_chain_start = 1; visits.push_back(visit2); std::vector<history::Cluster> result_clusters = ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); EXPECT_THAT(testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(1, 1.0), - testing::VisitResult(2, 1.0)))); + ElementsAre(ElementsAre(testing::VisitResult(2, 1.0), + testing::VisitResult(1, 1.0)))); } TEST_F(OnDeviceClusteringWithoutContentBackendTest, MultipleClusters) { @@ -343,42 +343,43 @@ // missing visit and should be considered as in its own cluster. // Also, make sure these aren't sorted so we test that we are sorting the // visits by visit ID. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://github.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://github.com/"), base::Time::FromTimeT(1)); visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visit2.referring_visit_of_redirect_chain_start = 1; // Set the visit duration to be 2x the default so it has the same duration // after |visit| and |visit4| are deduped. visit2.visit_row.visit_duration = base::Seconds(20); visits.push_back(visit2); - history::AnnotatedVisit visit4 = - testing::CreateDefaultAnnotatedVisit(4, GURL("https://github.com/")); + history::AnnotatedVisit visit4 = testing::CreateDefaultAnnotatedVisit( + 4, GURL("https://github.com/"), base::Time::FromTimeT(4)); visits.push_back(visit4); history::AnnotatedVisit visit5 = testing::CreateDefaultAnnotatedVisit( - 10, GURL("https://nonexistentreferrer.com/")); + 10, GURL("https://nonexistentreferrer.com/"), base::Time::FromTimeT(10)); visit5.referring_visit_of_redirect_chain_start = 6; visits.push_back(visit5); // Although it says shouldskip, it should not be skipped since there is no // optimization guide decider. history::AnnotatedVisit visit3 = testing::CreateDefaultAnnotatedVisit( - 3, GURL("https://shouldskip.com/butnotsincenodecider")); + 3, GURL("https://shouldskip.com/butnotsincenodecider"), + base::Time::FromTimeT(3)); visits.push_back(visit3); std::vector<history::Cluster> result_clusters = ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); EXPECT_THAT( testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(2, 1.0), - testing::VisitResult( - 4, 1.0, {testing::VisitResult(1, 0.0)})), - ElementsAre(testing::VisitResult(3, 1.0)), - ElementsAre(testing::VisitResult(10, 1.0)))); + ElementsAre(ElementsAre(testing::VisitResult(10, 1.0)), + ElementsAre(testing::VisitResult( + 4, 1.0, {testing::VisitResult(1, 0.0)}), + testing::VisitResult(2, 1.0)), + ElementsAre(testing::VisitResult(3, 1.0)))); histogram_tester.ExpectUniqueSample( "History.Clusters.Backend.ClusterSize.Min", 1, 1); histogram_tester.ExpectUniqueSample( @@ -454,14 +455,14 @@ // missing visit and should be considered as in its own cluster. // Also, make sure these aren't sorted so we test that we are sorting the // visits by visit ID. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://github.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://github.com/"), base::Time::FromTimeT(1)); visit.content_annotations.model_annotations.entities = {{"github", 100}}; visit.content_annotations.model_annotations.categories = {{"category", 100}}; visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visit2.content_annotations.model_annotations.entities = {{"github", 100}}; visit2.content_annotations.model_annotations.categories = {{"category", 100}}; visit2.referring_visit_of_redirect_chain_start = 1; @@ -470,8 +471,8 @@ visit2.visit_row.visit_duration = base::Seconds(20); visits.push_back(visit2); - history::AnnotatedVisit visit4 = - testing::CreateDefaultAnnotatedVisit(4, GURL("https://github.com/")); + history::AnnotatedVisit visit4 = testing::CreateDefaultAnnotatedVisit( + 4, GURL("https://github.com/"), base::Time::FromTimeT(4)); visit4.content_annotations.model_annotations.entities = {{"github", 100}}; visit4.content_annotations.model_annotations.categories = { {"category", 100}, {"category2", 100}}; @@ -481,8 +482,10 @@ // visit, visit2, and visit4 but all of the visits have the same entities // and categories so they will be clustered in the content pass. history::AnnotatedVisit visit5 = testing::CreateDefaultAnnotatedVisit( - 10, GURL("https://shouldskip.com/butnotsincehostcheckingisfalse/" - "andhasnonexistentreferrer")); + 10, + GURL("https://shouldskip.com/butnotsincehostcheckingisfalse/" + "andhasnonexistentreferrer"), + base::Time::FromTimeT(10)); visit5.content_annotations.model_annotations.entities = {{"github", 100}}; visit5.content_annotations.model_annotations.categories = { {"category", 100}, {"category2", 100}}; @@ -491,11 +494,11 @@ std::vector<history::Cluster> result_clusters = ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); - EXPECT_THAT(testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre( - testing::VisitResult(2, 1.0), - testing::VisitResult(4, 1.0, {testing::VisitResult(1, 0.0)}), - testing::VisitResult(10, 0.5)))); + EXPECT_THAT( + testing::ToVisitResults(result_clusters), + ElementsAre(ElementsAre( + testing::VisitResult(4, 1.0, {testing::VisitResult(1, 0.0)}), + testing::VisitResult(2, 1.0), testing::VisitResult(10, 0.5)))); } TEST_F(OnDeviceClusteringWithContentBackendTest, @@ -508,14 +511,14 @@ // missing visit and should be considered as in its own cluster. // Also, make sure these aren't sorted so we test that we are sorting the // visits by visit ID. - history::AnnotatedVisit visit = - testing::CreateDefaultAnnotatedVisit(1, GURL("https://github.com/")); + history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( + 1, GURL("https://github.com/"), base::Time::FromTimeT(1)); visit.content_annotations.model_annotations.entities = {{"github", 100}}; visit.content_annotations.model_annotations.categories = {{"category", 100}}; visits.push_back(visit); - history::AnnotatedVisit visit2 = - testing::CreateDefaultAnnotatedVisit(2, GURL("https://google.com/")); + history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( + 2, GURL("https://google.com/"), base::Time::FromTimeT(2)); visit2.referring_visit_of_redirect_chain_start = 1; // Set the visit duration to be 2x the default so it has the same duration // after |visit| and |visit4| are deduped. @@ -525,15 +528,15 @@ // After the context clustering, visit4 will not be in the same cluster as // visit and visit2 but should be clustered together since they have the same // title. - history::AnnotatedVisit visit4 = - testing::CreateDefaultAnnotatedVisit(4, GURL("https://github.com/")); + history::AnnotatedVisit visit4 = testing::CreateDefaultAnnotatedVisit( + 4, GURL("https://github.com/"), base::Time::FromTimeT(4)); visit4.content_annotations.model_annotations.entities = {{"github", 100}}; visit4.content_annotations.model_annotations.categories = {{"category", 100}}; visits.push_back(visit4); // This visit has a different title and shouldn't be grouped with the others. history::AnnotatedVisit visit5 = testing::CreateDefaultAnnotatedVisit( - 10, GURL("https://nonexistentreferrer.com/")); + 10, GURL("https://nonexistentreferrer.com/"), base::Time::FromTimeT(10)); visit5.referring_visit_of_redirect_chain_start = 6; visit5.content_annotations.model_annotations.entities = {{"irrelevant", 100}}; visits.push_back(visit5); @@ -542,10 +545,10 @@ ClusterVisits(ClusteringRequestSource::kJourneysPage, visits); EXPECT_THAT( testing::ToVisitResults(result_clusters), - ElementsAre(ElementsAre(testing::VisitResult(2, 1.0), - testing::VisitResult( - 4, 1.0, {testing::VisitResult(1, 0.0)})), - ElementsAre(testing::VisitResult(10, 1.0)))); + ElementsAre(ElementsAre(testing::VisitResult(10, 1.0)), + ElementsAre(testing::VisitResult( + 4, 1.0, {testing::VisitResult(1, 0.0)}), + testing::VisitResult(2, 1.0)))); histogram_tester.ExpectUniqueSample( "History.Clusters.Backend.ClusterSize.Min", 1, 1); histogram_tester.ExpectUniqueSample( @@ -627,7 +630,8 @@ // Visit2 has the same search URL as Visit1. history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit( - 1, GURL("http://default-engine.com/?q=foo&otherstuff")); + 1, GURL("http://default-engine.com/?q=foo&otherstuff"), + base::Time::FromTimeT(1)); visit.content_annotations.model_annotations.visibility_score = 0.5; visit.content_annotations.search_terms = u"foo"; visit.content_annotations.search_normalized_url = @@ -635,7 +639,7 @@ visits.push_back(visit); history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit( - 2, GURL("http://default-engine.com/?q=foo")); + 2, GURL("http://default-engine.com/?q=foo"), base::Time::FromTimeT(2)); visit2.content_annotations.model_annotations.entities = { history::VisitContentModelAnnotations::Category("foo", 70), history::VisitContentModelAnnotations::Category("nometadata", 100), @@ -648,7 +652,8 @@ visits.push_back(visit2); history::AnnotatedVisit visit3 = testing::CreateDefaultAnnotatedVisit( - 3, GURL("http://non-default-engine.com/?q=nometadata#whatever")); + 3, GURL("http://non-default-engine.com/?q=nometadata#whatever"), + base::Time::FromTimeT(3)); visit3.content_annotations.model_annotations.entities = { history::VisitContentModelAnnotations::Category("nometadata", 100), // This is too low and should not be added as a keyword despite it @@ -662,7 +667,7 @@ visits.push_back(visit3); history::AnnotatedVisit should_skip = testing::CreateDefaultAnnotatedVisit( - 11, GURL("https://shouldskip.com/whatever")); + 11, GURL("https://shouldskip.com/whatever"), base::Time::FromTimeT(11)); visits.push_back(should_skip); std::vector<history::Cluster> result_clusters = @@ -670,15 +675,28 @@ EXPECT_THAT( testing::ToVisitResults(result_clusters), ElementsAre( + ElementsAre(testing::VisitResult(3, 1.0, {}, u"nometadata")), ElementsAre(testing::VisitResult( - 2, 1.0, {testing::VisitResult(1, 0.0, {}, u"foo")}, u"foo")), - ElementsAre(testing::VisitResult(3, 1.0, {}, u"nometadata")))); + 2, 1.0, {testing::VisitResult(1, 0.0, {}, u"foo")}, u"foo")))); // Make sure visits are normalized. history::Cluster cluster = result_clusters.at(0); ASSERT_EQ(cluster.visits.size(), 1u); + // The third visit should have its original URL as the normalized URL and + // also have its entities rewritten. + history::ClusterVisit third_result_visit = cluster.visits.at(0); + EXPECT_EQ(third_result_visit.normalized_url, + GURL("http://non-default-engine.com/?q=nometadata")); + EXPECT_TRUE(third_result_visit.annotated_visit.content_annotations + .model_annotations.entities.empty()); + EXPECT_TRUE(third_result_visit.annotated_visit.content_annotations + .model_annotations.categories.empty()); + EXPECT_TRUE(cluster.keyword_to_data_map.empty()); + + history::Cluster cluster2 = result_clusters.at(1); + ASSERT_EQ(cluster2.visits.size(), 1u); // The first visit should have its original URL as the normalized URL and // also have its entities rewritten. - history::ClusterVisit better_visit = cluster.visits.at(0); + history::ClusterVisit better_visit = cluster2.visits.at(0); EXPECT_EQ(better_visit.normalized_url, GURL("http://default-engine.com/?q=foo")); std::vector<history::VisitContentModelAnnotations::Category> entities = @@ -696,31 +714,18 @@ .visibility_score, FloatEq(0.5)); // The second visit should have a normalized URL, but be the worse duplicate. - EXPECT_EQ(cluster.visits.at(0).duplicate_visits.at(0).normalized_url, + EXPECT_EQ(cluster2.visits.at(0).duplicate_visits.at(0).normalized_url, GURL("http://default-engine.com/?q=foo")); - EXPECT_THAT(cluster.visits.at(0) + EXPECT_THAT(cluster2.visits.at(0) .duplicate_visits.at(0) .annotated_visit.content_annotations.model_annotations .visibility_score, FloatEq(0.5)); // Cluster should have 3 keywords. EXPECT_THAT( - cluster.GetKeywords(), + cluster2.GetKeywords(), UnorderedElementsAre(u"rewritten-foo", u"category-foo", u"alias-foo")); - history::Cluster cluster2 = result_clusters.at(1); - ASSERT_EQ(cluster2.visits.size(), 1u); - // The third visit should have its original URL as the normalized URL and - // also have its entities rewritten. - history::ClusterVisit third_result_visit = cluster2.visits.at(0); - EXPECT_EQ(third_result_visit.normalized_url, - GURL("http://non-default-engine.com/?q=nometadata")); - EXPECT_TRUE(third_result_visit.annotated_visit.content_annotations - .model_annotations.entities.empty()); - EXPECT_TRUE(third_result_visit.annotated_visit.content_annotations - .model_annotations.categories.empty()); - EXPECT_TRUE(cluster2.keyword_to_data_map.empty()); - histogram_tester.ExpectUniqueSample( "History.Clusters.Backend.ClusterSize.Min", 1, 1); histogram_tester.ExpectUniqueSample(
diff --git a/components/media_router/common/media_source.cc b/components/media_router/common/media_source.cc index 65ccf99..285388a 100644 --- a/components/media_router/common/media_source.cc +++ b/components/media_router/common/media_source.cc
@@ -78,20 +78,6 @@ MediaSource::~MediaSource() = default; // static -MediaSource MediaSource::ForLocalFile() { - // TODO(crbug.com/1090878): Use something more sane here. Fixing this - // requires tracking down other places where tab ID 0 is used to indicate - // local file casting. - // - // This probably isn't a source of bugs in practice, because tab IDs are - // generated by SessionIdGenerator, which appears to only produce positive - // values, but that fact isn't clearly documentated, and other parts of - // Chromium don't seem to rely on it, using -1 as the canonical invalid tab - // ID. - return MediaSource(base::StringPrintf(kTabMediaUrnFormat, 0)); -} - -// static MediaSource MediaSource::ForAnyTab() { return MediaSource(std::string(kAnyTabMediaUrn)); } @@ -139,11 +125,6 @@ base::CompareCase::SENSITIVE); } -bool MediaSource::IsLocalFileSource() const { - // TODO(crbug.com/1090878): Keep this method is sync with ForLocalFile(). - return TabId() == 0; -} - bool MediaSource::IsCastPresentationUrl() const { return url_.SchemeIs(kCastPresentationUrlScheme) || IsLegacyCastPresentationUrl(url_);
diff --git a/components/media_router/common/media_source.h b/components/media_router/common/media_source.h index ec1ad73..ea28353 100644 --- a/components/media_router/common/media_source.h +++ b/components/media_router/common/media_source.h
@@ -89,7 +89,6 @@ // Protocol-specific media source object creation. // Returns MediaSource URI depending on the type of source. - static MediaSource ForLocalFile(); static MediaSource ForAnyTab(); static MediaSource ForTab(int tab_id); static MediaSource ForPresentationUrl(const GURL& presentation_url); @@ -114,9 +113,6 @@ // Returns true if source outputs its content via desktop mirroring. bool IsDesktopMirroringSource() const; - // Returns true if the source is a local file. - bool IsLocalFileSource() const; - // Returns true if this is represents a Cast Presentation URL. bool IsCastPresentationUrl() const;
diff --git a/components/media_router/common/media_source_unittest.cc b/components/media_router/common/media_source_unittest.cc index f2b8cd4..37a74f57 100644 --- a/components/media_router/common/media_source_unittest.cc +++ b/components/media_router/common/media_source_unittest.cc
@@ -60,7 +60,6 @@ EXPECT_EQ(-1, source.TabId()); EXPECT_FALSE(source.IsDesktopMirroringSource()); EXPECT_TRUE(source.IsTabMirroringSource()); - EXPECT_FALSE(source.IsLocalFileSource()); EXPECT_FALSE(source.IsCastPresentationUrl()); EXPECT_FALSE(source.IsDialSource()); } @@ -71,17 +70,6 @@ EXPECT_EQ(123, source.TabId()); EXPECT_FALSE(source.IsDesktopMirroringSource()); EXPECT_TRUE(source.IsTabMirroringSource()); - EXPECT_FALSE(source.IsLocalFileSource()); - EXPECT_FALSE(source.IsCastPresentationUrl()); - EXPECT_FALSE(source.IsDialSource()); -} - -TEST(MediaSourceTest, ForLocalFile) { - auto source = MediaSource::ForLocalFile(); - EXPECT_EQ("urn:x-org.chromium.media:source:tab:0", source.id()); - EXPECT_FALSE(source.IsDesktopMirroringSource()); - EXPECT_FALSE(source.IsTabMirroringSource()); - EXPECT_TRUE(source.IsLocalFileSource()); EXPECT_FALSE(source.IsCastPresentationUrl()); EXPECT_FALSE(source.IsDialSource()); } @@ -94,7 +82,6 @@ EXPECT_EQ(media_id, source.DesktopStreamId()); EXPECT_FALSE(source.IsDesktopSourceWithAudio()); EXPECT_FALSE(source.IsTabMirroringSource()); - EXPECT_FALSE(source.IsLocalFileSource()); EXPECT_FALSE(source.IsCastPresentationUrl()); EXPECT_FALSE(source.IsDialSource()); } @@ -109,7 +96,6 @@ EXPECT_EQ(media_id, source.DesktopStreamId()); EXPECT_TRUE(source.IsDesktopSourceWithAudio()); EXPECT_FALSE(source.IsTabMirroringSource()); - EXPECT_FALSE(source.IsLocalFileSource()); EXPECT_FALSE(source.IsCastPresentationUrl()); EXPECT_FALSE(source.IsDialSource()); } @@ -121,7 +107,6 @@ EXPECT_EQ(kPresentationUrl, source.id()); EXPECT_FALSE(source.IsDesktopMirroringSource()); EXPECT_FALSE(source.IsTabMirroringSource()); - EXPECT_FALSE(source.IsLocalFileSource()); EXPECT_FALSE(source.IsCastPresentationUrl()); EXPECT_FALSE(source.IsDialSource()); }
diff --git a/components/media_router/common/providers/cast/cast_media_source.cc b/components/media_router/common/providers/cast/cast_media_source.cc index b862ee25..76338a3 100644 --- a/components/media_router/common/providers/cast/cast_media_source.cc +++ b/components/media_router/common/providers/cast/cast_media_source.cc
@@ -423,7 +423,7 @@ // static std::unique_ptr<CastMediaSource> CastMediaSource::FromMediaSource( const MediaSource& source) { - if (source.IsTabMirroringSource() || source.IsLocalFileSource()) + if (source.IsTabMirroringSource()) return CastMediaSourceForTabMirroring(source.id()); if (source.IsDesktopMirroringSource())
diff --git a/components/omnibox/browser/history_fuzzy_provider.cc b/components/omnibox/browser/history_fuzzy_provider.cc index 5424fda..b479ede 100644 --- a/components/omnibox/browser/history_fuzzy_provider.cc +++ b/components/omnibox/browser/history_fuzzy_provider.cc
@@ -34,6 +34,7 @@ #include "components/omnibox/browser/bookmark_provider.h" #include "components/omnibox/browser/history_quick_provider.h" #include "components/omnibox/browser/omnibox_field_trial.h" +#include "components/omnibox/browser/omnibox_triggered_feature_service.h" #include "components/search_engines/omnibox_focus_type.h" #include "components/url_formatter/elide_url.h" #include "url/gurl.h" @@ -42,7 +43,7 @@ // Histogram names for measuring sub-provider match conversion efficacy. // Reminder in case other sub-providers or metrics are added: update -// the `Omnibox.FuzzyMatchConversion` entry in histograms.xml. +// the `Omnibox.HistoryFuzzy.MatchConversion` entry in histograms.xml. const char kMetricMatchConversionHistoryQuick[] = "Omnibox.HistoryFuzzy.MatchConversion.HistoryQuick"; const char kMetricMatchConversionBookmark[] = @@ -558,13 +559,19 @@ } } - // When in the counterfactual group, we do all the work of finding fuzzy - // matches, but do not provide the benefit. To reduce risk of unintended - // consequences downstream (for example showing fewer suggestions than - // normal), the matches are cleared here instead of at end of result - // processing pipeline so they won't interact or dedupe with other matches. - if (OmniboxFieldTrial::kFuzzyUrlSuggestionsCounterfactual.Get()) { - matches_.clear(); + if (!matches_.empty()) { + // This will likely produce some false positives. + client()->GetOmniboxTriggeredFeatureService()->FeatureTriggered( + OmniboxTriggeredFeatureService::Feature::kFuzzyUrlSuggestions); + + // When in the counterfactual group, we do all the work of finding fuzzy + // matches, but do not provide the benefit. To reduce risk of unintended + // consequences downstream (for example showing fewer suggestions than + // normal), the matches are cleared here instead of at end of result + // processing pipeline so they won't interact or dedupe with other matches. + if (OmniboxFieldTrial::kFuzzyUrlSuggestionsCounterfactual.Get()) { + matches_.clear(); + } } }
diff --git a/components/omnibox/browser/omnibox_triggered_feature_service.h b/components/omnibox/browser/omnibox_triggered_feature_service.h index 8a4aa63..5e34ce6 100644 --- a/components/omnibox/browser/omnibox_triggered_feature_service.h +++ b/components/omnibox/browser/omnibox_triggered_feature_service.h
@@ -21,7 +21,8 @@ kRichAutocompletion = 0, kBookmarkPaths = 1, kShortBookmarkSuggestionsByTotalInputLength = 2, - kMaxValue = kShortBookmarkSuggestionsByTotalInputLength, + kFuzzyUrlSuggestions = 3, + kMaxValue = kFuzzyUrlSuggestions, }; using Features = std::set<Feature>;
diff --git a/components/omnibox/browser/open_tab_provider.cc b/components/omnibox/browser/open_tab_provider.cc index 594c65ad..c9f83d3 100644 --- a/components/omnibox/browser/open_tab_provider.cc +++ b/components/omnibox/browser/open_tab_provider.cc
@@ -9,6 +9,7 @@ #include "base/strings/utf_string_conversions.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/omnibox/browser/autocomplete_match_classification.h" +#include "components/omnibox/browser/in_memory_url_index_types.h" #include "components/omnibox/browser/keyword_provider.h" #include "components/omnibox/browser/tab_matcher.h" @@ -37,12 +38,11 @@ #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) // Preprocess the query into lowercase terms. - std::vector<std::u16string> query_terms; - for (const std::u16string& term : - base::SplitString(base::i18n::ToLower(adjusted_input.text()), u" ", - base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { - query_terms.push_back(term); - } + const auto adjusted_input_text = std::u16string( + base::TrimWhitespace(base::i18n::ToLower(adjusted_input.text()), + base::TrimPositions::TRIM_ALL)); + std::vector<std::u16string> query_terms = + String16VectorFromString16(adjusted_input_text, nullptr); // Perform basic substring matching on the query terms. for (auto* web_contents : client_->GetTabMatcher().GetOpenTabs()) {
diff --git a/components/optimization_guide/core/entity_annotator_native_library.cc b/components/optimization_guide/core/entity_annotator_native_library.cc index 32350cb5..34f038f 100644 --- a/components/optimization_guide/core/entity_annotator_native_library.cc +++ b/components/optimization_guide/core/entity_annotator_native_library.cc
@@ -21,7 +21,7 @@ #endif // IMPORTANT: All functions in this file that call dlsym()'ed -// functions should be annotated with DISABLE_CFI_ICALL. +// functions should be annotated with DISABLE_CFI_DLSYM. namespace optimization_guide { @@ -126,7 +126,7 @@ return nullptr; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void EntityAnnotatorNativeLibrary::LoadFunctions() { get_max_supported_feature_flag_func_ = reinterpret_cast<GetMaxSupportedFeatureFlagFunc>( @@ -257,7 +257,7 @@ "OptimizationGuideEntityMetadataGetCollectionAtIndex")); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM bool EntityAnnotatorNativeLibrary::IsValid() const { return get_max_supported_feature_flag_func_ && create_from_options_func_ && get_creation_error_func_ && delete_func_ && @@ -282,7 +282,7 @@ entity_metadata_get_collection_at_index_func_; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM int32_t EntityAnnotatorNativeLibrary::GetMaxSupportedFeatureFlag() { DCHECK(IsValid()); if (!IsValid()) { @@ -292,7 +292,7 @@ return get_max_supported_feature_flag_func_(); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void* EntityAnnotatorNativeLibrary::CreateEntityAnnotator( const ModelInfo& model_info) { ScopedEntityAnnotatorCreationStatusRecorder recorder; @@ -326,7 +326,7 @@ return entity_annotator; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM bool EntityAnnotatorNativeLibrary::PopulateEntityAnnotatorOptionsFromModelInfo( void* options, const ModelInfo& model_info, @@ -429,7 +429,7 @@ return true; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void EntityAnnotatorNativeLibrary::DeleteEntityAnnotator( void* entity_annotator) { DCHECK(IsValid()); @@ -440,7 +440,7 @@ delete_func_(reinterpret_cast<void*>(entity_annotator)); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM absl::optional<std::vector<ScoredEntityMetadata>> EntityAnnotatorNativeLibrary::AnnotateText(void* annotator, const std::string& text) { @@ -471,7 +471,7 @@ return scored_md; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM absl::optional<EntityMetadata> EntityAnnotatorNativeLibrary::GetEntityMetadataForEntityId( void* annotator, @@ -497,7 +497,7 @@ return md; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM EntityMetadata EntityAnnotatorNativeLibrary:: GetEntityMetadataFromOptimizationGuideEntityMetadata( const void* og_entity_metadata) { @@ -539,4 +539,4 @@ return entity_metadata; } -} // namespace optimization_guide \ No newline at end of file +} // namespace optimization_guide
diff --git a/components/payments/content/BUILD.gn b/components/payments/content/BUILD.gn index 3d36fee..b9ecf27 100644 --- a/components/payments/content/BUILD.gn +++ b/components/payments/content/BUILD.gn
@@ -236,6 +236,8 @@ "service_worker_payment_app_unittest.cc", "test_content_payment_request_delegate.cc", "test_content_payment_request_delegate.h", + "test_payment_app.cc", + "test_payment_app.h", ] }
diff --git a/components/payments/content/payment_request_state_unittest.cc b/components/payments/content/payment_request_state_unittest.cc index 91e605b..8e8037f 100644 --- a/components/payments/content/payment_request_state_unittest.cc +++ b/components/payments/content/payment_request_state_unittest.cc
@@ -20,6 +20,7 @@ #include "components/payments/content/payment_app_service_factory.h" #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/test_content_payment_request_delegate.h" +#include "components/payments/content/test_payment_app.h" #include "components/payments/core/journey_logger.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_task_environment.h" @@ -32,49 +33,6 @@ namespace payments { namespace { -class TestApp : public PaymentApp { - public: - explicit TestApp(const std::string& method) - : PaymentApp(/*icon_resource_id=*/0, - PaymentApp::Type::SERVICE_WORKER_APP), - method_(method) {} - - TestApp(const TestApp& other) = delete; - TestApp& operator=(const TestApp& other) = delete; - - // PaymentApp: - void InvokePaymentApp(base::WeakPtr<Delegate> delegate) override {} - bool IsCompleteForPayment() const override { return true; } - uint32_t GetCompletenessScore() const override { return 0; } - bool CanPreselect() const override { return true; } - std::u16string GetMissingInfoLabel() const override { - return std::u16string(); - } - bool HasEnrolledInstrument() const override { return true; } - void RecordUse() override {} - bool NeedsInstallation() const override { return false; } - std::string GetId() const override { return method_; } - std::u16string GetLabel() const override { return std::u16string(); } - std::u16string GetSublabel() const override { return std::u16string(); } - bool IsValidForModifier( - const std::string& method, - bool supported_networks_specified, - const std::set<std::string>& supported_networks) const override { - return false; - } - base::WeakPtr<PaymentApp> AsWeakPtr() override { - return weak_ptr_factory_.GetWeakPtr(); - } - bool HandlesShippingAddress() const override { return false; } - bool HandlesPayerName() const override { return false; } - bool HandlesPayerEmail() const override { return false; } - bool HandlesPayerPhone() const override { return false; } - - private: - const std::string method_; - base::WeakPtrFactory<TestApp> weak_ptr_factory_{this}; -}; - class TestAppFactory : public PaymentAppFactory { public: explicit TestAppFactory(const std::string& method) @@ -88,7 +46,7 @@ auto requested_methods = delegate->GetSpec()->payment_method_identifiers_set(); if (requested_methods.find(method_) != requested_methods.end()) - delegate->OnPaymentAppCreated(std::make_unique<TestApp>(method_)); + delegate->OnPaymentAppCreated(std::make_unique<TestPaymentApp>(method_)); delegate->OnDoneCreatingPaymentApps(); }
diff --git a/components/payments/content/payment_response_helper_unittest.cc b/components/payments/content/payment_response_helper_unittest.cc index 7f3d799..bc059d9 100644 --- a/components/payments/content/payment_response_helper_unittest.cc +++ b/components/payments/content/payment_response_helper_unittest.cc
@@ -10,18 +10,14 @@ #include <vector> #include "base/memory/weak_ptr.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_executor.h" -#include "base/test/scoped_feature_list.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" -#include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" -#include "components/payments/content/autofill_payment_app.h" #include "components/payments/content/payment_request_spec.h" +#include "components/payments/content/test_payment_app.h" #include "components/payments/core/test_payment_request_delegate.h" -#include "content/public/common/content_features.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom.h" @@ -34,17 +30,9 @@ : test_payment_request_delegate_( std::make_unique<base::SingleThreadTaskExecutor>(), &test_personal_data_manager_), - address_(autofill::test::GetFullProfile()), - billing_addresses_({&address_}) { + address_(autofill::test::GetFullProfile()) { test_personal_data_manager_.AddProfile(address_); - - // Set up the autofill payment app. - visa_card_ = autofill::test::GetCreditCard(); - visa_card_.set_billing_address_id(address_.guid()); - visa_card_.set_use_count(5u); - autofill_app_ = std::make_unique<AutofillPaymentApp>( - "visa", visa_card_, billing_addresses_, "en-US", - test_payment_request_delegate_.GetWeakPtr()); + test_app_ = std::make_unique<TestPaymentApp>("method-name"); } ~PaymentResponseHelperTest() override {} @@ -96,8 +84,7 @@ base::WeakPtr<PaymentRequestSpec> spec() { return spec_->AsWeakPtr(); } const mojom::PaymentResponsePtr& response() { return payment_response_; } autofill::AutofillProfile* test_address() { return &address_; } - const autofill::CreditCard& test_credit_card() { return visa_card_; } - base::WeakPtr<PaymentApp> test_app() { return autofill_app_->AsWeakPtr(); } + base::WeakPtr<PaymentApp> test_app() { return test_app_->AsWeakPtr(); } base::WeakPtr<PaymentRequestDelegate> test_payment_request_delegate() { return test_payment_request_delegate_.GetWeakPtr(); } @@ -114,9 +101,7 @@ // Test data. autofill::AutofillProfile address_; - autofill::CreditCard visa_card_; - const std::vector<autofill::AutofillProfile*> billing_addresses_; - std::unique_ptr<AutofillPaymentApp> autofill_app_; + std::unique_ptr<PaymentApp> test_app_; base::WeakPtrFactory<PaymentResponseHelperTest> weak_ptr_factory_{this}; }; @@ -126,35 +111,11 @@ // Default options (no shipping, no contact info). RecreateSpecWithOptions(mojom::PaymentOptions::New()); - // "visa" is specified directly in the supportedMethods so it is returned - // as the method name. PaymentResponseHelper helper("en-US", spec(), test_app(), test_payment_request_delegate(), test_address(), test_address(), GetWeakPtr()); - EXPECT_EQ("visa", response()->method_name); - EXPECT_EQ( - base::StringPrintf( - "{\"billingAddress\":" - "{\"addressLine\":[\"666 Erebus St.\",\"Apt 8\"]," - "\"city\":\"Elysium\"," - "\"country\":\"US\"," - "\"dependentLocality\":\"\"," - "\"organization\":\"Underworld\"," - "\"phone\":\"16502111111\"," - "\"postalCode\":\"91111\"," - "\"recipient\":\"John H. Doe\"," - "\"region\":\"CA\"," - "\"sortingCode\":\"\"}," - "\"cardNumber\":\"4111111111111111\"," - "\"cardSecurityCode\":\"123\"," - "\"cardholderName\":\"Test User\"," - "\"expiryMonth\":\"%s\"," - "\"expiryYear\":\"%s\"}", - base::UTF16ToUTF8(test_credit_card().Expiration2DigitMonthAsString()) - .c_str(), - base::UTF16ToUTF8(test_credit_card().Expiration4DigitYearAsString()) - .c_str()), - response()->stringified_details); + EXPECT_EQ("method-name", response()->method_name); + EXPECT_EQ("{\"data\":\"details\"}", response()->stringified_details); } // Tests the the generated PaymentResponse has the correct values for the @@ -267,65 +228,4 @@ EXPECT_EQ("5151231234", response()->payer->phone.value()); } -class PaymentResponseHelperBasicCardEnabledTest - : public PaymentResponseHelperTest { - public: - PaymentResponseHelperBasicCardEnabledTest( - const PaymentResponseHelperBasicCardEnabledTest&) = delete; - PaymentResponseHelperBasicCardEnabledTest& operator=( - const PaymentResponseHelperBasicCardEnabledTest&) = delete; - - protected: - PaymentResponseHelperBasicCardEnabledTest() { - feature_list_.InitAndEnableFeature(::features::kPaymentRequestBasicCard); - } - - private: - base::test::ScopedFeatureList feature_list_; -}; - -// Test generating a PaymentResponse when the method is specified through -// "basic-card". -TEST_F(PaymentResponseHelperBasicCardEnabledTest, - GeneratePaymentResponse_BasicCard) { - // The method data supports visa through basic-card. - mojom::PaymentMethodDataPtr entry = mojom::PaymentMethodData::New(); - entry->supported_method = "basic-card"; - entry->supported_networks.push_back(mojom::BasicCardNetwork::VISA); - std::vector<mojom::PaymentMethodDataPtr> method_data; - method_data.push_back(std::move(entry)); - RecreateSpecWithOptionsAndDetails(mojom::PaymentOptions::New(), - mojom::PaymentDetails::New(), - std::move(method_data)); - - // "basic-card" is specified so it is returned as the method name. - PaymentResponseHelper helper("en-US", spec(), test_app(), - test_payment_request_delegate(), test_address(), - test_address(), GetWeakPtr()); - EXPECT_EQ("basic-card", response()->method_name); - EXPECT_EQ( - base::StringPrintf( - "{\"billingAddress\":" - "{\"addressLine\":[\"666 Erebus St.\",\"Apt 8\"]," - "\"city\":\"Elysium\"," - "\"country\":\"US\"," - "\"dependentLocality\":\"\"," - "\"organization\":\"Underworld\"," - "\"phone\":\"16502111111\"," - "\"postalCode\":\"91111\"," - "\"recipient\":\"John H. Doe\"," - "\"region\":\"CA\"," - "\"sortingCode\":\"\"}," - "\"cardNumber\":\"4111111111111111\"," - "\"cardSecurityCode\":\"123\"," - "\"cardholderName\":\"Test User\"," - "\"expiryMonth\":\"%s\"," - "\"expiryYear\":\"%s\"}", - base::UTF16ToUTF8(test_credit_card().Expiration2DigitMonthAsString()) - .c_str(), - base::UTF16ToUTF8(test_credit_card().Expiration4DigitYearAsString()) - .c_str()), - response()->stringified_details); -} - } // namespace payments
diff --git a/components/payments/content/test_payment_app.cc b/components/payments/content/test_payment_app.cc new file mode 100644 index 0000000..76b0d00 --- /dev/null +++ b/components/payments/content/test_payment_app.cc
@@ -0,0 +1,71 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/payments/content/test_payment_app.h" + +namespace payments { + +TestPaymentApp::TestPaymentApp(const std::string& method) + : PaymentApp(/*icon_resource_id=*/0, PaymentApp::Type::SERVICE_WORKER_APP), + method_(method) {} + +TestPaymentApp::~TestPaymentApp() {} + +void TestPaymentApp::InvokePaymentApp( + base::WeakPtr<PaymentApp::Delegate> delegate) { + const std::string stringified_details = "{\"data\":\"details\"}"; + delegate->OnInstrumentDetailsReady(method_, stringified_details, PayerData()); +} + +bool TestPaymentApp::IsCompleteForPayment() const { + return true; +} +uint32_t TestPaymentApp::GetCompletenessScore() const { + return 0; +} +bool TestPaymentApp::CanPreselect() const { + return true; +} +std::u16string TestPaymentApp::GetMissingInfoLabel() const { + return std::u16string(); +} +bool TestPaymentApp::HasEnrolledInstrument() const { + return true; +} +void TestPaymentApp::RecordUse() {} +bool TestPaymentApp::NeedsInstallation() const { + return false; +} +std::string TestPaymentApp::GetId() const { + return method_; +} +std::u16string TestPaymentApp::GetLabel() const { + return std::u16string(); +} +std::u16string TestPaymentApp::GetSublabel() const { + return std::u16string(); +} +bool TestPaymentApp::IsValidForModifier( + const std::string& method, + bool supported_networks_specified, + const std::set<std::string>& supported_networks) const { + return false; +} +base::WeakPtr<PaymentApp> TestPaymentApp::AsWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} +bool TestPaymentApp::HandlesShippingAddress() const { + return false; +} +bool TestPaymentApp::HandlesPayerName() const { + return false; +} +bool TestPaymentApp::HandlesPayerEmail() const { + return false; +} +bool TestPaymentApp::HandlesPayerPhone() const { + return false; +} + +} // namespace payments
diff --git a/components/payments/content/test_payment_app.h b/components/payments/content/test_payment_app.h new file mode 100644 index 0000000..ebba93f --- /dev/null +++ b/components/payments/content/test_payment_app.h
@@ -0,0 +1,51 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PAYMENTS_CONTENT_TEST_PAYMENT_APP_H_ +#define COMPONENTS_PAYMENTS_CONTENT_TEST_PAYMENT_APP_H_ + +#include "base/memory/weak_ptr.h" +#include "components/payments/content/payment_app.h" + +namespace payments { + +// A fake PaymentApp for use in unittests. +class TestPaymentApp : public PaymentApp { + public: + explicit TestPaymentApp(const std::string& method); + ~TestPaymentApp() override; + + TestPaymentApp(const TestPaymentApp& other) = delete; + TestPaymentApp& operator=(const TestPaymentApp& other) = delete; + + // PaymentApp: + void InvokePaymentApp(base::WeakPtr<Delegate> delegate) override; + bool IsCompleteForPayment() const override; + uint32_t GetCompletenessScore() const override; + bool CanPreselect() const override; + std::u16string GetMissingInfoLabel() const override; + bool HasEnrolledInstrument() const override; + void RecordUse() override; + bool NeedsInstallation() const override; + std::string GetId() const override; + std::u16string GetLabel() const override; + std::u16string GetSublabel() const override; + bool IsValidForModifier( + const std::string& method, + bool supported_networks_specified, + const std::set<std::string>& supported_networks) const override; + base::WeakPtr<PaymentApp> AsWeakPtr() override; + bool HandlesShippingAddress() const override; + bool HandlesPayerName() const override; + bool HandlesPayerEmail() const override; + bool HandlesPayerPhone() const override; + + private: + const std::string method_; + base::WeakPtrFactory<TestPaymentApp> weak_ptr_factory_{this}; +}; + +} // namespace payments + +#endif // COMPONENTS_PAYMENTS_CONTENT_TEST_PAYMENT_APP_H_
diff --git a/components/policy/core/browser/policy_conversions_client.cc b/components/policy/core/browser/policy_conversions_client.cc index 0af84154..3c609a73 100644 --- a/components/policy/core/browser/policy_conversions_client.cc +++ b/components/policy/core/browser/policy_conversions_client.cc
@@ -147,6 +147,7 @@ base::Value::List PolicyConversionsClient::GetPrecedenceOrder() { DCHECK(HasUserPolicies()); +#if !BUILDFLAG(IS_CHROMEOS) PolicyNamespace policy_namespace = PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()); const PolicyMap& chrome_policies = @@ -194,6 +195,12 @@ IDS_POLICY_PRECEDENCE_CLOUD_USER}; } } +#else + std::vector<int> precedence_order{IDS_POLICY_PRECEDENCE_PLATFORM_MACHINE, + IDS_POLICY_PRECEDENCE_CLOUD_MACHINE, + IDS_POLICY_PRECEDENCE_PLATFORM_USER, + IDS_POLICY_PRECEDENCE_CLOUD_USER}; +#endif // !BUILDFLAG(IS_CHROMEOS) base::Value::List precedence_order_localized; for (int label_id : precedence_order) {
diff --git a/components/policy/core/common/policy_map.cc b/components/policy/core/common/policy_map.cc index df79bf0f..1a508fe2 100644 --- a/components/policy/core/common/policy_map.cc +++ b/components/policy/core/common/policy_map.cc
@@ -13,6 +13,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "components/policy/core/common/cloud/affiliation.h" #include "components/policy/core/common/policy_merger.h" #include "components/policy/policy_constants.h" @@ -492,6 +493,7 @@ SetDeviceAffiliationIds( CombineIds(GetDeviceAffiliationIds(), other.GetDeviceAffiliationIds())); +#if !BUILDFLAG(IS_CHROMEOS) // Precedence metapolicies are merged before all other policies, including // merging metapolicies, because their value affects policy overriding. for (auto* policy : metapolicy::kPrecedence) { @@ -501,8 +503,10 @@ } UpdateStoredComputedMetapolicies(); +#endif for (const auto& policy_and_entry : other) { +#if !BUILDFLAG(IS_CHROMEOS) // Skip precedence metapolicies since they have already been merged into the // current PolicyMap. if (std::find(std::begin(metapolicy::kPrecedence), @@ -510,6 +514,7 @@ std::end(metapolicy::kPrecedence)) { continue; } +#endif // External factors, such as the values of metapolicies, are considered. MergePolicy(policy_and_entry.first, other, false); @@ -638,6 +643,7 @@ return device_affiliation_ids_; } +#if !BUILDFLAG(IS_CHROMEOS) void PolicyMap::UpdateStoredComputedMetapolicies() { cloud_policy_overrides_platform_policy_ = GetValue(key::kCloudPolicyOverridesPlatformPolicy, @@ -653,6 +659,7 @@ base::Value::Type::BOOLEAN) ->GetBool(); } +#endif void PolicyMap::UpdateStoredUserAffiliation() { is_user_affiliated_ =
diff --git a/components/policy/core/common/policy_map.h b/components/policy/core/common/policy_map.h index e11b2ba5..a42928fc 100644 --- a/components/policy/core/common/policy_map.h +++ b/components/policy/core/common/policy_map.h
@@ -351,8 +351,10 @@ const base::RepeatingCallback<bool(const const_iterator)>& filter, bool deletion_value); +#if !BUILDFLAG(IS_CHROMEOS) // Updates the stored state of computed metapolicies. void UpdateStoredComputedMetapolicies(); +#endif // Updates the stored state of user affiliation. void UpdateStoredUserAffiliation();
diff --git a/components/policy/core/common/policy_map_unittest.cc b/components/policy/core/common/policy_map_unittest.cc index 3e419456..c5d1c9a4 100644 --- a/components/policy/core/common/policy_map_unittest.cc +++ b/components/policy/core/common/policy_map_unittest.cc
@@ -1276,6 +1276,7 @@ EXPECT_TRUE(policies.IsUserAffiliated()); } +#if !BUILDFLAG(IS_CHROMEOS) class PolicyMapMergeTest : public PolicyMapTestBase, public testing::TestWithParam< @@ -1674,7 +1675,6 @@ testing::Values(false, true), testing::Values(false, true))); -#if !BUILDFLAG(IS_CHROMEOS) class PolicyMapPriorityTest : public testing::TestWithParam< std::tuple</*cloud_policy_overrides_platform_policy=*/bool,
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index dbeb48c2..dcd38f314 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -66,9 +66,10 @@ void DowngradeMetricsReportingToRecommendedPolicy(PolicyMap* policies) { // Capture both the Chrome-only and device-level policies on Chrome OS. const std::vector<const char*> metrics_keys = { - policy::key::kMetricsReportingEnabled, #if BUILDFLAG(IS_CHROMEOS) policy::key::kDeviceMetricsReportingEnabled, +#else + policy::key::kMetricsReportingEnabled, #endif }; for (const char* policy_key : metrics_keys) {
diff --git a/components/policy/tools/generate_policy_source.py b/components/policy/tools/generate_policy_source.py index 7fb456b..036dcf8 100755 --- a/components/policy/tools/generate_policy_source.py +++ b/components/policy/tools/generate_policy_source.py
@@ -504,7 +504,7 @@ # Ensure only windows supported policies are returned when building for windows. # Eventually only supported policies on every platforms will be returned. def _GetSupportedPolicies(policies, target_platform): - if target_platform in ['win', 'linux', 'mac', 'ios', 'android']: + if target_platform in ['win', 'linux', 'mac', 'ios', 'android', 'chrome_os']: return [policy for policy in policies if policy.is_supported] return [
diff --git a/components/reporting/README.md b/components/reporting/README.md index fdaf0f6d..d0a577f 100644 --- a/components/reporting/README.md +++ b/components/reporting/README.md
@@ -14,3 +14,18 @@ If you'd like to begin using ERP within Chrome please check the comment in [//components/reporting/client/report_queue_provider.h](https:://chromium.googlesource.com/chromium/src/+/master/components/reporting/client/report_queue_provider.h#25). + +### Run Unit Tests + +To run the unit tests for this directory, after having configured Chromium's +build environment: + +1. Run `autoninja -C out/Default components_unittests` to build the components + unit test executable. + +1. Then, run `out/Default/components_unittests --gtest_filter='<target tests>'` to + run relevant tests. Here, `<target tests>` is a wildcard pattern (refer to + the document of gtest for more details). For example, to run all tests for + `StorageQueue`, run + + $ out/Default/components_unittests --gtest_filter='*/StorageQueueTest.*'
diff --git a/components/services/app_service/public/cpp/app_registry_cache.cc b/components/services/app_service/public/cpp/app_registry_cache.cc index 705930d..291bc30 100644 --- a/components/services/app_service/public/cpp/app_registry_cache.cc +++ b/components/services/app_service/public/cpp/app_registry_cache.cc
@@ -4,11 +4,10 @@ #include "components/services/app_service/public/cpp/app_registry_cache.h" +#include <utility> + #include "base/containers/contains.h" #include "base/observer_list.h" -#include "components/services/app_service/public/cpp/features.h" - -#include <utility> namespace apps { @@ -143,28 +142,6 @@ } } - if (!base::FeatureList::IsEnabled(kAppServiceOnAppUpdateWithoutMojom)) { - // The remaining for loops range over the mojom_deltas_in_progress_ map, not - // the deltas vector, so that OnAppUpdate is called only once per unique - // app_id. - - // Notify the observers for every de-duplicated delta. - for (const auto& d_iter : mojom_deltas_in_progress_) { - // Do not update subscribers for removed apps. - if (d_iter.second->readiness == mojom::Readiness::kRemoved) { - continue; - } - auto s_iter = mojom_states_.find(d_iter.first); - apps::mojom::App* state = - (s_iter != mojom_states_.end()) ? s_iter->second.get() : nullptr; - apps::mojom::App* delta = d_iter.second; - - for (auto& obs : observers_) { - obs.OnAppUpdate(AppUpdate(state, delta, account_id_)); - } - } - } - // Update the states for every de-duplicated delta. for (const auto& d_iter : mojom_deltas_in_progress_) { auto s_iter = mojom_states_.find(d_iter.first); @@ -229,24 +206,22 @@ } } - if (base::FeatureList::IsEnabled(kAppServiceOnAppUpdateWithoutMojom)) { - // The remaining for loops range over the deltas_in_progress_ map, not - // the deltas vector, so that OnAppUpdate is called only once per unique - // app_id. + // The remaining for loops range over the deltas_in_progress_ map, not + // the deltas vector, so that OnAppUpdate is called only once per unique + // app_id. - // Notify the observers for every de-duplicated delta. - for (const auto& d_iter : deltas_in_progress_) { - // Do not update subscribers for removed apps. - if (d_iter.second->readiness == Readiness::kRemoved) { - continue; - } - auto s_iter = states_.find(d_iter.first); - App* state = (s_iter != states_.end()) ? s_iter->second.get() : nullptr; - App* delta = d_iter.second; + // Notify the observers for every de-duplicated delta. + for (const auto& d_iter : deltas_in_progress_) { + // Do not update subscribers for removed apps. + if (d_iter.second->readiness == Readiness::kRemoved) { + continue; + } + auto s_iter = states_.find(d_iter.first); + App* state = (s_iter != states_.end()) ? s_iter->second.get() : nullptr; + App* delta = d_iter.second; - for (auto& obs : observers_) { - obs.OnAppUpdate(AppUpdate(state, delta, account_id_)); - } + for (auto& obs : observers_) { + obs.OnAppUpdate(AppUpdate(state, delta, account_id_)); } } @@ -274,27 +249,13 @@ AppType AppRegistryCache::GetAppType(const std::string& app_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_); - if (base::FeatureList::IsEnabled(kAppServiceOnAppUpdateWithoutMojom)) { - auto d_iter = deltas_in_progress_.find(app_id); - if (d_iter != deltas_in_progress_.end()) { - return d_iter->second->app_type; - } - auto s_iter = states_.find(app_id); - if (s_iter != states_.end()) { - return s_iter->second->app_type; - } - return AppType::kUnknown; + auto d_iter = deltas_in_progress_.find(app_id); + if (d_iter != deltas_in_progress_.end()) { + return d_iter->second->app_type; } - - auto d_iter = mojom_deltas_in_progress_.find(app_id); - if (d_iter != mojom_deltas_in_progress_.end()) { - return ConvertMojomAppTypToAppType(d_iter->second->app_type); - } - auto s_iter = mojom_states_.find(app_id); - if (s_iter != mojom_states_.end()) { - return ConvertMojomAppTypToAppType(s_iter->second->app_type); - } - return AppType::kUnknown; + auto s_iter = states_.find(app_id); + return (s_iter != states_.end()) ? s_iter->second->app_type + : AppType::kUnknown; } std::vector<AppPtr> AppRegistryCache::GetAllApps() {
diff --git a/components/services/app_service/public/cpp/app_registry_cache.h b/components/services/app_service/public/cpp/app_registry_cache.h index f0e84427..921379ee 100644 --- a/components/services/app_service/public/cpp/app_registry_cache.h +++ b/components/services/app_service/public/cpp/app_registry_cache.h
@@ -19,7 +19,6 @@ #include "components/account_id/account_id.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/app_update.h" -#include "components/services/app_service/public/cpp/features.h" namespace apps { @@ -143,38 +142,6 @@ void ForEachApp(FunctionType f) { DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_); - if (base::FeatureList::IsEnabled(kAppServiceOnAppUpdateWithoutMojom)) { - ForAllApps(std::move(f)); - return; - } - - for (const auto& s_iter : mojom_states_) { - const apps::mojom::App* state = s_iter.second.get(); - - auto d_iter = mojom_deltas_in_progress_.find(s_iter.first); - const apps::mojom::App* delta = - (d_iter != mojom_deltas_in_progress_.end()) ? d_iter->second - : nullptr; - - f(apps::AppUpdate(state, delta, account_id_)); - } - - for (const auto& d_iter : mojom_deltas_in_progress_) { - const apps::mojom::App* delta = d_iter.second; - - auto s_iter = mojom_states_.find(d_iter.first); - if (s_iter != mojom_states_.end()) { - continue; - } - - f(apps::AppUpdate(nullptr, delta, account_id_)); - } - } - - template <typename FunctionType> - void ForAllApps(FunctionType f) { - DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_); - for (const auto& s_iter : states_) { const App* state = s_iter.second.get(); @@ -208,29 +175,6 @@ bool ForOneApp(const std::string& app_id, FunctionType f) { DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_); - if (base::FeatureList::IsEnabled(kAppServiceOnAppUpdateWithoutMojom)) { - return ForApp(app_id, std::move(f)); - } - - auto s_iter = mojom_states_.find(app_id); - const apps::mojom::App* state = - (s_iter != mojom_states_.end()) ? s_iter->second.get() : nullptr; - - auto d_iter = mojom_deltas_in_progress_.find(app_id); - const apps::mojom::App* delta = - (d_iter != mojom_deltas_in_progress_.end()) ? d_iter->second : nullptr; - - if (state || delta) { - f(apps::AppUpdate(state, delta, account_id_)); - return true; - } - return false; - } - - template <typename FunctionType> - bool ForApp(const std::string& app_id, FunctionType f) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_); - auto s_iter = states_.find(app_id); const App* state = (s_iter != states_.end()) ? s_iter->second.get() : nullptr;
diff --git a/components/services/app_service/public/cpp/app_registry_cache_unittest.cc b/components/services/app_service/public/cpp/app_registry_cache_unittest.cc index 4df6c00..dbf648889 100644 --- a/components/services/app_service/public/cpp/app_registry_cache_unittest.cc +++ b/components/services/app_service/public/cpp/app_registry_cache_unittest.cc
@@ -137,7 +137,7 @@ void OnAppUpdate(const AppUpdate& outer) override { EXPECT_EQ(account_id_, outer.AccountId()); int num_apps = 0; - cache_->ForAllApps([this, &outer, &num_apps](const AppUpdate& inner) { + cache_->ForEachApp([this, &outer, &num_apps](const AppUpdate& inner) { if (check_names_snapshot_) { if (num_apps_seen_on_app_update_ == 0) { // If this is the first time that OnAppUpdate is called, after a @@ -164,13 +164,13 @@ }); EXPECT_EQ(expected_num_apps_, num_apps); - EXPECT_FALSE(cache_->ForApp( + EXPECT_FALSE(cache_->ForOneApp( "no_such_app_id", [&outer](const AppUpdate& inner) { ExpectEq(outer, inner); })); - EXPECT_TRUE(cache_->ForApp(outer.AppId(), [&outer](const AppUpdate& inner) { - ExpectEq(outer, inner); - })); + EXPECT_TRUE(cache_->ForOneApp( + outer.AppId(), + [&outer](const AppUpdate& inner) { ExpectEq(outer, inner); })); if (outer.NameChanged()) { std::string old_name; @@ -312,8 +312,8 @@ public testing::WithParamInterface<bool>, public AppRegistryCache::Observer { public: - void CallForAllApps(AppRegistryCache& cache) { - cache.ForAllApps([this](const AppUpdate& update) { OnAppUpdate(update); }); + void CallForEachApp(AppRegistryCache& cache) { + cache.ForEachApp([this](const AppUpdate& update) { OnAppUpdate(update); }); } // apps::AppRegistryCache::Observer overrides. @@ -354,8 +354,8 @@ std::string GetName(AppRegistryCache& cache, const std::string& app_id) { std::string name; - cache.ForApp(app_id, - [&name](const AppUpdate& update) { name = update.Name(); }); + cache.ForOneApp(app_id, + [&name](const AppUpdate& update) { name = update.Name(); }); return name; } @@ -426,7 +426,7 @@ VerifyApp(cache, "c", "cherry", Readiness::kDisabledByPolicy, /*timeline=*/10); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(2u, updated_ids_.size()); EXPECT_EQ(2u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("b")); @@ -462,7 +462,7 @@ /*timeline=*/10); VerifyApp(cache, "d", "durian"); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(3u, updated_ids_.size()); EXPECT_EQ(3u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("a")); @@ -479,14 +479,14 @@ // Test that ForOneApp succeeds for "c" and fails for "e". bool found_c = false; - EXPECT_TRUE(cache.ForApp("c", [&found_c](const apps::AppUpdate& update) { + EXPECT_TRUE(cache.ForOneApp("c", [&found_c](const apps::AppUpdate& update) { found_c = true; EXPECT_EQ("c", update.AppId()); })); EXPECT_TRUE(found_c); bool found_e = false; - EXPECT_FALSE(cache.ForApp("e", [&found_e](const apps::AppUpdate& update) { + EXPECT_FALSE(cache.ForOneApp("e", [&found_e](const apps::AppUpdate& update) { found_e = true; EXPECT_EQ("e", update.AppId()); })); @@ -500,7 +500,7 @@ cache.AddObserver(&observer); // Starting with an empty cache. - cache.ForAllApps([&observer](const apps::AppUpdate& update) { + cache.ForEachApp([&observer](const apps::AppUpdate& update) { observer.OnAppUpdate(update); }); @@ -518,7 +518,7 @@ cache.OnApps(std::move(mojom_apps), apps::mojom::AppType::kUnknown, false /* should_notify_initialized */); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(1u, updated_ids_.size()); EXPECT_EQ(1u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("app")); @@ -549,7 +549,7 @@ // Even though we have queued the removal, checking the cache now // shows the app is still present. EXPECT_CALL(observer, OnAppUpdate(HasAppId("app"))); - cache.ForAllApps([&observer](const AppUpdate& update) { + cache.ForEachApp([&observer](const AppUpdate& update) { observer.OnAppUpdate(update); }); })); @@ -562,7 +562,7 @@ // The cache is now empty. EXPECT_EQ(0, AppCount(cache)); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_TRUE(updated_ids_.empty()); EXPECT_TRUE(updated_names_.empty()); Clear(); @@ -589,7 +589,7 @@ false /* should_notify_initialized */); // Verify "app" is notified via OnAppUpdate. - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(1u, updated_ids_.size()); EXPECT_EQ(1u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("app")); @@ -627,7 +627,7 @@ // The cache is not empty, "app" is still saved in the cache. EXPECT_EQ(1, AppCount(cache)); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(1u, updated_ids_.size()); EXPECT_EQ(1u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("app")); @@ -663,7 +663,7 @@ false /* should_notify_initialized */); // Verify "app1" is added to the cache and is notified via OnAppUpdate. - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(1u, updated_ids_.size()); EXPECT_EQ(1u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("app1")); @@ -707,7 +707,7 @@ // The cache is not empty. Verify both "app1" and "app2" exist in the cache. EXPECT_EQ(2, AppCount(cache)); - CallForAllApps(cache); + CallForEachApp(cache); EXPECT_EQ(2u, updated_ids_.size()); EXPECT_EQ(2u, updated_names_.size()); EXPECT_NE(updated_ids_.end(), updated_ids_.find("app1"));
diff --git a/components/services/app_service/public/cpp/features.cc b/components/services/app_service/public/cpp/features.cc index d8e9dde7..a645228 100644 --- a/components/services/app_service/public/cpp/features.cc +++ b/components/services/app_service/public/cpp/features.cc
@@ -6,9 +6,6 @@ namespace apps { -const base::Feature kAppServiceOnAppUpdateWithoutMojom{ - "AppServiceOnAppUpdateWithoutMojom", base::FEATURE_ENABLED_BY_DEFAULT}; - const base::Feature kAppServicePreferredAppsWithoutMojom{ "AppServicePreferredAppsWithoutMojom", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/components/services/app_service/public/cpp/features.h b/components/services/app_service/public/cpp/features.h index f802921..32bae59 100644 --- a/components/services/app_service/public/cpp/features.h +++ b/components/services/app_service/public/cpp/features.h
@@ -11,8 +11,6 @@ namespace apps { COMPONENT_EXPORT(APP_TYPES) -extern const base::Feature kAppServiceOnAppUpdateWithoutMojom; -COMPONENT_EXPORT(APP_TYPES) extern const base::Feature kAppServicePreferredAppsWithoutMojom; COMPONENT_EXPORT(APP_TYPES) extern const base::Feature kAppServiceLaunchWithoutMojom;
diff --git a/components/ui_devtools/views/view_element_unittest.cc b/components/ui_devtools/views/view_element_unittest.cc index c5a2032..11c8521 100644 --- a/components/ui_devtools/views/view_element_unittest.cc +++ b/components/ui_devtools/views/view_element_unittest.cc
@@ -114,7 +114,7 @@ // views::ViewObserver void OnChildViewAdded(View* observed_view, View* child) override { - ReorderChildView(always_on_top_view_, -1); + ReorderChildView(always_on_top_view_, children().size()); } private:
diff --git a/components/user_notes/browser/user_note_service.cc b/components/user_notes/browser/user_note_service.cc index 06866887..015ef7f2 100644 --- a/components/user_notes/browser/user_note_service.cc +++ b/components/user_notes/browser/user_note_service.cc
@@ -69,10 +69,11 @@ DCHECK(UserNoteManager::GetForPage(rfh->GetPage())); std::vector<content::RenderFrameHost*> frames = {rfh}; - std::vector<GURL> urls = {rfh->GetLastCommittedURL()}; + UserNoteStorage::UrlSet urls = {rfh->GetLastCommittedURL()}; storage_->GetNoteMetadataForUrls( - urls, base::BindOnce(&UserNoteService::OnNoteMetadataFetchedForNavigation, - weak_ptr_factory_.GetWeakPtr(), frames, rfh)); + std::move(urls), + base::BindOnce(&UserNoteService::OnNoteMetadataFetchedForNavigation, + weak_ptr_factory_.GetWeakPtr(), frames, rfh)); } void UserNoteService::OnNoteInstanceAddedToPage( @@ -257,15 +258,16 @@ void UserNoteService::OnNotesChanged() { std::vector<content::RenderFrameHost*> all_frames = delegate_->GetAllFramesForUserNotes(); - std::vector<GURL> urls; + UserNoteStorage::UrlSet urls; for (content::RenderFrameHost* frame : all_frames) { - urls.emplace_back(frame->GetLastCommittedURL()); + urls.emplace(frame->GetLastCommittedURL()); } storage_->GetNoteMetadataForUrls( - urls, base::BindOnce(&UserNoteService::OnNoteMetadataFetched, - weak_ptr_factory_.GetWeakPtr(), all_frames)); + std::move(urls), + base::BindOnce(&UserNoteService::OnNoteMetadataFetched, + weak_ptr_factory_.GetWeakPtr(), all_frames)); } void UserNoteService::InitializeNewNoteForCreation( @@ -421,24 +423,24 @@ // All added and modified notes must be fetched from storage to eventually be // put in the model map. For removed notes there is no need to update the // model map at this point; it will be done later when applying the changes. - std::vector<base::UnguessableToken> notes_to_fetch; - std::unordered_set<base::UnguessableToken, base::UnguessableTokenHash> - new_notes; + IdSet notes_to_fetch; + IdSet new_notes; for (const std::unique_ptr<FrameUserNoteChanges>& diff : note_changes) { for (const base::UnguessableToken& note_id : diff->notes_added()) { - notes_to_fetch.emplace_back(note_id); + notes_to_fetch.emplace(note_id); new_notes.emplace(note_id); } for (const base::UnguessableToken& note_id : diff->notes_modified()) { - notes_to_fetch.emplace_back(note_id); + notes_to_fetch.emplace(note_id); } } storage_->GetNotesById( - notes_to_fetch, base::BindOnce(&UserNoteService::OnNoteModelsFetched, - weak_ptr_factory_.GetWeakPtr(), new_notes, - std::move(note_changes))); + std::move(notes_to_fetch), + base::BindOnce(&UserNoteService::OnNoteModelsFetched, + weak_ptr_factory_.GetWeakPtr(), std::move(new_notes), + std::move(note_changes))); } void UserNoteService::OnNoteModelsFetched(
diff --git a/components/user_notes/browser/user_note_service_unittest.cc b/components/user_notes/browser/user_note_service_unittest.cc index 7ba1bca..2ba12d5 100644 --- a/components/user_notes/browser/user_note_service_unittest.cc +++ b/components/user_notes/browser/user_note_service_unittest.cc
@@ -61,13 +61,13 @@ public: MOCK_METHOD(void, GetNoteMetadataForUrls, - (const std::vector<GURL>& urls, + (const UserNoteStorage::UrlSet& urls, base::OnceCallback<void(UserNoteMetadataSnapshot)> callback), (override)); MOCK_METHOD(void, GetNotesById, - (const IdList& ids, + (const UserNoteStorage::IdSet& ids, base::OnceCallback<void(std::vector<std::unique_ptr<UserNote>>)> callback), (override)); @@ -98,20 +98,22 @@ MOCK_METHOD(void, AddObserver, (Observer * observer), (override)); MOCK_METHOD(void, RemoveObserver, (Observer * observer), (override)); - const std::vector<GURL>& requested_metadata_urls() { + const UserNoteStorage::UrlSet& requested_metadata_urls() { return requested_metadata_urls_; } - const IdList& requested_model_ids() { return requested_model_ids_; } + const UserNoteStorage::IdSet& requested_model_ids() { + return requested_model_ids_; + } void MockGetNoteMetadataForUrls( - const std::vector<GURL>& urls, + const UserNoteStorage::UrlSet& urls, base::OnceCallback<void(UserNoteMetadataSnapshot)> callback) { requested_metadata_urls_ = urls; std::move(callback).Run(UserNoteMetadataSnapshot()); } void MockGetNotesById( - const IdList& ids, + const UserNoteStorage::IdSet& ids, base::OnceCallback<void(std::vector<std::unique_ptr<UserNote>>)> callback) { requested_model_ids_ = ids; @@ -119,8 +121,8 @@ } private: - std::vector<GURL> requested_metadata_urls_; - IdList requested_model_ids_; + UserNoteStorage::UrlSet requested_metadata_urls_; + UserNoteStorage::IdSet requested_model_ids_; }; // Partially mock the object under test so tests can control side effects. @@ -494,11 +496,13 @@ // Mocks ensure callbacks are invoked synchronously, so expectations can be // immediately verified. - const std::vector<GURL>& fetched_urls = storage_->requested_metadata_urls(); + const UserNoteStorage::UrlSet& fetched_urls = + storage_->requested_metadata_urls(); + EXPECT_EQ(fetched_urls.size(), web_contents_list_.size()); for (size_t i = 0; i < fetched_urls.size(); ++i) { - EXPECT_EQ( - fetched_urls[i], + const auto& url_it = fetched_urls.find( web_contents_list_[i]->GetPrimaryMainFrame()->GetLastCommittedURL()); + EXPECT_NE(url_it, fetched_urls.end()); } } @@ -552,9 +556,10 @@ EXPECT_EQ(all_frames_result[0], frame); EXPECT_EQ(navigated_frame_result, frame); - const std::vector<GURL>& requested_urls = storage_->requested_metadata_urls(); + const UserNoteStorage::UrlSet& requested_urls = + storage_->requested_metadata_urls(); ASSERT_EQ(requested_urls.size(), 1u); - EXPECT_EQ(requested_urls[0], frame->GetLastCommittedURL()); + EXPECT_EQ(*(requested_urls.begin()), frame->GetLastCommittedURL()); } // After a navigation to a document that has user notes in the foreground, the @@ -868,7 +873,7 @@ // Mocks ensure callbacks are invoked synchronously, so expectations can be // immediately verified. - const IdList& fetched_ids = storage_->requested_model_ids(); + const UserNoteStorage::IdSet& fetched_ids = storage_->requested_model_ids(); EXPECT_EQ(fetched_ids.size(), 4u); EXPECT_NE(std::find(fetched_ids.begin(), fetched_ids.end(), note_ids_[0]), fetched_ids.end());
diff --git a/components/user_notes/interfaces/user_note_metadata_snapshot.h b/components/user_notes/interfaces/user_note_metadata_snapshot.h index 25c2b88..4433ff4c 100644 --- a/components/user_notes/interfaces/user_note_metadata_snapshot.h +++ b/components/user_notes/interfaces/user_note_metadata_snapshot.h
@@ -16,8 +16,6 @@ class UserNoteMetadata; -namespace { - // In order to have GURL as a key in a hashmap, GURL hashing mechanism is // needed. struct GURLHash { @@ -26,8 +24,6 @@ } }; -} // namespace - // A class that encapsulates an // `unordered_map<GURL, unordered_map<ID, UserNoteMetadata>>`. This represents // a snapshot of the note metadata contained in the database for a set of URLs.
diff --git a/components/user_notes/interfaces/user_note_storage.h b/components/user_notes/interfaces/user_note_storage.h index 0b0b18a..baf3513 100644 --- a/components/user_notes/interfaces/user_note_storage.h +++ b/components/user_notes/interfaces/user_note_storage.h
@@ -7,7 +7,8 @@ #include <memory> #include <string> -#include <unordered_map> +#include <unordered_set> +#include <vector> #include "base/callback.h" #include "base/unguessable_token.h" @@ -22,6 +23,10 @@ // Interface that callers can use to interact with the UserNotes in storage. class UserNoteStorage { public: + using UrlSet = std::unordered_set<GURL, GURLHash>; + using IdSet = + std::unordered_set<base::UnguessableToken, base::UnguessableTokenHash>; + // Observer class for the notes storage. Notifies implementers when the notes // have changed on disk so they can update their model. class Observer { @@ -44,13 +49,13 @@ // results are returned via `callback`, mapped by URL and by note // ID. virtual void GetNoteMetadataForUrls( - const std::vector<GURL>& urls, + const UrlSet& urls, base::OnceCallback<void(UserNoteMetadataSnapshot)> callback) = 0; // Fetches all `UserNotes` corresponding to the given IDs from disk. The // results are returned via `callback`. virtual void GetNotesById( - const std::vector<base::UnguessableToken>& ids, + const IdSet& ids, base::OnceCallback<void(std::vector<std::unique_ptr<UserNote>>)> callback) = 0;
diff --git a/components/user_notes/storage/user_note_database.cc b/components/user_notes/storage/user_note_database.cc index 0021674..b75bb9a 100644 --- a/components/user_notes/storage/user_note_database.cc +++ b/components/user_notes/storage/user_note_database.cc
@@ -71,7 +71,7 @@ } UserNoteMetadataSnapshot UserNoteDatabase::GetNoteMetadataForUrls( - std::vector<GURL> urls) { + const UserNoteStorage::UrlSet& urls) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!EnsureDBInit()) @@ -122,7 +122,7 @@ } std::vector<std::unique_ptr<UserNote>> UserNoteDatabase::GetNotesById( - std::vector<base::UnguessableToken> ids) { + const UserNoteStorage::IdSet& ids) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::vector<std::unique_ptr<UserNote>> user_notes;
diff --git a/components/user_notes/storage/user_note_database.h b/components/user_notes/storage/user_note_database.h index ab3bd969..1831b945 100644 --- a/components/user_notes/storage/user_note_database.h +++ b/components/user_notes/storage/user_note_database.h
@@ -13,6 +13,7 @@ #include "base/sequence_checker.h" #include "base/thread_annotations.h" #include "components/user_notes/interfaces/user_note_metadata_snapshot.h" +#include "components/user_notes/interfaces/user_note_storage.h" #include "components/user_notes/model/user_note.h" #include "sql/database.h" #include "url/gurl.h" @@ -33,10 +34,11 @@ // Initialises internal database. Must be called prior to any other usage. bool Init(); - UserNoteMetadataSnapshot GetNoteMetadataForUrls(std::vector<GURL> urls); + UserNoteMetadataSnapshot GetNoteMetadataForUrls( + const UserNoteStorage::UrlSet& urls); std::vector<std::unique_ptr<UserNote>> GetNotesById( - std::vector<base::UnguessableToken> ids); + const UserNoteStorage::IdSet& ids); bool UpdateNote(const UserNote* model, std::u16string note_body_text,
diff --git a/components/user_notes/storage/user_note_database_unittest.cc b/components/user_notes/storage/user_note_database_unittest.cc index be64d8ee..c84a9f5 100644 --- a/components/user_notes/storage/user_note_database_unittest.cc +++ b/components/user_notes/storage/user_note_database_unittest.cc
@@ -4,6 +4,9 @@ #include "components/user_notes/storage/user_note_database.h" +#include <algorithm> +#include <vector> + #include "base/containers/contains.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" @@ -213,10 +216,12 @@ EXPECT_TRUE(user_note_db.Init()); DCHECK_CALLED_ON_VALID_SEQUENCE(user_note_db.sequence_checker_); + UserNoteStorage::IdSet id_set; std::vector<base::UnguessableToken> ids; for (int i = 0; i < 3; i++) { base::UnguessableToken note_id = base::UnguessableToken::Create(); ids.emplace_back(note_id); + id_set.emplace(note_id); std::u16string original_text = u"original text " + base::NumberToString16(i); std::string selector = "selector " + base::NumberToString(i); @@ -233,12 +238,15 @@ delete user_note; } - std::vector<std::unique_ptr<UserNote>> notes = user_note_db.GetNotesById(ids); + std::vector<std::unique_ptr<UserNote>> notes = + user_note_db.GetNotesById(id_set); EXPECT_EQ(3u, notes.size()); - int i = 0; for (std::unique_ptr<UserNote>& note : notes) { - EXPECT_EQ(ids[i].ToString(), note->id().ToString()); + const auto& vector_it = std::find(ids.begin(), ids.end(), note->id()); + EXPECT_NE(vector_it, ids.end()); + EXPECT_NE(id_set.find(note->id()), id_set.end()); + int i = vector_it - ids.begin(); EXPECT_EQ("https://www.test.com/", note->target().target_page().spec()); EXPECT_EQ(u"original text " + base::NumberToString16(i), note->target().original_text()); @@ -246,7 +254,6 @@ EXPECT_EQ(u"new test note " + base::NumberToString16(i), note->body().plain_text_value()); EXPECT_EQ(UserNoteTarget::TargetType::kPageText, note->target().type()); - i++; } } @@ -254,10 +261,10 @@ UserNoteDatabase user_note_db(db_dir()); EXPECT_TRUE(user_note_db.Init()); - std::vector<base::UnguessableToken> ids; + UserNoteStorage::IdSet ids; for (int i = 0; i < 3; i++) { base::UnguessableToken note_id = base::UnguessableToken::Create(); - ids.emplace_back(note_id); + ids.emplace(note_id); UserNote* user_note = new UserNote(note_id, GetTestUserNoteMetadata(), GetTestUserNoteBody(), GetTestUserNotePageTarget()); @@ -278,10 +285,10 @@ UserNoteDatabase user_note_db(db_dir()); EXPECT_TRUE(user_note_db.Init()); - std::vector<base::UnguessableToken> ids; + UserNoteStorage::IdSet ids; for (int i = 0; i < 3; i++) { base::UnguessableToken note_id = base::UnguessableToken::Create(); - ids.emplace_back(note_id); + ids.emplace(note_id); UserNote* user_note = new UserNote(note_id, GetTestUserNoteMetadata(), GetTestUserNoteBody(), GetTestUserNotePageTarget("https://www.test.com")); @@ -304,10 +311,10 @@ UserNoteDatabase user_note_db(db_dir()); EXPECT_TRUE(user_note_db.Init()); - std::vector<base::UnguessableToken> ids; + UserNoteStorage::IdSet ids; for (int i = 0; i < 3; i++) { base::UnguessableToken note_id = base::UnguessableToken::Create(); - ids.emplace_back(note_id); + ids.emplace(note_id); UserNote* user_note = new UserNote(note_id, GetTestUserNoteMetadata(), GetTestUserNoteBody(), GetTestUserNotePageTarget("https://www.test.com")); @@ -330,7 +337,7 @@ EXPECT_TRUE(user_note_db.Init()); DCHECK_CALLED_ON_VALID_SEQUENCE(user_note_db.sequence_checker_); - std::set<base::UnguessableToken> ids; + UserNoteStorage::IdSet ids; base::Time time = base::Time::FromDoubleT(1600000000); int note_version = 1; for (int i = 0; i < 3; i++) { @@ -347,13 +354,17 @@ delete user_note; } - GURL url = GURL("https://www.test.com"); - std::vector<GURL> urls{url}; + GURL url1 = GURL("https://www.test.com"); + GURL url2 = GURL("https://www.test.com"); + GURL url3 = GURL("https://www.test.com/2"); + UserNoteStorage::UrlSet urls{url1, url2, url3}; UserNoteMetadataSnapshot metadata_snapshot = user_note_db.GetNoteMetadataForUrls(urls); const UserNoteMetadataSnapshot::IdToMetadataMap* metadata_map = - metadata_snapshot.GetMapForUrl(url); + metadata_snapshot.GetMapForUrl(url1); EXPECT_EQ(3u, metadata_map->size()); + EXPECT_EQ(3u, metadata_snapshot.GetMapForUrl(url2)->size()); + EXPECT_EQ(nullptr, metadata_snapshot.GetMapForUrl(url3)); for (const auto& metadata_it : *metadata_map) { EXPECT_TRUE(base::Contains(ids, metadata_it.first));
diff --git a/components/user_notes/storage/user_note_storage_impl.cc b/components/user_notes/storage/user_note_storage_impl.cc index 10f41cd..832f676 100644 --- a/components/user_notes/storage/user_note_storage_impl.cc +++ b/components/user_notes/storage/user_note_storage_impl.cc
@@ -4,6 +4,9 @@ #include "components/user_notes/storage/user_note_storage_impl.h" +#include <unordered_set> +#include <vector> + #include "base/bind.h" #include "base/callback.h" #include "base/files/file_path.h" @@ -39,7 +42,7 @@ } void UserNoteStorageImpl::GetNoteMetadataForUrls( - const std::vector<GURL>& urls, + const UserNoteStorage::UrlSet& urls, base::OnceCallback<void(UserNoteMetadataSnapshot)> callback) { database_.AsyncCall(&UserNoteDatabase::GetNoteMetadataForUrls) .WithArgs(std::move(urls)) @@ -47,7 +50,7 @@ } void UserNoteStorageImpl::GetNotesById( - const std::vector<base::UnguessableToken>& ids, + const UserNoteStorage::IdSet& ids, base::OnceCallback<void(std::vector<std::unique_ptr<UserNote>>)> callback) { database_.AsyncCall(&UserNoteDatabase::GetNotesById) .WithArgs(std::move(ids))
diff --git a/components/user_notes/storage/user_note_storage_impl.h b/components/user_notes/storage/user_note_storage_impl.h index c9e5b20..1ecb4229d 100644 --- a/components/user_notes/storage/user_note_storage_impl.h +++ b/components/user_notes/storage/user_note_storage_impl.h
@@ -36,11 +36,11 @@ void RemoveObserver(Observer* observer) override; void GetNoteMetadataForUrls( - const std::vector<GURL>& urls, + const UserNoteStorage::UrlSet& urls, base::OnceCallback<void(UserNoteMetadataSnapshot)> callback) override; void GetNotesById( - const std::vector<base::UnguessableToken>& ids, + const UserNoteStorage::IdSet& ids, base::OnceCallback<void(std::vector<std::unique_ptr<UserNote>>)> callback) override;
diff --git a/components/viz/common/resources/resource_format_utils.cc b/components/viz/common/resources/resource_format_utils.cc index 21c7922..7d554183 100644 --- a/components/viz/common/resources/resource_format_utils.cc +++ b/components/viz/common/resources/resource_format_utils.cc
@@ -641,52 +641,4 @@ return static_cast<WGPUTextureFormat>(ToDawnFormat(format)); } -size_t AlphaBitsForSkColorType(SkColorType color_type) { - switch (color_type) { - case kAlpha_8_SkColorType: - return 8; - case kRGB_565_SkColorType: - return 0; - case kARGB_4444_SkColorType: - return 4; - case kRGBA_8888_SkColorType: - return 8; - case kRGB_888x_SkColorType: - return 0; - case kBGRA_8888_SkColorType: - return 8; - case kRGBA_1010102_SkColorType: - case kBGRA_1010102_SkColorType: - return 2; - case kRGB_101010x_SkColorType: - case kBGR_101010x_SkColorType: - case kGray_8_SkColorType: - return 0; - case kRGBA_F16Norm_SkColorType: - case kRGBA_F16_SkColorType: - return 16; - case kRGBA_F32_SkColorType: - return 32; - case kR8G8_unorm_SkColorType: - return 0; - case kA16_float_SkColorType: - return 16; - case kR16G16_float_SkColorType: - return 0; - case kA16_unorm_SkColorType: - return 16; - case kR16G16_unorm_SkColorType: - return 0; - case kR16G16B16A16_unorm_SkColorType: - return 16; - case kSRGBA_8888_SkColorType: - return 8; - case kR8_unorm_SkColorType: - return 0; - case kUnknown_SkColorType: - default: - return 0; - } -} - } // namespace viz
diff --git a/components/viz/common/resources/resource_format_utils.h b/components/viz/common/resources/resource_format_utils.h index 1325c536f..6b0a324 100644 --- a/components/viz/common/resources/resource_format_utils.h +++ b/components/viz/common/resources/resource_format_utils.h
@@ -83,9 +83,6 @@ VIZ_RESOURCE_FORMAT_EXPORT unsigned int ToMTLPixelFormat(ResourceFormat format); #endif -VIZ_RESOURCE_FORMAT_EXPORT size_t -AlphaBitsForSkColorType(SkColorType color_type); - } // namespace viz #endif // COMPONENTS_VIZ_COMMON_RESOURCES_RESOURCE_FORMAT_UTILS_H_
diff --git a/components/viz/service/display/direct_renderer.cc b/components/viz/service/display/direct_renderer.cc index 2e956bbf..40e3397d 100644 --- a/components/viz/service/display/direct_renderer.cc +++ b/components/viz/service/display/direct_renderer.cc
@@ -341,6 +341,8 @@ reshape_params.color_space = frame_color_space; reshape_params.sdr_white_level = CurrentFrameSDRWhiteLevel(); reshape_params.format = frame_buffer_format; + reshape_params.alpha_type = + frame_has_alpha ? kPremul_SkAlphaType : kOpaque_SkAlphaType; if (next_frame_needs_full_frame_redraw_ || reshape_params != reshape_params_ || display_transform != reshape_display_transform_) {
diff --git a/components/viz/service/display/output_surface.h b/components/viz/service/display/output_surface.h index 5655794..491aebbe 100644 --- a/components/viz/service/display/output_surface.h +++ b/components/viz/service/display/output_surface.h
@@ -203,13 +203,16 @@ float device_scale_factor = 1.f; gfx::ColorSpace color_space; float sdr_white_level = gfx::ColorSpace::kDefaultSDRWhiteLevel; - gfx::BufferFormat format = gfx::BufferFormat::RGBX_8888; + // TODO(sunnyps): Change to SkColorType. + gfx::BufferFormat format = gfx::BufferFormat::RGBA_8888; + SkAlphaType alpha_type = kPremul_SkAlphaType; bool operator==(const ReshapeParams& other) const { return size == other.size && device_scale_factor == other.device_scale_factor && color_space == other.color_space && - sdr_white_level == other.sdr_white_level; + sdr_white_level == other.sdr_white_level && + format == other.format && alpha_type == other.alpha_type; } bool operator!=(const ReshapeParams& other) const { return !(*this == other);
diff --git a/components/viz/service/display_embedder/output_presenter_gl.cc b/components/viz/service/display_embedder/output_presenter_gl.cc index 87e93c2..aa2d1f0a 100644 --- a/components/viz/service/display_embedder/output_presenter_gl.cc +++ b/components/viz/service/display_embedder/output_presenter_gl.cc
@@ -273,11 +273,11 @@ const gfx::ColorSpace& color_space, float device_scale_factor, gfx::OverlayTransform transform) { - gfx::Size size = gfx::SkISizeToSize(characterization.dimensions()); + const gfx::Size size = gfx::SkISizeToSize(characterization.dimensions()); image_format_ = SkColorTypeToResourceFormat(characterization.colorType()); - return gl_surface_->Resize( - size, device_scale_factor, color_space, - !!AlphaBitsForSkColorType(characterization.colorType())); + const bool has_alpha = + !SkAlphaTypeIsOpaque(characterization.imageInfo().alphaType()); + return gl_surface_->Resize(size, device_scale_factor, color_space, has_alpha); } std::vector<std::unique_ptr<OutputPresenter::Image>>
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.cc b/components/viz/service/display_embedder/skia_output_device_gl.cc index 940de015..ce51ffd6 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.cc +++ b/components/viz/service/display_embedder/skia_output_device_gl.cc
@@ -159,8 +159,8 @@ capabilities_.orientation_mode = OutputSurface::OrientationMode::kHardware; #endif // IS_CHROMEOS_ASH - DCHECK(context_state_->gr_context()); - DCHECK(context_state_->context()); + DCHECK(context_state_); + DCHECK(gl_surface_); if (gl_surface_->SupportsSwapTimestamps()) { gl_surface_->SetEnableSwapTimestamps(); @@ -170,25 +170,29 @@ context_state_->MakeCurrent(gl_surface_.get()); } + DCHECK(context_state_->gr_context()); + DCHECK(context_state_->context()); + GrDirectContext* gr_context = context_state_->gr_context(); gl::CurrentGL* current_gl = context_state_->context()->GetCurrentGL(); // Get alpha bits from the default frame buffer. + int alpha_bits = 0; glBindFramebufferEXT(GL_FRAMEBUFFER, 0); gr_context->resetContext(kRenderTarget_GrGLBackendState); const auto* version = current_gl->Version; if (version->is_desktop_core_profile) { glGetFramebufferAttachmentParameterivEXT( GL_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, - &alpha_bits_); + &alpha_bits); } else { - glGetIntegerv(GL_ALPHA_BITS, &alpha_bits_); + glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); } CHECK_GL_ERROR(); auto color_type = kRGBA_8888_SkColorType; - if (!alpha_bits_) { + if (alpha_bits == 0) { color_type = gl_surface_->GetFormat().GetBufferSize() == 16 ? kRGB_565_SkColorType : kRGB_888x_SkColorType; @@ -201,8 +205,7 @@ color_type = kRGBA_8888_SkColorType; } } - - // sRGB + // SRGB capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_8888)] = color_type; capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBX_8888)] = @@ -211,7 +214,11 @@ color_type; capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::BGRX_8888)] = color_type; - // scRGB + // HDR10 + capabilities_ + .sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_1010102)] = + kRGBA_1010102_SkColorType; + // scRGB linear capabilities_.sk_color_types[static_cast<int>(gfx::BufferFormat::RGBA_F16)] = kRGBA_F16_SkColorType; } @@ -230,10 +237,12 @@ DCHECK_EQ(transform, gfx::OVERLAY_TRANSFORM_NONE); #endif // !BUILDFLAG(IS_CHROMEOS_ASH) - gfx::Size size = gfx::SkISizeToSize(characterization.dimensions()); - SkColorType color_type = characterization.colorType(); - if (!gl_surface_->Resize(size, device_scale_factor, color_space, - alpha_bits_)) { + const gfx::Size size = gfx::SkISizeToSize(characterization.dimensions()); + const SkColorType color_type = characterization.colorType(); + const bool has_alpha = + !SkAlphaTypeIsOpaque(characterization.imageInfo().alphaType()); + + if (!gl_surface_->Resize(size, device_scale_factor, color_space, has_alpha)) { CheckForLoopFailures(); // To prevent tail call, so we can see the stack. base::debug::Alias(nullptr); @@ -254,6 +263,9 @@ case kRGB_565_SkColorType: framebuffer_info.fFormat = GL_RGB565; break; + case kRGBA_1010102_SkColorType: + framebuffer_info.fFormat = GL_RGB10_A2_EXT; + break; case kRGBA_F16_SkColorType: framebuffer_info.fFormat = GL_RGBA16F; break; @@ -261,9 +273,6 @@ NOTREACHED() << "color_type: " << color_type; } - // TODO(kylechar): We might need to support RGB10A2 for HDR10. HDR10 was only - // used with Windows updated RS3 (2017) as a workaround for a DWM bug so it - // might not be relevant to support anymore as a result. GrBackendRenderTarget render_target(size.width(), size.height(), characterization.sampleCount(), /*stencilBits=*/0, framebuffer_info);
diff --git a/components/viz/service/display_embedder/skia_output_device_gl.h b/components/viz/service/display_embedder/skia_output_device_gl.h index 5bba2332..64279ac 100644 --- a/components/viz/service/display_embedder/skia_output_device_gl.h +++ b/components/viz/service/display_embedder/skia_output_device_gl.h
@@ -107,7 +107,6 @@ uint64_t backbuffer_estimated_size_ = 0; - int alpha_bits_ = 0; gfx::Size size_; SkColorType color_type_; gfx::ColorSpace color_space_;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.cc b/components/viz/service/display_embedder/skia_output_surface_impl.cc index 74fa08e4..79d3e76 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -289,6 +289,8 @@ void SkiaOutputSurfaceImpl::Reshape(const ReshapeParams& params) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!params.size.IsEmpty()); + DCHECK(params.alpha_type == kPremul_SkAlphaType || + params.alpha_type == kOpaque_SkAlphaType); // SetDrawRectangle() will need to be called at the new size. has_set_draw_rectangle_for_frame_ = false; @@ -318,8 +320,9 @@ auto sk_color_space = params.color_space.ToSkColorSpace(params.sdr_white_level); characterization_ = CreateSkSurfaceCharacterization( - params.size, color_type, /*mipmap=*/false, std::move(sk_color_space), - /*is_root_render_pass=*/true, /*is_overlay=*/false); + params.size, color_type, params.alpha_type, /*mipmap=*/false, + std::move(sk_color_space), /*is_root_render_pass=*/true, + /*is_overlay=*/false); // impl_on_gpu_ is released on the GPU thread by a posted task from // SkiaOutputSurfaceImpl::dtor. So it is safe to use base::Unretained. @@ -586,8 +589,9 @@ SkColorType color_type = ResourceFormatToClosestSkColorType(/*gpu_compositing=*/true, format); SkSurfaceCharacterization characterization = CreateSkSurfaceCharacterization( - surface_size, color_type, mipmap, std::move(color_space), - /*is_root_render_pass=*/false, /*is_overlay=*/is_overlay); + surface_size, color_type, kPremul_SkAlphaType, mipmap, + std::move(color_space), /*is_root_render_pass=*/false, + /*is_overlay=*/is_overlay); if (!characterization.isValid()) return nullptr; @@ -617,9 +621,10 @@ SkSurfaceCharacterization characterization = CreateSkSurfaceCharacterization( gfx::Size(characterization_.width(), characterization_.height()), - characterization_.colorType(), + characterization_.colorType(), characterization_.imageInfo().alphaType(), /*mipmap=*/false, characterization_.refColorSpace(), - /*is_root_render_pass=*/false, /*is_overlay=*/false); + /*is_root_render_pass=*/false, + /*is_overlay=*/false); if (characterization.isValid()) { overdraw_surface_recorder_.emplace(characterization); overdraw_canvas_.emplace((overdraw_surface_recorder_->getCanvas())); @@ -881,6 +886,7 @@ SkiaOutputSurfaceImpl::CreateSkSurfaceCharacterization( const gfx::Size& surface_size, SkColorType color_type, + SkAlphaType alpha_type, bool mipmap, sk_sp<SkColorSpace> color_space, bool is_root_render_pass, @@ -913,9 +919,9 @@ capabilities_.output_surface_origin == gfx::SurfaceOrigin::kBottomLeft ? kBottomLeft_GrSurfaceOrigin : kTopLeft_GrSurfaceOrigin; - auto image_info = SkImageInfo::Make( - surface_size.width(), surface_size.height(), color_type, - kPremul_SkAlphaType, std::move(color_space)); + auto image_info = + SkImageInfo::Make(surface_size.width(), surface_size.height(), + color_type, alpha_type, std::move(color_space)); DCHECK((capabilities_.uses_default_gl_framebuffer && dependency_->gr_context_type() == gpu::GrContextType::kGL) || !capabilities_.uses_default_gl_framebuffer); @@ -973,7 +979,7 @@ #endif auto image_info = SkImageInfo::Make(surface_size.width(), surface_size.height(), color_type, - kPremul_SkAlphaType, std::move(color_space)); + alpha_type, std::move(color_space)); auto characterization = gr_context_thread_safe_->createCharacterization( cache_max_resource_bytes, image_info, backend_format, sample_count,
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.h b/components/viz/service/display_embedder/skia_output_surface_impl.h index f7ae89f6..8e36f9c 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -180,6 +180,7 @@ SkSurfaceCharacterization CreateSkSurfaceCharacterization( const gfx::Size& surface_size, SkColorType color_type, + SkAlphaType alpha_type, bool mipmap, sk_sp<SkColorSpace> color_space, bool is_root_render_pass,
diff --git a/content/browser/attribution_reporting/attribution_host.cc b/content/browser/attribution_reporting/attribution_host.cc index d11887f..9f14db3 100644 --- a/content/browser/attribution_reporting/attribution_host.cc +++ b/content/browser/attribution_reporting/attribution_host.cc
@@ -135,9 +135,22 @@ const url::Origin& impression_origin = it->second; + const std::vector<GURL>& redirect_chain = + navigation_handle->GetRedirectChain(); + + if (redirect_chain.size() < 2) + return; + + // The reporting origin should be the origin of the request responsible for + // initiating this redirect. At this point, the navigation handle reflects the + // URL being navigated to, so instead use the second to last URL in the + // redirect chain. + url::Origin reporting_origin = + url::Origin::Create(redirect_chain[redirect_chain.size() - 2]); + data_host_manager->NotifyNavigationRedirectRegistation( navigation_handle->GetImpression()->attribution_src_token, source_header, - url::Origin::Create(navigation_handle->GetURL()), impression_origin); + std::move(reporting_origin), impression_origin); } void AttributionHost::DidFinishNavigation(NavigationHandle* navigation_handle) {
diff --git a/content/browser/attribution_reporting/attributions_browsertest.cc b/content/browser/attribution_reporting/attributions_browsertest.cc index 79509fc..94d98efc 100644 --- a/content/browser/attribution_reporting/attributions_browsertest.cc +++ b/content/browser/attribution_reporting/attributions_browsertest.cc
@@ -333,11 +333,15 @@ IN_PROC_BROWSER_TEST_F(AttributionsBrowserTest, ImpressionNavigationRedirect_ReportSent) { + auto register_response = + std::make_unique<net::test_server::ControllableHttpResponse>( + https_server(), "/register_source_redirect"); + // Expected reports must be registered before the server starts. ExpectedReportWaiter expected_report( GURL("https://d.test/.well-known/attribution-reporting/" "report-event-attribution"), - /*attribution_destination=*/"https://d.test", + /*attribution_destination=*/"https://c.test", /*source_event_id=*/"1", /*source_type=*/"navigation", /*trigger_data=*/"7", https_server()); ASSERT_TRUE(https_server()->Start()); @@ -348,16 +352,40 @@ // Create an anchor tag with impression attributes and click the link. By // default the target is set to "_top". - GURL register_source_url = https_server()->GetURL( - "d.test", - "/attribution_reporting/register_source_navigation_redirect.html"); + GURL register_source_url = + https_server()->GetURL("d.test", "/register_source_redirect"); - CreateAndClickSource(web_contents(), register_source_url, - /*attribution_src*/ ""); + EXPECT_TRUE(ExecJs(web_contents(), JsReplace(R"( + createAttributionSrcAnchor({id: 'link', + url: $1, + attributionsrc: '', + target: $2});)", + register_source_url, "_top"))); + + TestNavigationObserver observer(web_contents()); + EXPECT_TRUE(ExecJs(web_contents(), "simulateClick('link');")); + + register_response->WaitForRequest(); + auto http_response = std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_code(net::HTTP_MOVED_PERMANENTLY); + http_response->AddCustomHeader( + "Attribution-Reporting-Register-Source", + R"({"source_event_id":"1","destination":"https://c.test"})"); + + http_response->AddCustomHeader( + "Location", + https_server() + ->GetURL("c.test", + "/attribution_reporting/page_with_conversion_redirect.html") + .spec()); + register_response->Send(http_response->ToResponseString()); + register_response->Done(); + + // Wait for navigation to complete. + observer.Wait(); GURL register_trigger_url = https_server()->GetURL( "d.test", "/attribution_reporting/register_trigger_headers.html"); - EXPECT_TRUE(ExecJs(web_contents(), JsReplace("createAttributionSrcImg($1);", register_trigger_url))); @@ -365,6 +393,95 @@ } IN_PROC_BROWSER_TEST_F(AttributionsBrowserTest, + ImpressionNavigationMultipleRedirects_FirstReportSent) { + auto register_response = + std::make_unique<net::test_server::ControllableHttpResponse>( + https_server(), "/register_source_redirect"); + + auto register_response2 = + std::make_unique<net::test_server::ControllableHttpResponse>( + https_server(), "/register_source_redirect"); + + // Expected reports must be registered before the server starts. + ExpectedReportWaiter expected_report( + GURL("https://d.test/.well-known/attribution-reporting/" + "report-event-attribution"), + /*attribution_destination=*/"https://c.test", + /*source_event_id=*/"1", /*source_type=*/"navigation", + /*trigger_data=*/"7", https_server()); + ExpectedReportWaiter expected_report2( + GURL("https://b.test/.well-known/attribution-reporting/" + "report-event-attribution"), + /*attribution_destination=*/"https://c.test", + /*source_event_id=*/"2", /*source_type=*/"navigation", + /*trigger_data=*/"7", https_server()); + ASSERT_TRUE(https_server()->Start()); + + GURL impression_url = https_server()->GetURL( + "a.test", "/attribution_reporting/page_with_impression_creator.html"); + EXPECT_TRUE(NavigateToURL(web_contents(), impression_url)); + + // Create an anchor tag with impression attributes and click the link. By + // default the target is set to "_top". + GURL register_source_url = + https_server()->GetURL("d.test", "/register_source_redirect"); + + EXPECT_TRUE(ExecJs(web_contents(), JsReplace(R"( + createAttributionSrcAnchor({id: 'link', + url: $1, + attributionsrc: '', + target: $2});)", + register_source_url, "_top"))); + + TestNavigationObserver observer(web_contents()); + EXPECT_TRUE(ExecJs(web_contents(), "simulateClick('link');")); + + register_response->WaitForRequest(); + auto http_response = std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_code(net::HTTP_MOVED_PERMANENTLY); + http_response->AddCustomHeader( + "Attribution-Reporting-Register-Source", + R"({"source_event_id":"1","destination":"https://c.test"})"); + + http_response->AddCustomHeader( + "Location", + https_server()->GetURL("b.test", "/register_source_redirect").spec()); + register_response->Send(http_response->ToResponseString()); + register_response->Done(); + + register_response2->WaitForRequest(); + auto http_response2 = std::make_unique<net::test_server::BasicHttpResponse>(); + http_response2->set_code(net::HTTP_MOVED_PERMANENTLY); + http_response2->AddCustomHeader( + "Attribution-Reporting-Register-Source", + R"({"source_event_id":"2","destination":"https://c.test"})"); + + http_response2->AddCustomHeader( + "Location", + https_server() + ->GetURL("c.test", + "/attribution_reporting/page_with_conversion_redirect.html") + .spec()); + register_response2->Send(http_response2->ToResponseString()); + register_response2->Done(); + + // Wait for navigation to complete. + observer.Wait(); + + GURL register_trigger_url = https_server()->GetURL( + "d.test", "/attribution_reporting/register_trigger_headers.html"); + EXPECT_TRUE(ExecJs(web_contents(), JsReplace("createAttributionSrcImg($1);", + register_trigger_url))); + expected_report.WaitForReport(); + + GURL register_trigger_url2 = https_server()->GetURL( + "b.test", "/attribution_reporting/register_trigger_headers.html"); + EXPECT_TRUE(ExecJs(web_contents(), JsReplace("createAttributionSrcImg($1);", + register_trigger_url2))); + expected_report2.WaitForReport(); +} + +IN_PROC_BROWSER_TEST_F(AttributionsBrowserTest, ImpressionNavigationRedirectWindowOpen_ReportSent) { // Expected reports must be registered before the server starts. ExpectedReportWaiter expected_report(
diff --git a/content/browser/host_zoom_map_impl.cc b/content/browser/host_zoom_map_impl.cc index 6d66eb8..32b28237 100644 --- a/content/browser/host_zoom_map_impl.cc +++ b/content/browser/host_zoom_map_impl.cc
@@ -493,6 +493,16 @@ } #if BUILDFLAG(IS_ANDROID) +void HostZoomMapImpl::SetDefaultZoomLevelPrefCallback( + HostZoomMap::DefaultZoomChangedCallback callback) { + default_zoom_level_pref_callback_ = std::move(callback); +} + +HostZoomMap::DefaultZoomChangedCallback* +HostZoomMapImpl::GetDefaultZoomLevelPrefCallback() { + return &default_zoom_level_pref_callback_; +} + void JNI_HostZoomMapImpl_SetZoomLevel( JNIEnv* env, const base::android::JavaParamRef<jobject>& j_web_contents, @@ -523,6 +533,16 @@ HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>( HostZoomMap::GetDefaultForBrowserContext(context)); + + // If a callback has been set (e.g. by chrome_zoom_level_prefs to store an + // updated value in Prefs), call this now with the chosen zoom level. + if (host_zoom_map->GetDefaultZoomLevelPrefCallback()) { + host_zoom_map->GetDefaultZoomLevelPrefCallback()->Run( + new_default_zoom_level); + } + + // Update the default zoom level for existing tabs. This must be done after + // the Pref is updated due to guard clause in chrome_zoom_level_prefs. host_zoom_map->SetDefaultZoomLevel(new_default_zoom_level); }
diff --git a/content/browser/host_zoom_map_impl.h b/content/browser/host_zoom_map_impl.h index 543ab3a53..21d92ff 100644 --- a/content/browser/host_zoom_map_impl.h +++ b/content/browser/host_zoom_map_impl.h
@@ -80,6 +80,12 @@ void SetClockForTesting(base::Clock* clock) override; +#if BUILDFLAG(IS_ANDROID) + void SetDefaultZoomLevelPrefCallback( + HostZoomMap::DefaultZoomChangedCallback callback) override; + HostZoomMap::DefaultZoomChangedCallback* GetDefaultZoomLevelPrefCallback(); +#endif + private: struct ZoomLevel { double level; @@ -121,6 +127,11 @@ base::RepeatingCallbackList<void(const ZoomLevelChange&)> zoom_level_changed_callbacks_; +#if BUILDFLAG(IS_ANDROID) + // Callback called when Java-side UI updates the default zoom level. + HostZoomMap::DefaultZoomChangedCallback default_zoom_level_pref_callback_; +#endif + // Copy of the pref data. HostZoomLevels host_zoom_levels_; SchemeHostZoomLevels scheme_host_zoom_levels_;
diff --git a/content/browser/media/cdm_registry_impl.cc b/content/browser/media/cdm_registry_impl.cc index 0c6fbc0e..f83da99 100644 --- a/content/browser/media/cdm_registry_impl.cc +++ b/content/browser/media/cdm_registry_impl.cc
@@ -94,15 +94,16 @@ // indicate that all relevant profiles should be considered supported. std::vector<media::AudioCodec> audio_codecs; media::CdmCapability::VideoCodecMap video_codecs; + const media::VideoCodecInfo kAllProfiles; for (const auto& codec : overridden_codecs) { if (codec == "vp8") - video_codecs[media::VideoCodec::kVP8] = {}; + video_codecs.emplace(media::VideoCodec::kVP8, kAllProfiles); else if (codec == "vp9") - video_codecs[media::VideoCodec::kVP9] = {}; + video_codecs.emplace(media::VideoCodec::kVP9, kAllProfiles); else if (codec == "avc1") - video_codecs[media::VideoCodec::kH264] = {}; + video_codecs.emplace(media::VideoCodec::kH264, kAllProfiles); else if (codec == "hevc") - video_codecs[media::VideoCodec::kHEVC] = {}; + video_codecs.emplace(media::VideoCodec::kHEVC, kAllProfiles); else if (codec == "mp4a") audio_codecs.push_back(media::AudioCodec::kAAC); else if (codec == "vorbis")
diff --git a/content/browser/media/cdm_registry_impl_unittest.cc b/content/browser/media/cdm_registry_impl_unittest.cc index 4c1c1718a..3b0dd0a 100644 --- a/content/browser/media/cdm_registry_impl_unittest.cc +++ b/content/browser/media/cdm_registry_impl_unittest.cc
@@ -62,8 +62,8 @@ std::vector<media::VideoCodec> VideoCodecMapToList( const media::CdmCapability::VideoCodecMap& map) { std::vector<media::VideoCodec> list; - for (const auto& entry : map) { - list.push_back(entry.first); + for (const auto& [video_codec, _] : map) { + list.push_back(video_codec); } return list; } @@ -309,16 +309,20 @@ media::CdmCapability( {AudioCodec::kVorbis}, {{VideoCodec::kVP9, - {media::VP9PROFILE_PROFILE0, media::VP9PROFILE_PROFILE2}}}, + {{media::VP9PROFILE_PROFILE0, media::VP9PROFILE_PROFILE2}}}}, {EncryptionScheme::kCenc}, {CdmSessionType::kTemporary})); auto cdm_info = cdm_registry_.GetCdmInfo( kTestKeySystem, CdmInfo::Robustness::kSoftwareSecure); CdmInfo& cdm = *cdm_info; EXPECT_VIDEO_CODECS(VideoCodec::kVP9); - EXPECT_TRUE(base::Contains(cdm.capability->video_codecs[VideoCodec::kVP9], - media::VP9PROFILE_PROFILE0)); - EXPECT_TRUE(base::Contains(cdm.capability->video_codecs[VideoCodec::kVP9], - media::VP9PROFILE_PROFILE2)); + EXPECT_TRUE(base::Contains( + cdm.capability->video_codecs[VideoCodec::kVP9].video_codec_profiles, + media::VP9PROFILE_PROFILE0)); + EXPECT_TRUE(base::Contains( + cdm.capability->video_codecs[VideoCodec::kVP9].video_codec_profiles, + media::VP9PROFILE_PROFILE2)); + EXPECT_TRUE( + cdm.capability->video_codecs[VideoCodec::kVP9].supports_clear_lead); } TEST_F(CdmRegistryImplTest, SupportedEncryptionSchemes) {
diff --git a/content/browser/media/media_internals_cdm_helper.cc b/content/browser/media/media_internals_cdm_helper.cc index d471917..bda0d6cd 100644 --- a/content/browser/media/media_internals_cdm_helper.cc +++ b/content/browser/media/media_internals_cdm_helper.cc
@@ -61,7 +61,7 @@ } base::Value VideoCodecProfilesToValue( - const std::vector<media::VideoCodecProfile>& profiles) { + const base::flat_set<media::VideoCodecProfile>& profiles) { base::Value list(base::Value::Type::LIST); for (const auto& profile : profiles) list.Append(media::GetProfileName(profile)); @@ -78,9 +78,10 @@ auto* video_codec_dict = dict.SetKey("Video Codecs", base::Value(base::Value::Type::DICTIONARY)); - for (const auto& video_codec_map : cdm_capability.video_codecs) { - auto codec_name = media::GetCodecName(video_codec_map.first); - auto& profiles = video_codec_map.second; + for (const auto& [video_codec, video_codec_info] : + cdm_capability.video_codecs) { + auto codec_name = media::GetCodecName(video_codec); + auto& profiles = video_codec_info.video_codec_profiles; video_codec_dict->SetPath(codec_name, VideoCodecProfilesToValue(profiles)); }
diff --git a/content/browser/renderer_host/cross_process_frame_connector.cc b/content/browser/renderer_host/cross_process_frame_connector.cc index 201d471..898f5cb4 100644 --- a/content/browser/renderer_host/cross_process_frame_connector.cc +++ b/content/browser/renderer_host/cross_process_frame_connector.cc
@@ -86,7 +86,7 @@ view_->SetFrameConnector(nullptr); } - ResetScreenSpaceRect(); + ResetRectInParentView(); view_ = view; // Attach ourselves to the new view and size it appropriately. Also update @@ -192,7 +192,7 @@ capture_sequence_number_ = visual_properties.capture_sequence_number; - SetScreenSpaceRect(visual_properties.screen_space_rect); + SetRectInParentView(visual_properties.rect_in_local_root); SetLocalFrameSize(visual_properties.local_frame_size); if (!view_) @@ -345,7 +345,7 @@ TRACE_EVENT_FLAG_FLOW_IN, "message", "FrameHostMsg_SynchronizeVisualProperties", "new_local_surface_id", visual_properties.local_surface_id.ToString()); - // If the |screen_space_rect| or current ScreenInfo of the frame has + // If the |rect_in_local_root| or current ScreenInfo of the frame has // changed, then the viz::LocalSurfaceId must also change. if ((last_received_local_frame_size_ != visual_properties.local_frame_size || screen_infos_.current() != visual_properties.screen_infos.current() || @@ -529,25 +529,24 @@ gfx::ScaleToRoundedSize(local_frame_size, 1.f / dsf); } -void CrossProcessFrameConnector::SetScreenSpaceRect( - const gfx::Rect& screen_space_rect) { - gfx::Rect old_rect = screen_space_rect_in_pixels_; +void CrossProcessFrameConnector::SetRectInParentView( + const gfx::Rect& rect_in_parent_view) { + gfx::Rect old_rect = rect_in_parent_view_in_dip_; const float dsf = screen_infos_.current().device_scale_factor; - screen_space_rect_in_pixels_ = screen_space_rect; - screen_space_rect_in_dip_ = - gfx::Rect(gfx::ScaleToFlooredPoint(screen_space_rect.origin(), 1.f / dsf), - gfx::ScaleToCeiledSize(screen_space_rect.size(), 1.f / dsf)); + rect_in_parent_view_in_dip_ = gfx::Rect( + gfx::ScaleToFlooredPoint(rect_in_parent_view.origin(), 1.f / dsf), + gfx::ScaleToCeiledSize(rect_in_parent_view.size(), 1.f / dsf)); if (view_ && frame_proxy_in_parent_renderer_) { - view_->SetBounds(screen_space_rect_in_dip_); + view_->SetBounds(rect_in_parent_view_in_dip_); // Other local root frames nested underneath this one implicitly have their // view rects changed when their ancestor is repositioned, and therefore // need to have their screen rects updated. FrameTreeNode* proxy_node = frame_proxy_in_parent_renderer_->frame_tree_node(); - if (old_rect.x() != screen_space_rect_in_pixels_.x() || - old_rect.y() != screen_space_rect_in_pixels_.y()) { + if (old_rect.x() != rect_in_parent_view_in_dip_.x() || + old_rect.y() != rect_in_parent_view_in_dip_.y()) { for (FrameTreeNode* node : proxy_node->frame_tree()->SubtreeNodes(proxy_node)) { if (node != proxy_node && node->current_frame_host()->is_local_root()) @@ -557,12 +556,11 @@ } } -void CrossProcessFrameConnector::ResetScreenSpaceRect() { +void CrossProcessFrameConnector::ResetRectInParentView() { local_surface_id_ = viz::LocalSurfaceId(); - // TODO(lfg): Why do we need to reset the screen_space_rect_ that comes from - // the parent when setting the child? https://crbug.com/809275 - screen_space_rect_in_pixels_ = gfx::Rect(); - screen_space_rect_in_dip_ = gfx::Rect(); + // TODO(lfg): Why do we need to reset the rect_in_parent_view_in_dip_ that + // comes from the parent when setting the child? https://crbug.com/809275 + rect_in_parent_view_in_dip_ = gfx::Rect(); last_received_local_frame_size_ = gfx::Size(); }
diff --git a/content/browser/renderer_host/cross_process_frame_connector.h b/content/browser/renderer_host/cross_process_frame_connector.h index 70daf50..646d0ad 100644 --- a/content/browser/renderer_host/cross_process_frame_connector.h +++ b/content/browser/renderer_host/cross_process_frame_connector.h
@@ -135,14 +135,8 @@ // Return the rect in DIP that the RenderWidgetHostViewChildFrame's content // will render into. - const gfx::Rect& screen_space_rect_in_dip() const { - return screen_space_rect_in_dip_; - } - - // Return the rect in pixels that the RenderWidgetHostViewChildFrame's content - // will render into. - const gfx::Rect& screen_space_rect_in_pixels() const { - return screen_space_rect_in_pixels_; + const gfx::Rect& rect_in_parent_view_in_dip() const { + return rect_in_parent_view_in_dip_; } // Return the latest capture sequence number for this subframe. @@ -268,9 +262,9 @@ // if not. void SetLocalFrameSize(const gfx::Size& local_frame_size); - // Called to resize the child renderer. |screen_space_rect| is in pixels if - // zoom-for-dsf is enabled, and in DIP if not. - void SetScreenSpaceRect(const gfx::Rect& screen_space_rect); + // Called to resize the child renderer. |rect_in_parent_view| is in physical + // pixels. + void SetRectInParentView(const gfx::Rect& rect_in_parent_view); void SetIsInert(bool inert); @@ -341,7 +335,7 @@ // Resets the rect and the viz::LocalSurfaceId of the connector to ensure the // unguessable surface ID is not reused after a cross-process navigation. - void ResetScreenSpaceRect(); + void ResetRectInParentView(); // Logs the Stability.ChildFrameCrash.Visibility metric after checking that a // crash has indeed happened and checking that the crash has not already been @@ -366,8 +360,7 @@ display::ScreenInfos screen_infos_; gfx::Size local_frame_size_in_dip_; gfx::Size local_frame_size_in_pixels_; - gfx::Rect screen_space_rect_in_dip_; - gfx::Rect screen_space_rect_in_pixels_; + gfx::Rect rect_in_parent_view_in_dip_; viz::LocalSurfaceId local_surface_id_;
diff --git a/content/browser/renderer_host/media/audio_service_listener.cc b/content/browser/renderer_host/media/audio_service_listener.cc index aa57490..8f3ae57c 100644 --- a/content/browser/renderer_host/media/audio_service_listener.cc +++ b/content/browser/renderer_host/media/audio_service_listener.cc
@@ -8,6 +8,7 @@ #include "base/feature_list.h" #include "base/metrics/histogram_macros.h" +#include "base/process/process.h" #include "base/time/default_tick_clock.h" #include "content/browser/media/audio_log_factory.h" #include "content/public/browser/audio_service.h" @@ -30,16 +31,18 @@ ServiceProcessHost::RemoveObserver(this); } -base::ProcessId AudioServiceListener::GetProcessId() const { +base::Process AudioServiceListener::GetProcess() const { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); - return process_id_; + if (!audio_process_.IsValid()) + return base::Process(); + return audio_process_.Duplicate(); } void AudioServiceListener::Init( std::vector<ServiceProcessInfo> running_service_processes) { for (const auto& info : running_service_processes) { if (info.IsService<audio::mojom::AudioService>()) { - process_id_ = info.pid; + audio_process_ = info.GetProcess().Duplicate(); MaybeSetLogFactory(); break; } @@ -52,7 +55,7 @@ if (!info.IsService<audio::mojom::AudioService>()) return; - process_id_ = info.pid; + audio_process_ = info.GetProcess().Duplicate(); MaybeSetLogFactory(); } @@ -62,7 +65,7 @@ if (!info.IsService<audio::mojom::AudioService>()) return; - process_id_ = base::kNullProcessId; + audio_process_ = base::Process(); log_factory_is_set_ = false; } @@ -72,7 +75,7 @@ if (!info.IsService<audio::mojom::AudioService>()) return; - process_id_ = base::kNullProcessId; + audio_process_ = base::Process(); log_factory_is_set_ = false; }
diff --git a/content/browser/renderer_host/media/audio_service_listener.h b/content/browser/renderer_host/media/audio_service_listener.h index 9f6adaf..5d86901 100644 --- a/content/browser/renderer_host/media/audio_service_listener.h +++ b/content/browser/renderer_host/media/audio_service_listener.h
@@ -9,7 +9,7 @@ #include <vector> #include "base/gtest_prod_util.h" -#include "base/process/process_handle.h" +#include "base/process/process.h" #include "content/common/content_export.h" #include "content/public/browser/service_process_host.h" #include "content/public/browser/service_process_info.h" @@ -28,7 +28,7 @@ ~AudioServiceListener() override; - base::ProcessId GetProcessId() const; + base::Process GetProcess() const; private: FRIEND_TEST_ALL_PREFIXES(AudioServiceListenerTest, @@ -51,7 +51,7 @@ void MaybeSetLogFactory(); - base::ProcessId process_id_ = base::kNullProcessId; + base::Process audio_process_; bool log_factory_is_set_ = false; SEQUENCE_CHECKER(owning_sequence_); };
diff --git a/content/browser/renderer_host/media/audio_service_listener_unittest.cc b/content/browser/renderer_host/media/audio_service_listener_unittest.cc index e808185..739b900b 100644 --- a/content/browser/renderer_host/media/audio_service_listener_unittest.cc +++ b/content/browser/renderer_host/media/audio_service_listener_unittest.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/process/process.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "base/token.h" @@ -19,11 +20,10 @@ namespace { -ServiceProcessInfo MakeFakeAudioServiceProcessInfo(base::ProcessId pid) { - ServiceProcessInfo fake_audio_process_info; - fake_audio_process_info.pid = pid; - fake_audio_process_info.service_interface_name = - audio::mojom::AudioService::Name_; +ServiceProcessInfo MakeFakeAudioServiceProcessInfo() { + ServiceProcessInfo fake_audio_process_info(audio::mojom::AudioService::Name_, + content::ServiceProcessId(), + base::Process::Current()); return fake_audio_process_info; } @@ -45,10 +45,12 @@ TEST_F(AudioServiceListenerTest, OnInitWithAudioService_ProcessIdNotNull) { AudioServiceListener audio_service_listener; - constexpr base::ProcessId pid(42); - ServiceProcessInfo audio_process_info = MakeFakeAudioServiceProcessInfo(pid); - audio_service_listener.Init({audio_process_info}); - EXPECT_EQ(pid, audio_service_listener.GetProcessId()); + ServiceProcessInfo audio_process_info = MakeFakeAudioServiceProcessInfo(); + std::vector<ServiceProcessInfo> info; + info.push_back(std::move(audio_process_info)); + audio_service_listener.Init(std::move(info)); + EXPECT_EQ(base::Process::Current().Pid(), + audio_service_listener.GetProcess().Pid()); } } // namespace content
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index d66cd3f..b603089c 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -3250,42 +3250,10 @@ // Compute the WebExposedIsolationInfo that will be bundled into UrlInfo. auto web_exposed_isolation_info = ComputeWebExposedIsolationInfo(); - // Determine if the request is for a sandboxed frame or not. If - // PolicyContainer::ComputePoliciesToCommit() has run - // `policy_container_builder_` will be valid, but even if it hasn't, we can - // speculatively take `commit_params_->frame_policy.sandbox_flags` if we - // haven't received the response yet and don't have the final - // `policy_container_builder_`, and if the state of the kOrigin flag changes, - // we'll detect the change and recompute the target SiteInstance elsewhere. - // Note: We don't try to process-isolate about:blank URLs since that would - // prevent the parent frame from interacting with them, and they would be - // stuck as empty content. - bool is_origin_restricted_sandbox = false; - if (SiteIsolationPolicy::AreIsolatedSandboxedIframesEnabled() && - !GetURL().IsAboutBlank()) { - if (policy_container_builder_->HasComputedPolicies()) { - is_origin_restricted_sandbox = - (policy_container_builder_->FinalPolicies().sandbox_flags & - network::mojom::WebSandboxFlags::kOrigin) == - network::mojom::WebSandboxFlags::kOrigin; - } else { - // Note: We'll end up here if this function is called before - // ComputePoliciesToCommit(), such as when computing a speculative - // RenderFrameHost's SiteInstance before receiving a response. In that - // event we use the sandbox flags in commit_params_ as a current "best - // estimate". - is_origin_restricted_sandbox = - (commit_params_->frame_policy.sandbox_flags & - network::mojom::WebSandboxFlags::kOrigin) == - network::mojom::WebSandboxFlags::kOrigin; - } - } - UrlInfoInit url_info_init(GetURL()); url_info_init.WithOriginIsolationRequest(isolation_request) .WithWebExposedIsolationInfo(web_exposed_isolation_info) - .WithIsPdf(is_pdf_) - .WithSandbox(is_origin_restricted_sandbox); + .WithIsPdf(is_pdf_); // Navigations within guests should always stay in the guest's // StoragePartition. @@ -3331,6 +3299,62 @@ DCHECK(!url_info_init.origin().has_value()); } + // Determine if the request is for a sandboxed frame or not, and if so whether + // the sandboxed frame should get a dedicated process. Setting + // `has_origin_restricted_sandbox_flag` to true indicates it should get + // process isolation, but only if the site/origin would have qualified for a + // dedicated process even without the sandbox flags. + // + // If PolicyContainer::ComputePoliciesToCommit() has run + // `policy_container_builder_` will be valid, but even if it hasn't, we can + // speculatively take `commit_params_->frame_policy.sandbox_flags` if we + // haven't received the response yet and don't have the final + // `policy_container_builder_`, and if the state of the kOrigin flag changes, + // we'll detect the change and recompute the target SiteInstance elsewhere. + // Note: We don't try to process-isolate about:blank URLs since that would + // prevent the parent frame from interacting with them, and they would be + // stuck as empty content. + if (SiteIsolationPolicy::AreIsolatedSandboxedIframesEnabled() && + !GetURL().IsAboutBlank()) { + // Determine if the frame has the sandbox flag or not. + bool has_origin_restricted_sandbox_flag = false; + if (policy_container_builder_->HasComputedPolicies()) { + has_origin_restricted_sandbox_flag = + (policy_container_builder_->FinalPolicies().sandbox_flags & + network::mojom::WebSandboxFlags::kOrigin) == + network::mojom::WebSandboxFlags::kOrigin; + } else { + // Note: We'll end up here if this function is called before + // ComputePoliciesToCommit(), such as when computing a speculative + // RenderFrameHost's SiteInstance before receiving a response. In that + // event we use the sandbox flags in commit_params_ as a current "best + // estimate". + has_origin_restricted_sandbox_flag = + (commit_params_->frame_policy.sandbox_flags & + network::mojom::WebSandboxFlags::kOrigin) == + network::mojom::WebSandboxFlags::kOrigin; + } + + if (has_origin_restricted_sandbox_flag) { + // If the URL under consideration wouldn't qualify for a dedicated process + // without the sandbox flags, then it shouldn't qualify even with the + // sandbox flag. This is most likely to occur when site isolation is only + // partial, as on Android. + // + // Ideally the IsolationContext would be the one used for the committed + // RenderFrameHost at the end of the navigation, since a different set of + // origins may require isolation if a BrowsingInstance swap occurs. This + // isn't known at the start of the navigation, though, so we use the + // current IsolationContext instead. + const IsolationContext& isolation_context = + current_instance->GetIsolationContext(); + if (SiteInfo::Create(isolation_context, UrlInfo(url_info_init)) + .RequiresDedicatedProcess(isolation_context)) { + url_info_init.WithSandbox(true); + } + } + } + return UrlInfo(url_info_init); }
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 3c934fe4..cfa45a1 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -2520,11 +2520,11 @@ std::move(callback).Run(); } -void RenderWidgetHostImpl::ShowPopup(const gfx::Rect& initial_rect, - const gfx::Rect& anchor_rect, +void RenderWidgetHostImpl::ShowPopup(const gfx::Rect& initial_screen_rect, + const gfx::Rect& anchor_screen_rect, ShowPopupCallback callback) { delegate_->ShowCreatedWidget(GetProcess()->GetID(), GetRoutingID(), - initial_rect, anchor_rect); + initial_screen_rect, anchor_screen_rect); std::move(callback).Run(); }
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index 4c568e1..db807cca5 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -332,8 +332,8 @@ // blink::mojom::PopupWidgetHost implementation. void RequestClosePopup() override; - void ShowPopup(const gfx::Rect& initial_rect, - const gfx::Rect& anchor_rect, + void ShowPopup(const gfx::Rect& initial_screen_rect, + const gfx::Rect& anchor_screen_rect, ShowPopupCallback callback) override; void SetPopupBounds(const gfx::Rect& bounds, SetPopupBoundsCallback callback) override;
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index c56d5c0..fe70c30 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -248,9 +248,9 @@ } gfx::Rect RenderWidgetHostViewChildFrame::GetViewBounds() { - gfx::Rect rect; + gfx::Rect screen_space_rect; if (frame_connector_) { - rect = frame_connector_->screen_space_rect_in_dip(); + screen_space_rect = frame_connector_->rect_in_parent_view_in_dip(); RenderWidgetHostView* parent_view = frame_connector_->GetParentRenderWidgetHostView(); @@ -259,16 +259,16 @@ if (parent_view) { // Translate screen_space_rect by the parent's RenderWidgetHostView // offset. - rect.Offset(parent_view->GetViewBounds().OffsetFromOrigin()); + screen_space_rect.Offset(parent_view->GetViewBounds().OffsetFromOrigin()); } // TODO(wjmaclean): GetViewBounds is a bit of a mess. It's used to determine // the size of the renderer content and where to place context menus and so // on. We want the location of the frame in screen coordinates to place // popups but we want the size in local coordinates to produce the right- // sized CompositorFrames. https://crbug.com/928825. - rect.set_size(frame_connector_->local_frame_size_in_dip()); + screen_space_rect.set_size(frame_connector_->local_frame_size_in_dip()); } - return rect; + return screen_space_rect; } gfx::Size RenderWidgetHostViewChildFrame::GetVisibleViewportSize() {
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc b/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc index 87c60673..4d1d5f2 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame_unittest.cc
@@ -275,13 +275,11 @@ test_frame_connector_->SetLocalFrameSize(local_frame_size); EXPECT_EQ(local_frame_size, view_->GetCompositorViewportPixelSize()); - gfx::Rect screen_space_rect(local_frame_size); - screen_space_rect.set_origin(gfx::Point(230, 263)); - test_frame_connector_->SetScreenSpaceRect(screen_space_rect); + gfx::Rect rect_in_parent_view(local_frame_size); + rect_in_parent_view.set_origin(gfx::Point(230, 263)); + test_frame_connector_->SetRectInParentView(rect_in_parent_view); EXPECT_EQ(local_frame_size, view_->GetCompositorViewportPixelSize()); EXPECT_EQ(gfx::Point(115, 131), view_->GetViewBounds().origin()); - EXPECT_EQ(gfx::Point(230, 263), - test_frame_connector_->screen_space_rect_in_pixels().origin()); } // Tests that SynchronizeVisualProperties is called only once and all the @@ -295,14 +293,14 @@ widget_host_->RendererWidgetCreated(/*for_frame_widget=*/true); constexpr gfx::Rect compositor_viewport_pixel_rect(100, 100); - constexpr gfx::Rect screen_space_rect(compositor_viewport_pixel_rect); + constexpr gfx::Rect rect_in_local_root(compositor_viewport_pixel_rect); viz::ParentLocalSurfaceIdAllocator allocator; allocator.GenerateId(); viz::LocalSurfaceId local_surface_id = allocator.GetCurrentLocalSurfaceId(); blink::FrameVisualProperties visual_properties; visual_properties.screen_infos = display::ScreenInfos(display::ScreenInfo()); - visual_properties.screen_space_rect = screen_space_rect; + visual_properties.rect_in_local_root = rect_in_local_root; visual_properties.compositor_viewport = compositor_viewport_pixel_rect; visual_properties.local_frame_size = compositor_viewport_pixel_rect.size(); visual_properties.capture_sequence_number = 123u; @@ -322,7 +320,7 @@ EXPECT_EQ(compositor_viewport_pixel_rect, sent_visual_properties.compositor_viewport_pixel_rect); - EXPECT_EQ(screen_space_rect.size(), sent_visual_properties.new_size); + EXPECT_EQ(rect_in_local_root.size(), sent_visual_properties.new_size); EXPECT_EQ(local_surface_id, sent_visual_properties.local_surface_id); EXPECT_EQ(123u, sent_visual_properties.capture_sequence_number); EXPECT_EQ(1u, sent_visual_properties.root_widget_window_segments.size());
diff --git a/content/browser/service_process_host_browsertest.cc b/content/browser/service_process_host_browsertest.cc index 4d5e7a3..f45535b 100644 --- a/content/browser/service_process_host_browsertest.cc +++ b/content/browser/service_process_host_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/memory/shared_memory_mapping.h" #include "base/memory/unsafe_shared_memory_region.h" +#include "base/process/process.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/time/time.h" @@ -18,7 +19,6 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" - namespace content { using ServiceProcessHostBrowserTest = ContentBrowserTest; @@ -40,13 +40,13 @@ void WaitForCrash() { crash_loop_.Run(); } // Valid after WaitForLaunch. - base::ProcessId pid() const { return pid_; } + base::ProcessId pid() const { return process_.Pid(); } private: // ServiceProcessHost::Observer: void OnServiceProcessLaunched(const ServiceProcessInfo& info) override { if (info.IsService<echo::mojom::EchoService>()) { - pid_ = info.pid; + process_ = info.GetProcess().Duplicate(); launch_loop_.Quit(); } } @@ -65,7 +65,7 @@ base::RunLoop launch_loop_; base::RunLoop death_loop_; base::RunLoop crash_loop_; - base::ProcessId pid_ = base::kNullProcessId; + base::Process process_; }; IN_PROC_BROWSER_TEST_F(ServiceProcessHostBrowserTest, Launch) {
diff --git a/content/browser/service_process_host_impl.cc b/content/browser/service_process_host_impl.cc index f232eb49..5f89cc0 100644 --- a/content/browser/service_process_host_impl.cc +++ b/content/browser/service_process_host_impl.cc
@@ -10,6 +10,7 @@ #include "base/memory/weak_ptr.h" #include "base/no_destructor.h" #include "base/observer_list.h" +#include "base/process/process.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/threading/sequenced_task_runner_handle.h" @@ -20,11 +21,16 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/service_process_host.h" +#include "content/public/browser/service_process_info.h" #include "content/public/common/content_client.h" #include "mojo/public/cpp/bindings/generic_pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "sandbox/policy/mojom/sandbox.mojom.h" +#if BUILDFLAG(IS_CASTOS) || BUILDFLAG(IS_CAST_ANDROID) +#include "base/process/process_handle.h" +#endif + namespace content { namespace { @@ -48,17 +54,16 @@ ~ServiceProcessTracker() = default; - ServiceProcessInfo AddProcess(const base::Process& process, + ServiceProcessInfo AddProcess(base::Process process, const std::string& service_interface_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auto id = GenerateNextId(); - ServiceProcessInfo& info = processes_[id]; - info.service_process_id = id; - info.pid = process.Pid(); - info.service_interface_name = service_interface_name; + ServiceProcessInfo info(service_interface_name, id, std::move(process)); + auto info_dup = info.Duplicate(); + processes_.insert({id, std::move(info)}); for (auto& observer : observers_) - observer.OnServiceProcessLaunched(info); - return info; + observer.OnServiceProcessLaunched(info_dup); + return info_dup; } void NotifyTerminated(ServiceProcessId id) { @@ -67,7 +72,7 @@ DCHECK(iter != processes_.end()); for (auto& observer : observers_) - observer.OnServiceProcessTerminatedNormally(iter->second); + observer.OnServiceProcessTerminatedNormally(iter->second.Duplicate()); processes_.erase(iter); } @@ -76,7 +81,7 @@ auto iter = processes_.find(id); DCHECK(iter != processes_.end()); for (auto& observer : observers_) - observer.OnServiceProcessCrashed(iter->second); + observer.OnServiceProcessCrashed(iter->second.Duplicate()); processes_.erase(iter); } @@ -96,7 +101,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<ServiceProcessInfo> processes; for (const auto& entry : processes_) - processes.push_back(entry.second); + processes.push_back(entry.second.Duplicate()); return processes; } @@ -138,8 +143,8 @@ // UtilityProcessHost::Client: void OnProcessLaunched(const base::Process& process) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); - process_info_ = - GetServiceProcessTracker().AddProcess(process, service_interface_name_); + process_info_.emplace(GetServiceProcessTracker().AddProcess( + process.Duplicate(), service_interface_name_)); if (process_callback_) { std::move(process_callback_).Run(process); } @@ -147,7 +152,7 @@ void OnProcessTerminatedNormally() override { GetServiceProcessTracker().NotifyTerminated( - process_info_->service_process_id); + process_info_->service_process_id()); } void OnProcessCrashed() override { @@ -157,7 +162,8 @@ if (!process_info_) return; - GetServiceProcessTracker().NotifyCrashed(process_info_->service_process_id); + GetServiceProcessTracker().NotifyCrashed( + process_info_->service_process_id()); } private:
diff --git a/content/browser/site_per_process_layout_browsertest.cc b/content/browser/site_per_process_layout_browsertest.cc index 87552a9..aa7ee15 100644 --- a/content/browser/site_per_process_layout_browsertest.cc +++ b/content/browser/site_per_process_layout_browsertest.cc
@@ -1383,8 +1383,8 @@ // good way to avoid this due to various device-scale-factor. (e.g. when // dsf=3.375, ceil(round(50 * 3.375) / 3.375) = 51. Thus, we allow the screen // size in dip to be off by 1 here. - EXPECT_NEAR(50, connector->screen_space_rect_in_dip().size().width(), 1); - EXPECT_NEAR(50, connector->screen_space_rect_in_dip().size().height(), 1); + EXPECT_NEAR(50, connector->rect_in_parent_view_in_dip().size().width(), 1); + EXPECT_NEAR(50, connector->rect_in_parent_view_in_dip().size().height(), 1); EXPECT_EQ(gfx::Size(100, 100), rwhv_nested->GetViewBounds().size()); EXPECT_EQ(gfx::Size(100, 100), connector->local_frame_size_in_dip()); EXPECT_EQ(connector->local_frame_size_in_pixels(),
diff --git a/content/browser/site_per_process_oopsif_browsertest.cc b/content/browser/site_per_process_oopsif_browsertest.cc index ed4ce8b..da4b68f 100644 --- a/content/browser/site_per_process_oopsif_browsertest.cc +++ b/content/browser/site_per_process_oopsif_browsertest.cc
@@ -4,6 +4,7 @@ #include "content/browser/site_per_process_browsertest.h" +#include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test_utils.h" @@ -54,6 +55,66 @@ base::test::ScopedFeatureList feature_list_; }; +class SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest + : public SitePerProcessIsolatedSandboxedIframeTest { + public: + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest() { + feature_list_.InitAndEnableFeature(features::kIsolateSandboxedIframes); + } + + void SetUpCommandLine(base::CommandLine* command_line) override { + SitePerProcessIsolatedSandboxedIframeTest::SetUpCommandLine(command_line); + // Because this test derives from SitePerProcessBrowserTestBase which + // calls IsolateAllSitesForTesting, we need to manually remove the + // kSitePerProcess switch to simulate the environment where not all sites + // automatically get isolation. + command_line->RemoveSwitch(switches::kSitePerProcess); + } + + void SetUpOnMainThread() override { + SitePerProcessIsolatedSandboxedIframeTest::SetUpOnMainThread(); + + // Override BrowserClient to disable strict site isolation. + original_client_ = SetBrowserClientForTesting(&browser_client_); + // The custom ContentBrowserClient below typically ensures that this test + // runs without strict site isolation, but it's still possible to + // inadvertently override this when running with --site-per-process on the + // command line. This might happen on try bots, so these tests take this + // into account to prevent failures, but this is not an intended + // configuration for these tests, since isolating sandboxed iframes in + // these tests depends on use of default SiteInstances. + if (AreAllSitesIsolatedForTesting()) { + LOG(WARNING) << "This test should be run without --site-per-process, " + << "as it's designed to exercise code paths when strict " + << "site isolation is turned off."; + } + } + + void TearDownOnMainThread() override { + SitePerProcessIsolatedSandboxedIframeTest::TearDownOnMainThread(); + SetBrowserClientForTesting(original_client_); + } + + // A custom ContentBrowserClient to turn off strict site isolation, since + // isolated sandboxed iframes behave differently in environments like Android + // where it is not (generally) used. Note that kSitePerProcess is a + // higher-layer feature, so we can't just disable it here. + class PartialSiteIsolationContentBrowserClient : public ContentBrowserClient { + public: + bool ShouldEnableStrictSiteIsolation() override { return false; } + bool DoesSiteRequireDedicatedProcess( + BrowserContext* browser_context, + const GURL& effective_site_url) override { + return effective_site_url == GURL("http://isolated.com"); + } + }; + + private: + base::test::ScopedFeatureList feature_list_; + PartialSiteIsolationContentBrowserClient browser_client_; + raw_ptr<ContentBrowserClient> original_client_ = nullptr; +}; + // The following test should not crash. In this test the // kIsolateSandboxedIframes flag is forced off, so we don't need to verify // the process isolation details, as is done in @@ -816,6 +877,261 @@ grand_child->current_frame_host()->GetSiteInstance()); } +// A test to verify that an iframe with a fully-restrictive sandbox is rendered +// in the same process as its parent frame when the parent frame is in a +// default SiteInstance. +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + NotIsolatedSandbox) { + GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); + // The child needs to have the same origin as the parent. + GURL child_url(main_url); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + // Create sandboxed child frame, same-origin. + { + std::string js_str = base::StringPrintf( + "var frame = document.createElement('iframe'); " + "frame.sandbox = ''; " + "frame.src = '%s'; " + "document.body.appendChild(frame);", + child_url.spec().c_str()); + EXPECT_TRUE(ExecJs(shell(), js_str)); + ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); + } + + // Check frame-tree. + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* child = root->child_at(0); + auto* parent_site_instance = root->current_frame_host()->GetSiteInstance(); + auto* child_site_instance = child->current_frame_host()->GetSiteInstance(); + EXPECT_EQ(network::mojom::WebSandboxFlags::kAll, + child->effective_frame_policy().sandbox_flags); + EXPECT_FALSE(parent_site_instance->RequiresDedicatedProcess()); + EXPECT_EQ(parent_site_instance, child_site_instance); + EXPECT_FALSE(child_site_instance->GetSiteInfo().is_sandboxed()); +} + +// Similar to the NotIsolatedSandbox test, but using a site that requires a +// dedicated process, and thus resulting in a separate process for the sandboxed +// iframe. +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + IsolatedSandbox) { + // Specify an isolated.com site to get the main frame into a dedicated + // process. + GURL main_url(embedded_test_server()->GetURL("isolated.com", "/title1.html")); + // The child needs to have the same origin as the parent. + GURL child_url(main_url); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + // Create sandboxed child frame, same-origin. + { + std::string js_str = base::StringPrintf( + "var frame = document.createElement('iframe'); " + "frame.sandbox = ''; " + "frame.src = '%s'; " + "document.body.appendChild(frame);", + child_url.spec().c_str()); + EXPECT_TRUE(ExecJs(shell(), js_str)); + ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); + } + + // Check frame-tree. + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* child = root->child_at(0); + auto* parent_site_instance = root->current_frame_host()->GetSiteInstance(); + auto* child_site_instance = child->current_frame_host()->GetSiteInstance(); + EXPECT_EQ(network::mojom::WebSandboxFlags::kAll, + child->effective_frame_policy().sandbox_flags); + EXPECT_TRUE(parent_site_instance->RequiresDedicatedProcess()); + EXPECT_NE(parent_site_instance, child_site_instance); + EXPECT_NE(parent_site_instance->GetProcess(), + child_site_instance->GetProcess()); + EXPECT_TRUE(child_site_instance->GetSiteInfo().is_sandboxed()); +} + +// In this test, a main frame requests sandbox isolation for a site that would +// not normally be given a dedicated process. This causes the sandbox isolation +// request to fail. +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + CSPSandboxedMainFrame) { + GURL main_url(embedded_test_server()->GetURL( + "a.com", "/set-header?Content-Security-Policy: sandbox allow-scripts")); + GURL child_url(embedded_test_server()->GetURL("a.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + // Create sandboxed child frame, same-origin. + { + std::string js_str = base::StringPrintf( + "var frame = document.createElement('iframe'); " + "frame.sandbox = ''; " + "frame.src = '%s'; " + "document.body.appendChild(frame);", + child_url.spec().c_str()); + EXPECT_TRUE(ExecJs(shell(), js_str)); + ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); + } + + // Check frame-tree. + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* child = root->child_at(0); + auto* parent_site_instance = root->current_frame_host()->GetSiteInstance(); + auto* child_site_instance = child->current_frame_host()->GetSiteInstance(); + EXPECT_FALSE(parent_site_instance->RequiresDedicatedProcess()); + EXPECT_FALSE(parent_site_instance->GetSiteInfo().is_sandboxed()); + // TODO(wjmaclean): It seems weird that the + // effective_frame_policy().sandbox_flags don't get set in this case. Maybe + // worth investigating this at some point. https://crbug.com/1346723 + EXPECT_EQ(network::mojom::WebSandboxFlags::kNone, + root->effective_frame_policy().sandbox_flags); + // Since the parent is sandboxed, the child is same process to it. + EXPECT_EQ(parent_site_instance, child_site_instance); +} + +// Same as CSPSandboxedMainframe, but this time the site is isolatable on its +// own, so it gets the sandbox attribute via the CSP header. +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + CSPSandboxedMainframeIsolated) { + GURL main_url(embedded_test_server()->GetURL( + "isolated.com", + "/set-header?Content-Security-Policy: sandbox allow-scripts")); + GURL child_url( + embedded_test_server()->GetURL("isolated.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + // Create sandboxed child frame, same-origin. + { + std::string js_str = base::StringPrintf( + "var frame = document.createElement('iframe'); " + "frame.sandbox = ''; " + "frame.src = '%s'; " + "document.body.appendChild(frame);", + child_url.spec().c_str()); + EXPECT_TRUE(ExecJs(shell(), js_str)); + ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); + } + + // Check frame-tree. + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* child = root->child_at(0); + auto* parent_site_instance = root->current_frame_host()->GetSiteInstance(); + auto* child_site_instance = child->current_frame_host()->GetSiteInstance(); + EXPECT_TRUE(parent_site_instance->RequiresDedicatedProcess()); + EXPECT_TRUE(parent_site_instance->GetSiteInfo().is_sandboxed()); + // TODO(wjmaclean): It seems weird that the + // effective_frame_policy().sandbox_flags don't get set in this case. Maybe + // worth investigating this at some point. https://crbug.com/1346723 + EXPECT_EQ(network::mojom::WebSandboxFlags::kNone, + root->effective_frame_policy().sandbox_flags); + // Since the parent is sandboxed, the child is same process to it. + // Note: this assumes that we are running per-site isolation mode for isolated + // sandboxed iframes. + EXPECT_EQ(parent_site_instance, child_site_instance); +} + +// Test to verify which IsolationContext is used when a BrowsingInstance swap is +// performed during a navigation. +// Note: this test does not work as hoped, see comment before the final +// expectation of the test. +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + MainFrameBrowsingInstanceSwap) { + GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + scoped_refptr<SiteInstanceImpl> site_instance_a = + web_contents()->GetSiteInstance(); + EXPECT_FALSE(site_instance_a->GetSiteInfo().is_sandboxed()); + + // Force BrowsingInstance swap to a URL with a CSP sandbox header. + GURL isolated_url(embedded_test_server()->GetURL( + "b.com", "/set-header?Content-Security-Policy: sandbox")); + SiteInstance::StartIsolatingSite( + shell()->web_contents()->GetController().GetBrowserContext(), + isolated_url, + content::ChildProcessSecurityPolicy::IsolatedOriginSource::TEST); + EXPECT_TRUE(NavigateToURL(shell(), isolated_url)); + scoped_refptr<SiteInstanceImpl> site_instance_b = + web_contents()->GetSiteInstance(); + EXPECT_NE(site_instance_a, site_instance_b); + EXPECT_NE(site_instance_a->GetIsolationContext().browsing_instance_id(), + site_instance_b->GetIsolationContext().browsing_instance_id()); + // The SiteInstance is not considered sandboxed even in the new + // BrowsingInstance. This is not the result we wanted, but without a massive + // amount of work it's the best we can do. This happens because + // NavigationRequest::GetUrlInfo() doesn't know (at the time + // NavigationRequest::OnResponseStarted() calls + // RenderFrameHostManager::GetFrameHostForNavigation()) that there will be + // a BrowsingInstance swap, and it doesn't have access to the new + // BrowsingInstance (IsolationContext) when deciding to add the `is_sandboxed` + // attribute to UrlInfoInit. + // This is an edge case we can live with since it only happens with the + // main frame getting a CSP sandbox, and the main frame does get its own + // process regardless in this case. + EXPECT_FALSE(site_instance_b->GetSiteInfo().is_sandboxed()); +} + +IN_PROC_BROWSER_TEST_P( + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + MainFrameWithSandboxedOpener) { + // Specify an isolated.com site to get the main frame into a dedicated + // process. + GURL main_url(embedded_test_server()->GetURL("isolated.com", "/title1.html")); + // The child needs to have the same origin as the parent. + GURL child_url(main_url); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + // Create sandboxed child frame, same-origin. + { + std::string js_str = base::StringPrintf( + "var frame = document.createElement('iframe'); " + "frame.sandbox = 'allow-scripts allow-popups'; " + "frame.src = '%s'; " + "document.body.appendChild(frame);", + child_url.spec().c_str()); + EXPECT_TRUE(ExecJs(shell(), js_str)); + ASSERT_TRUE(WaitForLoadStop(shell()->web_contents())); + } + + // Check frame-tree. + FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root(); + ASSERT_EQ(1U, root->child_count()); + FrameTreeNode* child = root->child_at(0); + auto* parent_site_instance = root->current_frame_host()->GetSiteInstance(); + auto* child_site_instance = child->current_frame_host()->GetSiteInstance(); + network::mojom::WebSandboxFlags expected_flags = + network::mojom::WebSandboxFlags::kAll & + ~network::mojom::WebSandboxFlags::kScripts & + ~network::mojom::WebSandboxFlags::kPopups & + ~network::mojom::WebSandboxFlags::kAutomaticFeatures & + ~network::mojom::WebSandboxFlags::kTopNavigationToCustomProtocols; + EXPECT_EQ(expected_flags, child->effective_frame_policy().sandbox_flags); + EXPECT_TRUE(parent_site_instance->RequiresDedicatedProcess()); + EXPECT_NE(parent_site_instance, child_site_instance); + EXPECT_TRUE(child_site_instance->GetSiteInfo().is_sandboxed()); + + // Sandboxed child calls window.open. + Shell* new_shell = OpenPopup(child, child_url, ""); + EXPECT_TRUE(new_shell); + FrameTreeNode* new_root = + static_cast<WebContentsImpl*>(new_shell->web_contents()) + ->GetPrimaryFrameTree() + .root(); + auto* new_window_site_instance = + new_root->current_frame_host()->GetSiteInstance(); + EXPECT_TRUE(new_window_site_instance->RequiresDedicatedProcess()); + EXPECT_TRUE(new_window_site_instance->GetSiteInfo().is_sandboxed()); + // Note: this assumes per-site mode for sandboxed iframe isolation. If we + // settle on per-document mode, this will change to EXPECT_NE. + EXPECT_EQ(child_site_instance, new_window_site_instance); +} + INSTANTIATE_TEST_SUITE_P(All, SitePerProcessIsolatedSandboxedIframeTest, testing::ValuesIn(RenderDocumentFeatureLevelValues())); @@ -825,5 +1141,9 @@ INSTANTIATE_TEST_SUITE_P(All, SitePerProcessPerOriginIsolatedSandboxedIframeTest, testing::ValuesIn(RenderDocumentFeatureLevelValues())); +INSTANTIATE_TEST_SUITE_P( + All, + SitePerProcessIsolatedSandboxWithoutStrictSiteIsolationBrowserTest, + testing::ValuesIn(RenderDocumentFeatureLevelValues())); } // namespace content
diff --git a/content/browser/snapshot_browsertest.cc b/content/browser/snapshot_browsertest.cc index 54741d7..cae0da1 100644 --- a/content/browser/snapshot_browsertest.cc +++ b/content/browser/snapshot_browsertest.cc
@@ -214,7 +214,13 @@ // that the multi-window tests would never work on that platform. #if !BUILDFLAG(IS_ANDROID) -IN_PROC_BROWSER_TEST_F(SnapshotBrowserTest, SingleWindowTest) { +#if BUILDFLAG(IS_MAC) +// TODO(crbug.com/1347296): This test is flakey on macOS. +#define MAYBE_SingleWindowTest DISABLED_SingleWindowTest +#else +#define MAYBE_SingleWindowTest SingleWindowTest +#endif +IN_PROC_BROWSER_TEST_F(SnapshotBrowserTest, MAYBE_SingleWindowTest) { SetupTestServer(); content::RenderWidgetHostImpl* rwhi = GetRenderWidgetHostImpl(shell());
diff --git a/content/browser/webid/federated_auth_request_impl.cc b/content/browser/webid/federated_auth_request_impl.cc index b095af4..2951818 100644 --- a/content/browser/webid/federated_auth_request_impl.cc +++ b/content/browser/webid/federated_auth_request_impl.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/rand_util.h" #include "base/ranges/algorithm.h" +#include "base/strings/escape.h" #include "base/strings/string_piece.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" @@ -52,24 +53,26 @@ // TODO(cbiesinger): Determine what the right number is. static constexpr size_t kMaxProvidersInManifestList = 1ul; -std::string FormatRequestParamsWithoutScope(const std::string& client_id, - const std::string& nonce, - const std::string& account_id, - bool is_sign_in) { +std::string ComputeUrlEncodedTokenPostData(const std::string& client_id, + const std::string& nonce, + const std::string& account_id, + bool is_sign_in) { std::string query; if (!client_id.empty()) - query += "client_id=" + client_id; + query += + "client_id=" + base::EscapeUrlEncodedData(client_id, /*use_plus=*/true); if (!nonce.empty()) { if (!query.empty()) query += "&"; - query += "nonce=" + nonce; + query += "nonce=" + base::EscapeUrlEncodedData(nonce, /*use_plus=*/true); } if (!account_id.empty()) { if (!query.empty()) query += "&"; - query += "account_id=" + account_id; + query += "account_id=" + + base::EscapeUrlEncodedData(account_id, /*use_plus=*/true); } // For new users signing up, we show some disclosure text to remind them about // data sharing between IDP and RP. For returning users signing in, such @@ -776,8 +779,8 @@ network_manager_->SendTokenRequest( endpoints_.token, account_id_, - FormatRequestParamsWithoutScope(client_id_, nonce_, account_id, - is_sign_in), + ComputeUrlEncodedTokenPostData(client_id_, nonce_, account_id, + is_sign_in), base::BindOnce(&FederatedAuthRequestImpl::OnTokenResponseReceived, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/content/browser/webid/federated_auth_request_impl_unittest.cc b/content/browser/webid/federated_auth_request_impl_unittest.cc index 920925c..60daefb4 100644 --- a/content/browser/webid/federated_auth_request_impl_unittest.cc +++ b/content/browser/webid/federated_auth_request_impl_unittest.cc
@@ -159,7 +159,6 @@ bool delay_token_response; bool customized_dialog; bool wait_for_callback; - std::string post_request_body; }; static const MockClientIdConfiguration kDefaultClientMetadata{ @@ -184,8 +183,7 @@ FetchStatus::kSuccess, false /* delay_token_response */, false /* customized_dialog */, - true /* wait_for_callback */, - "" /* post_request_body */}; + true /* wait_for_callback */}; static const RequestExpectations kExpectationSuccess{ RequestTokenStatus::kSuccess, FederatedAuthRequestResult::kSuccess, @@ -321,9 +319,9 @@ void SendTokenRequest(const GURL& token_url, const std::string& account, - const std::string& request, + const std::string& url_encoded_post_data, TokenRequestCallback callback) override { - delegate_->SendTokenRequest(token_url, account, request, + delegate_->SendTokenRequest(token_url, account, url_encoded_post_data, std::move(callback)); } @@ -388,11 +386,8 @@ void SendTokenRequest(const GURL& token_url, const std::string& account, - const std::string& request, + const std::string& url_encoded_post_data, TokenRequestCallback callback) override { - if (!config_.post_request_body.empty()) { - EXPECT_EQ(config_.post_request_body, request); - } fetched_endpoints_ |= FetchedEndpoint::TOKEN; std::string delivered_token = config_.token_response == FetchStatus::kSuccess ? config_.token @@ -432,18 +427,22 @@ : public TestIdpNetworkRequestManager { public: void SetExpectations(const std::string& expected_client_id, - const std::string& expected_selected_account_id, - const std::string& expected_revocation_hint) { + const std::string& expected_selected_account_id) { expected_client_id_ = expected_client_id; expected_selected_account_id_ = expected_selected_account_id; - expected_revocation_hint_ = expected_revocation_hint; + } + + void SetExpectedTokenPostData( + const std::string& expected_url_encoded_post_data) { + expected_url_encoded_post_data_ = expected_url_encoded_post_data; } void FetchClientMetadata(const GURL& endpoint, const std::string& client_id, FetchClientMetadataCallback callback) override { EXPECT_EQ(config_.manifest.client_metadata_endpoint, endpoint); - EXPECT_EQ(expected_client_id_, client_id); + if (expected_client_id_) + EXPECT_EQ(expected_client_id_, client_id); TestIdpNetworkRequestManager::FetchClientMetadata(endpoint, client_id, std::move(callback)); } @@ -452,25 +451,29 @@ const std::string& client_id, AccountsRequestCallback callback) override { EXPECT_EQ(config_.manifest.accounts_endpoint, accounts_url); - EXPECT_EQ(expected_client_id_, client_id); + if (expected_client_id_) + EXPECT_EQ(expected_client_id_, client_id); TestIdpNetworkRequestManager::SendAccountsRequest(accounts_url, client_id, std::move(callback)); } void SendTokenRequest(const GURL& token_url, const std::string& account, - const std::string& request, + const std::string& url_encoded_post_data, TokenRequestCallback callback) override { EXPECT_EQ(config_.manifest.token_endpoint, token_url); - EXPECT_EQ(expected_selected_account_id_, account); - TestIdpNetworkRequestManager::SendTokenRequest(token_url, account, request, - std::move(callback)); + if (expected_selected_account_id_) + EXPECT_EQ(expected_selected_account_id_, account); + if (expected_url_encoded_post_data_) + EXPECT_EQ(expected_url_encoded_post_data_, url_encoded_post_data); + TestIdpNetworkRequestManager::SendTokenRequest( + token_url, account, url_encoded_post_data, std::move(callback)); } private: - std::string expected_client_id_; - std::string expected_selected_account_id_; - std::string expected_revocation_hint_; + absl::optional<std::string> expected_client_id_; + absl::optional<std::string> expected_selected_account_id_; + absl::optional<std::string> expected_url_encoded_post_data_; }; class TestApiPermissionDelegate : public MockApiPermissionDelegate { @@ -865,8 +868,7 @@ std::unique_ptr<IdpNetworkRequestManagerParamChecker> checker = std::make_unique<IdpNetworkRequestManagerParamChecker>(); checker->SetExpectations(kDefaultRequestParameters.client_id, - kConfigurationValid.accounts[0].id, - /* expected_revocation_hint=*/""); + kConfigurationValid.accounts[0].id); SetNetworkRequestManager(std::move(checker)); RunAuthTest(kDefaultRequestParameters, kExpectationSuccess, @@ -883,8 +885,7 @@ std::unique_ptr<IdpNetworkRequestManagerParamChecker> checker = std::make_unique<IdpNetworkRequestManagerParamChecker>(); checker->SetExpectations(kDefaultRequestParameters.client_id, - kConfigurationValid.accounts[0].id, - /* expected_revocation_hint=*/""); + kConfigurationValid.accounts[0].id); SetNetworkRequestManager(std::move(checker)); RunAuthTest(kDefaultRequestParameters, kExpectationSuccess, @@ -1838,18 +1839,21 @@ CheckAllFedCmSessionIDs(); } -// Test that disclosure text is shown for first time user. +// Test the disclosure_text_shown value in the token post data for sign-up case. TEST_F(BasicFederatedAuthRequestImplTest, DisclosureTextShownForFirstTimeUser) { - MockConfiguration configuration = kConfigurationValid; - configuration.post_request_body = + std::unique_ptr<IdpNetworkRequestManagerParamChecker> checker = + std::make_unique<IdpNetworkRequestManagerParamChecker>(); + checker->SetExpectedTokenPostData( "client_id=" + std::string(kClientId) + "&nonce=" + std::string(kNonce) + - "&account_id=" + std::string(kAccountId) + "&disclosure_text_shown=true"; + "&account_id=" + std::string(kAccountId) + "&disclosure_text_shown=true"); + SetNetworkRequestManager(std::move(checker)); RunAuthTest(kDefaultRequestParameters, kExpectationSuccess, kConfigurationValid); } -// Test that disclosure text is not shown for returning user. +// Test the disclosure_text_shown value in the token post data for returning +// user case. TEST_F(BasicFederatedAuthRequestImplTest, DisclosureTextNotShownForReturningUser) { // Pretend the sharing permission has been granted for this account. @@ -1859,10 +1863,31 @@ kAccountId)) .WillOnce(Return(true)); + std::unique_ptr<IdpNetworkRequestManagerParamChecker> checker = + std::make_unique<IdpNetworkRequestManagerParamChecker>(); + checker->SetExpectedTokenPostData("client_id=" + std::string(kClientId) + + "&nonce=" + std::string(kNonce) + + "&account_id=" + std::string(kAccountId) + + "&disclosure_text_shown=false"); + SetNetworkRequestManager(std::move(checker)); + + RunAuthTest(kDefaultRequestParameters, kExpectationSuccess, + kConfigurationValid); +} + +// Test that the values in the token post data are escaped according to the +// application/x-www-form-urlencoded spec. +TEST_F(BasicFederatedAuthRequestImplTest, TokenEndpointPostDataEscaping) { + const std::string kAccountIdWithSpace("account id"); MockConfiguration configuration = kConfigurationValid; - configuration.post_request_body = + configuration.accounts[0].id = kAccountIdWithSpace; + + std::unique_ptr<IdpNetworkRequestManagerParamChecker> checker = + std::make_unique<IdpNetworkRequestManagerParamChecker>(); + checker->SetExpectedTokenPostData( "client_id=" + std::string(kClientId) + "&nonce=" + std::string(kNonce) + - "&account_id=" + std::string(kAccountId) + "&disclosure_text_shown=false"; + "&account_id=account+id&disclosure_text_shown=true"); + SetNetworkRequestManager(std::move(checker)); RunAuthTest(kDefaultRequestParameters, kExpectationSuccess, configuration); }
diff --git a/content/browser/webid/idp_network_request_manager.cc b/content/browser/webid/idp_network_request_manager.cc index e00f826..703ce03 100644 --- a/content/browser/webid/idp_network_request_manager.cc +++ b/content/browser/webid/idp_network_request_manager.cc
@@ -90,7 +90,7 @@ constexpr char kRevokeRequestKey[] = "request"; // Body content types. -constexpr char kRequestBodyContentType[] = "application/x-www-form-urlencoded"; +constexpr char kUrlEncodedContentType[] = "application/x-www-form-urlencoded"; constexpr char kResponseBodyContentType[] = "application/json"; // 1 MiB is an arbitrary upper bound that should account for any reasonable @@ -638,18 +638,20 @@ maxResponseSizeInKiB * 1024); } -void IdpNetworkRequestManager::SendTokenRequest(const GURL& token_url, - const std::string& account, - const std::string& request, - TokenRequestCallback callback) { - if (request.empty()) { +void IdpNetworkRequestManager::SendTokenRequest( + const GURL& token_url, + const std::string& account, + const std::string& url_encoded_post_data, + TokenRequestCallback callback) { + if (url_encoded_post_data.empty()) { std::move(callback).Run(FetchStatus::kInvalidRequestError, std::string()); return; } std::unique_ptr<network::SimpleURLLoader> url_loader = CreateCredentialedUrlLoader(token_url, - /* send_referrer= */ true, request); + /* send_referrer= */ true, + url_encoded_post_data); DownloadJsonAndParse( std::move(url_loader), base::BindOnce(&OnTokenRequestParsed, std::move(callback)), @@ -784,22 +786,23 @@ IdpNetworkRequestManager::CreateCredentialedUrlLoader( const GURL& target_url, bool send_referrer, - absl::optional<std::string> request_body) const { + absl::optional<std::string> url_encoded_post_data) const { auto resource_request = CreateCredentialedResourceRequest( target_url, send_referrer, relying_party_origin_, client_security_state_.Clone()); - if (request_body) { + if (url_encoded_post_data) { resource_request->method = net::HttpRequestHeaders::kPostMethod; resource_request->headers.SetHeader(net::HttpRequestHeaders::kContentType, - kRequestBodyContentType); + kUrlEncodedContentType); } auto traffic_annotation = CreateTrafficAnnotation(); std::unique_ptr<network::SimpleURLLoader> loader = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); - if (request_body) - loader->AttachStringForUpload(*request_body, kRequestBodyContentType); + if (url_encoded_post_data) + loader->AttachStringForUpload(*url_encoded_post_data, + kUrlEncodedContentType); return loader; }
diff --git a/content/browser/webid/idp_network_request_manager.h b/content/browser/webid/idp_network_request_manager.h index 74ba378..369604c 100644 --- a/content/browser/webid/idp_network_request_manager.h +++ b/content/browser/webid/idp_network_request_manager.h
@@ -158,7 +158,7 @@ // Request a new token for this user account and RP from the IDP. virtual void SendTokenRequest(const GURL& token_url, const std::string& account, - const std::string& request, + const std::string& url_encoded_post_data, TokenRequestCallback callback); // Send logout request to a single target.
diff --git a/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc b/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc index 34a0807..098806d 100644 --- a/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc +++ b/content/browser/webrtc/webrtc_video_capture_service_browsertest.cc
@@ -543,7 +543,8 @@ }; // TODO(https://crbug.com/1318247): Fix and enable on Fuchsia. -#if BUILDFLAG(IS_FUCHSIA) +// TODO(https://crbug.com/1235254): This test is flakey on macOS. +#if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_MAC) #define MAYBE_FramesSentThroughTextureVirtualDeviceGetDisplayedOnPage \ DISABLED_FramesSentThroughTextureVirtualDeviceGetDisplayedOnPage #else
diff --git a/content/public/browser/audio_service_info.cc b/content/public/browser/audio_service_info.cc index e863832..2483f818 100644 --- a/content/public/browser/audio_service_info.cc +++ b/content/public/browser/audio_service_info.cc
@@ -4,6 +4,8 @@ #include "content/public/browser/audio_service_info.h" +#include "base/process/process.h" +#include "base/process/process_handle.h" #include "content/browser/browser_main_loop.h" #include "content/browser/renderer_host/media/audio_service_listener.h" #include "content/browser/renderer_host/media/media_stream_manager.h" @@ -20,7 +22,10 @@ MediaStreamManager* manager = BrowserMainLoop::GetInstance()->media_stream_manager(); - return manager->audio_service_listener()->GetProcessId(); + base::Process audio_process = manager->audio_service_listener()->GetProcess(); + if (audio_process.IsValid()) + return audio_process.Pid(); + return base::kNullProcessId; } } // namespace content
diff --git a/content/public/browser/host_zoom_map.h b/content/public/browser/host_zoom_map.h index ab515cf..652521a 100644 --- a/content/public/browser/host_zoom_map.h +++ b/content/public/browser/host_zoom_map.h
@@ -178,6 +178,16 @@ virtual void SetClockForTesting(base::Clock* clock) = 0; + // On Android only, set a callback for when the Java-side UI sets a default + // zoom level so the HostZoomMapImpl does not depend on Prefs or //chrome/. +#if BUILDFLAG(IS_ANDROID) + using DefaultZoomChangedCallback = + base::RepeatingCallback<void(double new_level)>; + + virtual void SetDefaultZoomLevelPrefCallback( + DefaultZoomChangedCallback callback) = 0; +#endif + protected: virtual ~HostZoomMap() {} };
diff --git a/content/public/browser/service_process_info.cc b/content/public/browser/service_process_info.cc index 8429cd8..b47c5a0 100644 --- a/content/public/browser/service_process_info.cc +++ b/content/public/browser/service_process_info.cc
@@ -4,12 +4,26 @@ #include "content/public/browser/service_process_info.h" +#include "base/process/process.h" + namespace content { -ServiceProcessInfo::ServiceProcessInfo() = default; +ServiceProcessInfo::ServiceProcessInfo(const std::string& name, + const ServiceProcessId& id, + base::Process process) + : service_interface_name_(name), + service_process_id_(id), + process_(std::move(process)) {} -ServiceProcessInfo::ServiceProcessInfo(const ServiceProcessInfo&) = default; +ServiceProcessInfo::ServiceProcessInfo(ServiceProcessInfo&&) = default; +ServiceProcessInfo& ServiceProcessInfo::operator=(ServiceProcessInfo&&) = + default; ServiceProcessInfo::~ServiceProcessInfo() = default; +ServiceProcessInfo ServiceProcessInfo::Duplicate() const { + return ServiceProcessInfo(service_interface_name_, service_process_id_, + process_.Duplicate()); +} + } // namespace content
diff --git a/content/public/browser/service_process_info.h b/content/public/browser/service_process_info.h index 75be1db..0be747d 100644 --- a/content/public/browser/service_process_info.h +++ b/content/public/browser/service_process_info.h
@@ -9,7 +9,7 @@ #include <string> -#include "base/process/process_handle.h" +#include "base/process/process.h" #include "base/types/id_type.h" #include "content/common/content_export.h" @@ -25,27 +25,51 @@ base::IdType<internal::ServiceProcessIdTypeMarker, uint64_t, 0u>; // Information about a running (or very recently running) service process. -struct CONTENT_EXPORT ServiceProcessInfo { - ServiceProcessInfo(); - ServiceProcessInfo(const ServiceProcessInfo&); +// +// This class is move-only but can be copied by calling the Duplicate() method. +// This is explicitly defined to prevent accidental copying, as the Duplicate() +// operation will call Duplicate() on the underlying base::Process. +class CONTENT_EXPORT ServiceProcessInfo { + public: + ServiceProcessInfo(const std::string& name, + const ServiceProcessId& id, + base::Process process); + ServiceProcessInfo(const ServiceProcessInfo&) = delete; + ServiceProcessInfo(ServiceProcessInfo&&); + ServiceProcessInfo& operator=(const ServiceProcessInfo&) = delete; + ServiceProcessInfo& operator=(ServiceProcessInfo&&); + ~ServiceProcessInfo(); // Template helper for testing whether this ServiceProcessInfo corresponds to // a service process launched to run the |Interface|. template <typename Interface> bool IsService() const { - return service_interface_name == Interface::Name_; + return service_interface_name_ == Interface::Name_; } + // Duplicates the ServiceProcessInfo since this struct is non-copyable. This + // Duplicates the underlying `process_`. + ServiceProcessInfo Duplicate() const; + + const ServiceProcessId service_process_id() const { + return service_process_id_; + } + const std::string service_interface_name() const { + return service_interface_name_; + } + const base::Process& GetProcess() const { return process_; } + + private: + // The name of the service interface for which the process was launched. + std::string service_interface_name_; + // A unique identifier for this service process instance. ServiceProcessIds // are never reused. - ServiceProcessId service_process_id; + ServiceProcessId service_process_id_; - // The system-dependent process ID of the service process. - base::ProcessId pid; - - // The name of the service interface for which the process was launched. - std::string service_interface_name; + // The service process. + base::Process process_; }; } // namespace content
diff --git a/content/public/browser/site_isolation_policy.cc b/content/public/browser/site_isolation_policy.cc index 17a06eed..c47582b 100644 --- a/content/public/browser/site_isolation_policy.cc +++ b/content/public/browser/site_isolation_policy.cc
@@ -140,16 +140,7 @@ // static bool SiteIsolationPolicy::AreIsolatedSandboxedIframesEnabled() { - // We repeat the call to IsSiteIsolationDisabled() below even though - // UseDedicatedProcessesForAllSites() also calls it, since the latter uses - // SiteIsolationMode::kStrictSiteIsolation instead of - // SiteIsolationMode::kPartialSiteIsolation. We have different memory - // thresholds for strict and partial site isolation. - // TODO(wjmaclean, alexmos): Remove the call to - // UseDedicatedProcessesForAllSites() in future when we make isolated - // sandboxed iframes work on Android. return !IsSiteIsolationDisabled(SiteIsolationMode::kPartialSiteIsolation) && - UseDedicatedProcessesForAllSites() && base::FeatureList::IsEnabled(features::kIsolateSandboxedIframes); }
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index 4168eed..db811839 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -3926,7 +3926,7 @@ SynchronizeVisualPropertiesInterceptor::SynchronizeVisualPropertiesInterceptor( RenderFrameProxyHost* render_frame_proxy_host) : render_frame_proxy_host_(render_frame_proxy_host), - screen_space_rect_run_loop_(std::make_unique<base::RunLoop>()), + local_root_rect_run_loop_(std::make_unique<base::RunLoop>()), swapped_impl_(render_frame_proxy_host_->frame_host_receiver_for_testing(), this) {} @@ -3939,13 +3939,13 @@ } void SynchronizeVisualPropertiesInterceptor::WaitForRect() { - screen_space_rect_run_loop_->Run(); + local_root_rect_run_loop_->Run(); } void SynchronizeVisualPropertiesInterceptor::ResetRectRunLoop() { last_rect_ = gfx::Rect(); - screen_space_rect_run_loop_ = std::make_unique<base::RunLoop>(); - screen_space_rect_received_ = false; + local_root_rect_run_loop_ = std::make_unique<base::RunLoop>(); + local_root_rect_received_ = false; } viz::LocalSurfaceId SynchronizeVisualPropertiesInterceptor::WaitForSurfaceId() { @@ -3970,21 +3970,21 @@ } last_pinch_gesture_active_ = visual_properties.is_pinch_gesture_active; - gfx::Rect screen_space_rect_in_dip = visual_properties.screen_space_rect; + gfx::Rect local_root_rect_in_dip = visual_properties.rect_in_local_root; const float dsf = visual_properties.screen_infos.current().device_scale_factor; - screen_space_rect_in_dip = + local_root_rect_in_dip = gfx::Rect(gfx::ScaleToFlooredPoint( - visual_properties.screen_space_rect.origin(), 1.f / dsf), + visual_properties.rect_in_local_root.origin(), 1.f / dsf), gfx::ScaleToCeiledSize( - visual_properties.screen_space_rect.size(), 1.f / dsf)); + visual_properties.rect_in_local_root.size(), 1.f / dsf)); // Track each rect updates. GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &SynchronizeVisualPropertiesInterceptor::OnUpdatedFrameRectOnUI, - weak_factory_.GetWeakPtr(), screen_space_rect_in_dip)); + weak_factory_.GetWeakPtr(), local_root_rect_in_dip)); // Track each surface id update. GetUIThreadTaskRunner({})->PostTask( @@ -4007,11 +4007,11 @@ void SynchronizeVisualPropertiesInterceptor::OnUpdatedFrameRectOnUI( const gfx::Rect& rect) { last_rect_ = rect; - if (!screen_space_rect_received_) { - screen_space_rect_received_ = true; + if (!local_root_rect_received_) { + local_root_rect_received_ = true; // Tests looking at the rect currently expect all received input to finish // processing before the test continutes. - screen_space_rect_run_loop_->QuitWhenIdle(); + local_root_rect_run_loop_->QuitWhenIdle(); } }
diff --git a/content/public/test/browser_test_utils.h b/content/public/test/browser_test_utils.h index 04d850a..516af00 100644 --- a/content/public/test/browser_test_utils.h +++ b/content/public/test/browser_test_utils.h
@@ -2072,8 +2072,8 @@ raw_ptr<RenderFrameProxyHost> render_frame_proxy_host_; - std::unique_ptr<base::RunLoop> screen_space_rect_run_loop_; - bool screen_space_rect_received_ = false; + std::unique_ptr<base::RunLoop> local_root_rect_run_loop_; + bool local_root_rect_received_ = false; gfx::Rect last_rect_; viz::LocalSurfaceId last_surface_id_;
diff --git a/content/renderer/accessibility/blink_ax_tree_source.cc b/content/renderer/accessibility/blink_ax_tree_source.cc index ae94a591..accac1c 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.cc +++ b/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -88,6 +88,56 @@ } #endif +// Helper function that searches in the subtree of |obj| to a max +// depth of |max_depth| for an image. +// +// Returns true on success, or false if it finds more than one image, +// or any node with a name, or anything deeper than |max_depth|. +bool SearchForExactlyOneInnerImage(WebAXObject obj, + WebAXObject* inner_image, + int max_depth) { + DCHECK(inner_image); + + // If it's the first image, set |inner_image|. If we already + // found an image, fail. + if (ui::IsImage(obj.Role())) { + if (!inner_image->IsDetached()) + return false; + *inner_image = obj; + } else { + // If we found something else with a name, fail. + if (!ui::IsPlatformDocument(obj.Role()) && !ui::IsLink(obj.Role())) { + blink::WebString web_name = obj.GetName(); + if (!base::ContainsOnlyChars(web_name.Utf8(), base::kWhitespaceASCII)) { + return false; + } + } + } + + // Fail if we recursed to |max_depth| and there's more of a subtree. + if (max_depth == 0 && obj.ChildCount()) + return false; + + // Don't count ignored nodes toward depth. + int next_depth = obj.AccessibilityIsIgnored() ? max_depth : max_depth - 1; + + // Recurse. + for (unsigned int i = 0; i < obj.ChildCount(); i++) { + if (!SearchForExactlyOneInnerImage(obj.ChildAt(i), inner_image, next_depth)) + return false; + } + + return !inner_image->IsDetached(); +} + +// Return true if the subtree of |obj|, to a max depth of 3, contains +// exactly one image. Return that image in |inner_image|. +bool FindExactlyOneInnerImageInMaxDepthThree(WebAXObject obj, + WebAXObject* inner_image) { + DCHECK(inner_image); + return SearchForExactlyOneInnerImage(obj, inner_image, /* max_depth = */ 3); +} + // Ignore code that limits based on the protocol (like https, file, etc.) // to enable tests to run. bool g_ignore_protocol_checks_for_testing; @@ -416,6 +466,20 @@ return; } + if (ui::IsImage(dst->role)) + AddImageAnnotations(src, dst); + + // If a link or web area isn't otherwise labeled and contains exactly one + // image (searching only to a max depth of 2), and the link doesn't have + // accessible text from an attribute like aria-label, then annotate the + // link/web area with the image's annotation, too. + if ((ui::IsLink(dst->role) || ui::IsPlatformDocument(dst->role)) && + dst->GetNameFrom() != ax::mojom::NameFrom::kAttribute) { + WebAXObject inner_image; + if (FindExactlyOneInnerImageInMaxDepthThree(src, &inner_image)) + AddImageAnnotations(inner_image, dst); + } + if (dst->id == image_data_node_id_) { // In general, string attributes should be truncated using // TruncateAndAddStringAttribute, but ImageDataUrl contains a data url
diff --git a/content/renderer/accessibility/blink_ax_tree_source.h b/content/renderer/accessibility/blink_ax_tree_source.h index 89f2175..6a6d82b 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.h +++ b/content/renderer/accessibility/blink_ax_tree_source.h
@@ -123,8 +123,6 @@ // to enable tests to run. static void IgnoreProtocolChecksForTesting(); - void AddImageAnnotations(blink::WebAXObject& src, ui::AXNodeData* dst) const; - private: const blink::WebDocument& document() const { DCHECK(frozen_); @@ -152,6 +150,8 @@ const std::string& value, uint32_t max_len = kMaxStringAttributeLength) const; + void AddImageAnnotations(blink::WebAXObject& src, ui::AXNodeData* dst) const; + RenderFrameImpl* render_frame_; ui::AXMode accessibility_mode_;
diff --git a/content/renderer/accessibility/render_accessibility_impl.cc b/content/renderer/accessibility/render_accessibility_impl.cc index c56265c..9b1a8011 100644 --- a/content/renderer/accessibility/render_accessibility_impl.cc +++ b/content/renderer/accessibility/render_accessibility_impl.cc
@@ -489,11 +489,6 @@ ScheduleSendPendingAccessibilityEvents(); } -void RenderAccessibilityImpl::AddImageAnnotations(WebAXObject& obj, - ui::AXNodeData* dst) { - tree_source_->AddImageAnnotations(obj, dst); -} - void RenderAccessibilityImpl::HandleAXEvent(const ui::AXEvent& event) { const WebDocument& document = GetMainDocument(); if (document.IsNull())
diff --git a/content/renderer/accessibility/render_accessibility_impl.h b/content/renderer/accessibility/render_accessibility_impl.h index b117804..7dddbdd5 100644 --- a/content/renderer/accessibility/render_accessibility_impl.h +++ b/content/renderer/accessibility/render_accessibility_impl.h
@@ -131,7 +131,6 @@ ax::mojom::Action event_from_action = ax::mojom::Action::kNone, std::vector<ui::AXEventIntent> event_intents = {}, ax::mojom::Event event_type = ax::mojom::Event::kNone); - void AddImageAnnotations(blink::WebAXObject&, ui::AXNodeData* dst); // Returns the main top-level document for this page, or NULL if there's // no view or frame.
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 6c5caf05..e15253f 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -4513,15 +4513,6 @@ ->MarkWebAXObjectDirty(obj, subtree, event_from, event_from_action); } -void RenderFrameImpl::AddImageAnnotations(blink::WebAXObject& obj, - ui::AXNodeData* dst) { - if (!IsAccessibilityEnabled()) - return; - - render_accessibility_manager_->GetRenderAccessibilityImpl() - ->AddImageAnnotations(obj, dst); -} - void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) { observers_.AddObserver(observer); }
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 056e256..0898048 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -618,7 +618,6 @@ bool subtree, ax::mojom::EventFrom event_from, ax::mojom::Action event_from_action) override; - void AddImageAnnotations(blink::WebAXObject&, ui::AXNodeData* dst) override; void CheckIfAudioSinkExistsAndIsAuthorized( const blink::WebString& sink_id, blink::WebSetSinkIdCompleteCallback callback) override;
diff --git a/content/test/gpu/gpu_tests/pixel_test_pages.py b/content/test/gpu/gpu_tests/pixel_test_pages.py index f908d36..af19d7f 100644 --- a/content/test/gpu/gpu_tests/pixel_test_pages.py +++ b/content/test/gpu/gpu_tests/pixel_test_pages.py
@@ -1176,18 +1176,24 @@ ] @staticmethod - def ForceFullDamagePages(base_name: str) -> List[PixelTestPage]: + def RootSwapChainPages(base_name: str) -> List[PixelTestPage]: return [ PixelTestPage( 'wait_for_compositing.html', base_name + '_ForceFullDamage', test_rect=[0, 0, 0, 0], - other_args={'full_damage': True}, + other_args={ + 'has_alpha': False, + 'full_damage': True + }, browser_args=[cba.ENABLE_DIRECT_COMPOSITION_FORCE_FULL_DAMAGE]), PixelTestPage( 'wait_for_compositing.html', base_name + '_ForcePartialDamage', test_rect=[0, 0, 0, 0], - other_args={'full_damage': False}, + other_args={ + 'has_alpha': False, + 'full_damage': False + }, browser_args=[cba.DISABLE_DIRECT_COMPOSITION_FORCE_FULL_DAMAGE]), ]
diff --git a/content/test/gpu/gpu_tests/test_expectations/webgl2_conformance_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/webgl2_conformance_expectations.txt index 7f068578..c0eb4d4 100644 --- a/content/test/gpu/gpu_tests/test_expectations/webgl2_conformance_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/webgl2_conformance_expectations.txt
@@ -864,7 +864,9 @@ crbug.com/1218162 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/uniformbuffers/single_basic_type.html [ Failure ] crbug.com/1218169 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fragmentoutput/array.float.html [ Failure ] crbug.com/1218169 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fragmentoutput/basic.float.html [ Failure ] -crbug.com/1218509 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fbomultisample.8_samples.html [ Failure ] +crbug.com/1218509 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fbomultisample.2_samples.html [ RetryOnFailure ] +crbug.com/1218509 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fbomultisample.4_samples.html [ RetryOnFailure ] +crbug.com/1218509 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/fbomultisample.8_samples.html [ RetryOnFailure ] crbug.com/1218512 [ chromeos chromeos-board-kevin ] deqp/functional/gles3/shadertexturefunction/texturelodoffset.html [ Failure ] crbug.com/1218516 [ chromeos chromeos-board-kevin ] deqp/data/gles3/shaders/arrays.html [ Failure ] crbug.com/1218607 [ chromeos chromeos-board-kevin ] conformance2/reading/read-pixels-pack-parameters.html [ Failure ]
diff --git a/content/test/gpu/gpu_tests/trace_integration_test.py b/content/test/gpu/gpu_tests/trace_integration_test.py index ac82d715..2e4cefa 100644 --- a/content/test/gpu/gpu_tests/trace_integration_test.py +++ b/content/test/gpu/gpu_tests/trace_integration_test.py
@@ -105,7 +105,7 @@ _GET_STATISTICS_EVENT_NAME = 'GetFrameStatisticsMedia' _SWAP_CHAIN_PRESENT_EVENT_NAME = 'SwapChain::Present' _PRESENT_TO_SWAP_CHAIN_EVENT_NAME = 'SwapChainPresenter::PresentToSwapChain' -_PRESENT_MAIN_SWAP_CHAIN_EVENT_NAME =\ +_PRESENT_ROOT_SWAP_CHAIN_EVENT_NAME =\ 'DirectCompositionChildSurfaceWin::PresentSwapChain' _SUPPORTED_WIN_AMD_GPUS_WITH_NV12_ROTATED_OVERLAYS = [0x7340] @@ -183,14 +183,14 @@ success_eval_func='CheckOverlayMode', other_args=p.other_args) ]) - for p in namespace.ForceFullDamagePages('SwapChainTraceTest'): + for p in namespace.RootSwapChainPages('SwapChainTraceTest'): yield (p.name, posixpath.join(gpu_data_relative_path, p.url), [ _TraceTestArguments( browser_args=p.browser_args, category='gpu', test_harness_script=basic_test_harness_script, finish_js_condition='domAutomationController._finished', - success_eval_func='CheckMainSwapChainPath', + success_eval_func='CheckRootSwapChainPath', other_args=p.other_args) ]) for p in namespace.WebGPUCanvasCapturePages('WebGPUTraceTest'): @@ -512,7 +512,7 @@ 'Overlay not expected but found: matching %s events were found' % _PRESENT_TO_SWAP_CHAIN_EVENT_NAME) - def _EvaluateSuccess_CheckMainSwapChainPath(self, category: str, + def _EvaluateSuccess_CheckRootSwapChainPath(self, category: str, event_iterator: Iterator, other_args: dict) -> None: """Verified that Chrome's main swap chain is presented with full damage.""" @@ -525,6 +525,7 @@ assert overlay_bot_config.get('direct_composition', False) expect_full_damage = other_args and other_args.get('full_damage', False) + expect_has_alpha = other_args and other_args.get('has_alpha', False) partial_damage_encountered = False full_damage_encountered = False @@ -532,24 +533,31 @@ for event in event_iterator: if event.category != category: continue - if event.name != _PRESENT_MAIN_SWAP_CHAIN_EVENT_NAME: + if event.name != _PRESENT_ROOT_SWAP_CHAIN_EVENT_NAME: continue dirty_rect = event.args.get('dirty_rect', None) - if dirty_rect is None: - continue - if dirty_rect == 'full_damage': - full_damage_encountered = True - else: - partial_damage_encountered = True + if dirty_rect is not None: + if dirty_rect == 'full_damage': + full_damage_encountered = True + else: + partial_damage_encountered = True + + got_has_alpha = event.args.get('has_alpha', None) + if got_has_alpha is not None and expect_has_alpha != got_has_alpha: + self.fail( + 'Expected events with name %s with has_alpha expected %s, got %s' % + (_PRESENT_ROOT_SWAP_CHAIN_EVENT_NAME, expect_has_alpha, + got_has_alpha)) # Today Chrome either run with full damage or partial damage, but not both. # This may change in the future. if (expect_full_damage != full_damage_encountered or expect_full_damage == partial_damage_encountered): self.fail('Expected events with name %s of %s, got others' % - (_PRESENT_MAIN_SWAP_CHAIN_EVENT_NAME, + (_PRESENT_ROOT_SWAP_CHAIN_EVENT_NAME, 'full damage' if expect_full_damage else 'partial damage')) + def _EvaluateSuccess_CheckWebGPUCanvasCapture(self, category: str, event_iterator: Iterator, other_args: dict) -> None:
diff --git a/extensions/browser/extension_prefs.cc b/extensions/browser/extension_prefs.cc index 5efa4e100..efcbe38 100644 --- a/extensions/browser/extension_prefs.cc +++ b/extensions/browser/extension_prefs.cc
@@ -1370,16 +1370,6 @@ return DoesExtensionHaveState(id, Extension::DISABLED); } -ExtensionIdList ExtensionPrefs::GetToolbarOrder() const { - ExtensionIdList id_list_out; - GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out); - return id_list_out; -} - -void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) { - SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids); -} - ExtensionIdList ExtensionPrefs::GetPinnedExtensions() const { ExtensionIdList id_list_out; GetUserExtensionPrefIntoContainer(pref_names::kPinnedExtensions, @@ -2279,8 +2269,6 @@ void ExtensionPrefs::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterDictionaryPref(pref_names::kExtensions); - registry->RegisterListPref(pref_names::kToolbar, - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(pref_names::kPinnedExtensions, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterListPref(pref_names::kDeletedComponentExtensions);
diff --git a/extensions/browser/extension_prefs.h b/extensions/browser/extension_prefs.h index 0148db6c..1fc01cf 100644 --- a/extensions/browser/extension_prefs.h +++ b/extensions/browser/extension_prefs.h
@@ -202,11 +202,6 @@ // Note that blocklisted extensions are NOT marked as disabled! bool IsExtensionDisabled(const std::string& id) const; - // Get/Set the order that the browser actions appear in the toolbar. - // TODO(devlin): Remove this. The pref is no longer used. - ExtensionIdList GetToolbarOrder() const; - void SetToolbarOrder(const ExtensionIdList& extension_ids); - // Get/Set the set of extensions that are pinned to the toolbar. Only used // when the experiment ExtensionsMenu is active." // TODO(crbug.com/943702): Remove reference to experiment when it launches or
diff --git a/extensions/browser/guest_view/app_view/app_view_guest.cc b/extensions/browser/guest_view/app_view/app_view_guest.cc index 46d69b3..90d4942 100644 --- a/extensions/browser/guest_view/app_view/app_view_guest.cc +++ b/extensions/browser/guest_view/app_view/app_view_guest.cc
@@ -107,16 +107,15 @@ AppViewGuest::AppViewGuest(WebContents* owner_web_contents) : GuestView<AppViewGuest>(owner_web_contents), - app_view_guest_delegate_( - ExtensionsAPIClient::Get()->CreateAppViewGuestDelegate()) { + app_view_guest_delegate_(base::WrapUnique( + ExtensionsAPIClient::Get()->CreateAppViewGuestDelegate())) { if (app_view_guest_delegate_) { - app_delegate_.reset( + app_delegate_ = base::WrapUnique( app_view_guest_delegate_->CreateAppDelegate(owner_web_contents)); } } -AppViewGuest::~AppViewGuest() { -} +AppViewGuest::~AppViewGuest() = default; bool AppViewGuest::HandleContextMenu( content::RenderFrameHost& render_frame_host,
diff --git a/extensions/browser/guest_view/app_view/app_view_guest.h b/extensions/browser/guest_view/app_view/app_view_guest.h index 7a40ac4..e96e1e7f 100644 --- a/extensions/browser/guest_view/app_view/app_view_guest.h +++ b/extensions/browser/guest_view/app_view/app_view_guest.h
@@ -27,6 +27,8 @@ AppViewGuest(const AppViewGuest&) = delete; AppViewGuest& operator=(const AppViewGuest&) = delete; + static GuestViewBase* Create(content::WebContents* owner_web_contents); + // Completes the creation of a WebContents associated with the provided // |guest_extension_id| and |guest_instance_id| for the given // |browser_context|. @@ -43,8 +45,6 @@ const std::string& guest_extension_id, content::RenderProcessHost* guest_render_process_host); - static GuestViewBase* Create(content::WebContents* owner_web_contents); - static std::vector<int> GetAllRegisteredInstanceIdsForTesting(); // Sets the AppDelegate for this guest.
diff --git a/extensions/browser/guest_view/extension_options/extension_options_guest.cc b/extensions/browser/guest_view/extension_options/extension_options_guest.cc index cf38ea90..9265f761 100644 --- a/extensions/browser/guest_view/extension_options/extension_options_guest.cc +++ b/extensions/browser/guest_view/extension_options/extension_options_guest.cc
@@ -50,8 +50,7 @@ extensions::ExtensionsAPIClient::Get() ->CreateExtensionOptionsGuestDelegate(this)) {} -ExtensionOptionsGuest::~ExtensionOptionsGuest() { -} +ExtensionOptionsGuest::~ExtensionOptionsGuest() = default; // static GuestViewBase* ExtensionOptionsGuest::Create(WebContents* owner_web_contents) {
diff --git a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc index ed5510d..11576c1f 100644 --- a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc +++ b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc
@@ -43,8 +43,8 @@ : context_(context) { } -ExtensionsGuestViewManagerDelegate::~ExtensionsGuestViewManagerDelegate() { -} +ExtensionsGuestViewManagerDelegate::~ExtensionsGuestViewManagerDelegate() = + default; void ExtensionsGuestViewManagerDelegate::OnGuestAdded( content::WebContents* guest_web_contents) const { @@ -120,12 +120,21 @@ GetExtensionForWebContents(guest->owner_web_contents()); } -void ExtensionsGuestViewManagerDelegate::RegisterAdditionalGuestViewTypes() { - GuestViewManager* manager = GuestViewManager::FromBrowserContext(context_); - manager->RegisterGuestViewType<AppViewGuest>(); - manager->RegisterGuestViewType<ExtensionOptionsGuest>(); - manager->RegisterGuestViewType<MimeHandlerViewGuest>(); - manager->RegisterGuestViewType<WebViewGuest>(); +void ExtensionsGuestViewManagerDelegate::RegisterAdditionalGuestViewTypes( + GuestViewManager* manager) { + manager->RegisterGuestViewType(AppViewGuest::Type, + base::BindRepeating(&AppViewGuest::Create), + base::NullCallback()); + manager->RegisterGuestViewType( + ExtensionOptionsGuest::Type, + base::BindRepeating(&ExtensionOptionsGuest::Create), + base::NullCallback()); + manager->RegisterGuestViewType( + MimeHandlerViewGuest::Type, + base::BindRepeating(&MimeHandlerViewGuest::Create), base::NullCallback()); + manager->RegisterGuestViewType(WebViewGuest::Type, + base::BindRepeating(&WebViewGuest::Create), + base::BindRepeating(&WebViewGuest::CleanUp)); } } // namespace extensions
diff --git a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.h b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.h index 14558d6..126e086 100644 --- a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.h +++ b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.h
@@ -30,7 +30,8 @@ int instance_id) override; bool IsGuestAvailableToContext(guest_view::GuestViewBase* guest) override; bool IsOwnedByExtension(guest_view::GuestViewBase* guest) override; - void RegisterAdditionalGuestViewTypes() override; + void RegisterAdditionalGuestViewTypes( + guest_view::GuestViewManager* manager) override; private: const raw_ptr<content::BrowserContext> context_;
diff --git a/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc b/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc index 4505e5c..2830d57 100644 --- a/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc +++ b/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/time/time.h" +#include "components/guest_view/browser/test_guest_view_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_utils.h" @@ -18,7 +19,16 @@ content::WebContents* owner_web_contents) : MimeHandlerViewGuest(owner_web_contents) {} -TestMimeHandlerViewGuest::~TestMimeHandlerViewGuest() {} +TestMimeHandlerViewGuest::~TestMimeHandlerViewGuest() = default; + +// static +void TestMimeHandlerViewGuest::RegisterTestGuestViewType( + guest_view::TestGuestViewManager* manager) { + manager->RegisterGuestViewType( + TestMimeHandlerViewGuest::Type, + base::BindRepeating(&TestMimeHandlerViewGuest::Create), + base::NullCallback()); +} // static GuestViewBase* TestMimeHandlerViewGuest::Create(
diff --git a/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.h b/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.h index 57d0dd688..dc25b73 100644 --- a/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.h +++ b/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.h
@@ -13,6 +13,10 @@ class MessageLoopRunner; } // namespace content +namespace guest_view { +class TestGuestViewManager; +} // namespace guest_view + namespace extensions { // TestMimeHandlerViewGuest is used instead of its base class, @@ -23,6 +27,11 @@ TestMimeHandlerViewGuest(const TestMimeHandlerViewGuest&) = delete; TestMimeHandlerViewGuest& operator=(const TestMimeHandlerViewGuest&) = delete; + // Have `manager` create TestMimeHandlerViewGuests in place of + // MimeHandlerViewGuests. + static void RegisterTestGuestViewType( + guest_view::TestGuestViewManager* manager); + static GuestViewBase* Create(content::WebContents* owner_web_contents); // Set a delay in the next creation of a guest's WebContents by |delay|
diff --git a/extensions/browser/guest_view/web_view/web_view_guest.cc b/extensions/browser/guest_view/web_view/web_view_guest.cc index 5838b003..49dc39d1 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.cc +++ b/extensions/browser/guest_view/web_view/web_view_guest.cc
@@ -237,9 +237,6 @@ void WebViewGuest::CleanUp(content::BrowserContext* browser_context, int embedder_process_id, int view_instance_id) { - GuestViewBase::CleanUp(browser_context, embedder_process_id, - view_instance_id); - // Clean up rules registries for the WebView. WebViewKey key(embedder_process_id, view_instance_id); auto it = web_view_key_to_id_map.Get().find(key); @@ -761,24 +758,14 @@ : GuestView<WebViewGuest>(owner_web_contents), rules_registry_id_(RulesRegistryService::kInvalidRulesRegistryID), find_helper_(this), - is_overriding_user_agent_(false), - allow_transparency_(false), javascript_dialog_helper_(this), - allow_scaling_(false), - is_guest_fullscreen_(false), - is_embedder_fullscreen_(false), - last_fullscreen_permission_was_allowed_by_embedder_(false), - pending_zoom_factor_(0.0), - did_set_explicit_zoom_(false), + web_view_guest_delegate_(base::WrapUnique( + ExtensionsAPIClient::Get()->CreateWebViewGuestDelegate(this))), is_spatial_navigation_enabled_( base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableSpatialNavigation)) { - web_view_guest_delegate_.reset( - ExtensionsAPIClient::Get()->CreateWebViewGuestDelegate(this)); -} + switches::kEnableSpatialNavigation)) {} -WebViewGuest::~WebViewGuest() { -} +WebViewGuest::~WebViewGuest() = default; void WebViewGuest::DidFinishNavigation( content::NavigationHandle* navigation_handle) {
diff --git a/extensions/browser/guest_view/web_view/web_view_guest.h b/extensions/browser/guest_view/web_view/web_view_guest.h index ffb9a2c..80f436e 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.h +++ b/extensions/browser/guest_view/web_view/web_view_guest.h
@@ -39,13 +39,16 @@ WebViewGuest(const WebViewGuest&) = delete; WebViewGuest& operator=(const WebViewGuest&) = delete; - // Clean up state when this GuestView is being destroyed. See - // GuestViewBase::CleanUp(). + static GuestViewBase* Create(content::WebContents* owner_web_contents); + // Cleans up state when this GuestView is being destroyed. + // Note that this cannot be done in the destructor since a GuestView could + // potentially be created and destroyed in JavaScript before getting a + // GuestViewBase instance. static void CleanUp(content::BrowserContext* browser_context, int embedder_process_id, int view_instance_id); - static GuestViewBase* Create(content::WebContents* owner_web_contents); + static const char Type[]; // Returns the WebView partition ID associated with the render process // represented by |render_process_host|, if any. Otherwise, an empty string is @@ -53,8 +56,6 @@ static std::string GetPartitionID( content::RenderProcessHost* render_process_host); - static const char Type[]; - // Returns the stored rules registry ID of the given webview. Will generate // an ID for the first query. static int GetOrGenerateRulesRegistryID( @@ -316,13 +317,13 @@ std::unique_ptr<ScriptExecutor> script_executor_; // True if the user agent is overridden. - bool is_overriding_user_agent_; + bool is_overriding_user_agent_ = false; // Stores the window name of the main frame of the guest. std::string name_; // Stores whether the contents of the guest can be transparent. - bool allow_transparency_; + bool allow_transparency_ = false; // Handles the JavaScript dialog requests. JavaScriptDialogHelper javascript_dialog_helper_; @@ -360,17 +361,17 @@ PendingWindowMap pending_new_windows_; // Determines if this guest accepts pinch-zoom gestures. - bool allow_scaling_; - bool is_guest_fullscreen_; - bool is_embedder_fullscreen_; - bool last_fullscreen_permission_was_allowed_by_embedder_; + bool allow_scaling_ = false; + bool is_guest_fullscreen_ = false; + bool is_embedder_fullscreen_ = false; + bool last_fullscreen_permission_was_allowed_by_embedder_ = false; // Tracks whether the webview has a pending zoom from before the first // navigation. This will be equal to 0 when there is no pending zoom. - double pending_zoom_factor_; + double pending_zoom_factor_ = 0.0; // Whether the GuestView set an explicit zoom level. - bool did_set_explicit_zoom_; + bool did_set_explicit_zoom_ = false; // Store spatial navigation status. bool is_spatial_navigation_enabled_;
diff --git a/extensions/browser/pref_names.cc b/extensions/browser/pref_names.cc index 828cb9f..2693cab 100644 --- a/extensions/browser/pref_names.cc +++ b/extensions/browser/pref_names.cc
@@ -45,7 +45,6 @@ "native_messaging.user_level_hosts"; const char kPinnedExtensions[] = "extensions.pinned_extensions"; const char kStorageGarbageCollect[] = "extensions.storage.garbagecollect"; -const char kToolbar[] = "extensions.toolbar"; const char kDeletedComponentExtensions[] = "extensions.deleted_component_extensions"; #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
diff --git a/extensions/browser/pref_names.h b/extensions/browser/pref_names.h index 2ef8a2d..c0c9121 100644 --- a/extensions/browser/pref_names.h +++ b/extensions/browser/pref_names.h
@@ -93,10 +93,6 @@ // on the next start of the browser. extern const char kStorageGarbageCollect[]; -// A preference that tracks browser action toolbar configuration. This is a list -// object stored in the Preferences file. The extensions are stored by ID. -extern const char kToolbar[]; - // A preference for a list of Component extensions that have been // uninstalled/removed and should not be reloaded. extern const char kDeletedComponentExtensions[];
diff --git a/fuchsia_web/webengine/browser/receiver_session_client.cc b/fuchsia_web/webengine/browser/receiver_session_client.cc index 310667f..9626395 100644 --- a/fuchsia_web/webengine/browser/receiver_session_client.cc +++ b/fuchsia_web/webengine/browser/receiver_session_client.cc
@@ -33,12 +33,17 @@ // out by build flags. auto stream_config = std::make_unique<cast_streaming::ReceiverSession::AVConstraints>( - cast_streaming::ToVideoCaptureConfigCodecs(media::VideoCodec::kH264, - media::VideoCodec::kVP8), - video_only_receiver_ - ? std::vector<openscreen::cast::AudioCodec>() - : cast_streaming::ToAudioCaptureConfigCodecs( - media::AudioCodec::kAAC, media::AudioCodec::kOpus)); + cast_streaming::ToVideoCaptureConfigCodecs( +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + media::VideoCodec::kH264, +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) + media::VideoCodec::kVP8), + video_only_receiver_ ? std::vector<openscreen::cast::AudioCodec>() + : cast_streaming::ToAudioCaptureConfigCodecs( +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + media::AudioCodec::kAAC, +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) + media::AudioCodec::kOpus)); receiver_session_ = cast_streaming::ReceiverSession::Create( std::move(stream_config),
diff --git a/fuchsia_web/webengine/renderer/web_engine_audio_renderer.cc b/fuchsia_web/webengine/renderer/web_engine_audio_renderer.cc index ef2cba8..20a32e0f 100644 --- a/fuchsia_web/webengine/renderer/web_engine_audio_renderer.cc +++ b/fuchsia_web/webengine/renderer/web_engine_audio_renderer.cc
@@ -28,9 +28,11 @@ GetFuchsiaCompressionFromDecoderConfig(media::AudioDecoderConfig config) { auto compression = std::make_unique<fuchsia::media::Compression>(); switch (config.codec()) { +#if BUILDFLAG(USE_PROPRIETARY_CODECS) case media::AudioCodec::kAAC: compression->type = fuchsia::media::AUDIO_ENCODING_AAC; break; +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) case media::AudioCodec::kMP3: compression->type = fuchsia::media::AUDIO_ENCODING_MP3; break; @@ -158,6 +160,7 @@ } void WebEngineAudioRenderer::InitializeStream() { +#if BUILDFLAG(USE_PROPRIETARY_CODECS) // AAC streams require bitstream conversion. Without it the demuxer may // produce decoded stream without ADTS headers which are required for AAC // streams in AudioConsumer. @@ -166,6 +169,7 @@ media::AudioCodec::kAAC) { demuxer_stream_->EnableBitstreamConverter(); } +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) if (demuxer_stream_->audio_decoder_config().is_encrypted()) { if (!cdm_context_) {
diff --git a/fuchsia_web/webengine/renderer/web_engine_content_renderer_client.cc b/fuchsia_web/webengine/renderer/web_engine_content_renderer_client.cc index 763fdcb..f75bf84e 100644 --- a/fuchsia_web/webengine/renderer/web_engine_content_renderer_client.cc +++ b/fuchsia_web/webengine/renderer/web_engine_content_renderer_client.cc
@@ -36,10 +36,12 @@ // Returns true if the specified video format can be decoded on hardware. bool IsSupportedHardwareVideoCodec(const media::VideoType& type) { +#if BUILDFLAG(USE_PROPRIETARY_CODECS) // TODO(crbug.com/1013412): Replace these hardcoded checks with a query to the // fuchsia.mediacodec FIDL service. if (type.codec == media::VideoCodec::kH264 && type.level <= 41) return true; +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) if (type.codec == media::VideoCodec::kVP9 && type.level <= 40) return true; @@ -188,11 +190,13 @@ supported_video_codecs |= media::EME_CODEC_VP9_PROFILE2; } +#if BUILDFLAG(USE_PROPRIETARY_CODECS) if (IsSupportedHardwareVideoCodec(media::VideoType{ media::VideoCodec::kH264, media::H264PROFILE_MAIN, kUnknownCodecLevel, media::VideoColorSpace::REC709()})) { supported_video_codecs |= media::EME_CODEC_AVC1; } +#endif // BUILDFLAG(USE_PROPRIETARY_CODECS) media::SupportedCodecs supported_audio_codecs = media::EME_CODEC_AUDIO_ALL;
diff --git a/gpu/config/gpu_finch_features.cc b/gpu/config/gpu_finch_features.cc index ae47e7b..e72053e 100644 --- a/gpu/config/gpu_finch_features.cc +++ b/gpu/config/gpu_finch_features.cc
@@ -143,8 +143,15 @@ }; // Enables the use of out of process rasterization for canvas. -const base::Feature kCanvasOopRasterization{"CanvasOopRasterization", - base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kCanvasOopRasterization { + "CanvasOopRasterization", +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS_ASH) || \ + (BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64)) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; // Enables the use of MSAA in skia on Ice Lake and later intel architectures. const base::Feature kEnableMSAAOnNewIntelGPUs{
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index 0bf719b..52652ba 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -787,6 +787,10 @@ "test/test_network_interceptor.h", ] + if (enable_basic_printing && enable_pdf) { + sources += [ "test/headless_printtopdf_browsertest.cc" ] + } + if (headless_use_policy) { sources += [ "test/headless_policy_browsertest.cc",
diff --git a/headless/test/headless_printtopdf_browsertest.cc b/headless/test/headless_printtopdf_browsertest.cc new file mode 100644 index 0000000..5bf4e40 --- /dev/null +++ b/headless/test/headless_printtopdf_browsertest.cc
@@ -0,0 +1,480 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> +#include <string> +#include <vector> + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/json/json_writer.h" +#include "base/run_loop.h" +#include "base/strings/string_number_conversions.h" +#include "content/public/test/browser_test.h" +#include "headless/app/headless_shell_switches.h" +#include "headless/lib/browser/headless_web_contents_impl.h" +#include "headless/public/devtools/domains/io.h" +#include "headless/public/devtools/domains/runtime.h" +#include "headless/test/headless_browser_test.h" +#include "pdf/pdf.h" +#include "printing/buildflags/buildflags.h" +#include "printing/pdf_render_settings.h" +#include "printing/units.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/geometry/rect.h" + +namespace headless { + +class HeadlessPDFPagesBrowserTest : public HeadlessAsyncDevTooledBrowserTest { + public: + const double kPaperWidth = 10; + const double kPaperHeight = 15; + const double kDocHeight = 50; + // Number of color channels in a BGRA bitmap. + const int kColorChannels = 4; + const int kDpi = 300; + + void RunDevTooledTest() override { + std::string height_expression = "document.body.style.height = '" + + base::NumberToString(kDocHeight) + "in'"; + std::unique_ptr<runtime::EvaluateParams> params = + runtime::EvaluateParams::Builder() + .SetExpression("document.body.style.background = '#123456';" + + height_expression) + .Build(); + devtools_client_->GetRuntime()->Evaluate( + std::move(params), + base::BindOnce(&HeadlessPDFPagesBrowserTest::OnPageSetupCompleted, + base::Unretained(this))); + } + + void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { + devtools_client_->GetPage()->GetExperimental()->PrintToPDF( + page::PrintToPDFParams::Builder() + .SetPrintBackground(true) + .SetPaperHeight(kPaperHeight) + .SetPaperWidth(kPaperWidth) + .SetMarginTop(0) + .SetMarginBottom(0) + .SetMarginLeft(0) + .SetMarginRight(0) + .Build(), + base::BindOnce(&HeadlessPDFPagesBrowserTest::OnPDFCreated, + base::Unretained(this))); + } + + void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { + protocol::Binary pdf_data = result->GetData(); + EXPECT_GT(pdf_data.size(), 0U); + auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); + int num_pages; + EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); + EXPECT_EQ(std::ceil(kDocHeight / kPaperHeight), num_pages); + + constexpr chrome_pdf::RenderOptions options = { + .stretch_to_bounds = false, + .keep_aspect_ratio = true, + .autorotate = true, + .use_color = true, + .render_device_type = chrome_pdf::RenderDeviceType::kPrinter, + }; + for (int i = 0; i < num_pages; i++) { + absl::optional<gfx::SizeF> size_in_points = + chrome_pdf::GetPDFPageSizeByIndex(pdf_span, i); + ASSERT_TRUE(size_in_points.has_value()); + EXPECT_EQ(static_cast<int>(size_in_points.value().width()), + static_cast<int>(kPaperWidth * printing::kPointsPerInch)); + EXPECT_EQ(static_cast<int>(size_in_points.value().height()), + static_cast<int>(kPaperHeight * printing::kPointsPerInch)); + + gfx::Rect rect(kPaperWidth * kDpi, kPaperHeight * kDpi); + printing::PdfRenderSettings settings( + rect, gfx::Point(), gfx::Size(kDpi, kDpi), options.autorotate, + options.use_color, printing::PdfRenderSettings::Mode::NORMAL); + std::vector<uint8_t> page_bitmap_data(kColorChannels * + settings.area.size().GetArea()); + EXPECT_TRUE(chrome_pdf::RenderPDFPageToBitmap( + pdf_span, i, page_bitmap_data.data(), settings.area.size(), + settings.dpi, options)); + EXPECT_EQ(0x56, page_bitmap_data[0]); // B + EXPECT_EQ(0x34, page_bitmap_data[1]); // G + EXPECT_EQ(0x12, page_bitmap_data[2]); // R + } + FinishAsynchronousTest(); + } +}; + +HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessPDFPagesBrowserTest); + +class HeadlessPDFStreamBrowserTest : public HeadlessAsyncDevTooledBrowserTest { + public: + const double kPaperWidth = 10; + const double kPaperHeight = 15; + const double kDocHeight = 50; + + void RunDevTooledTest() override { + std::string height_expression = "document.body.style.height = '" + + base::NumberToString(kDocHeight) + "in'"; + std::unique_ptr<runtime::EvaluateParams> params = + runtime::EvaluateParams::Builder() + .SetExpression(height_expression) + .Build(); + devtools_client_->GetRuntime()->Evaluate( + std::move(params), + base::BindOnce(&HeadlessPDFStreamBrowserTest::OnPageSetupCompleted, + base::Unretained(this))); + } + + void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { + devtools_client_->GetPage()->GetExperimental()->PrintToPDF( + page::PrintToPDFParams::Builder() + .SetTransferMode(page::PrintToPDFTransferMode::RETURN_AS_STREAM) + .SetPaperHeight(kPaperHeight) + .SetPaperWidth(kPaperWidth) + .SetMarginTop(0) + .SetMarginBottom(0) + .SetMarginLeft(0) + .SetMarginRight(0) + .Build(), + base::BindOnce(&HeadlessPDFStreamBrowserTest::OnPDFCreated, + base::Unretained(this))); + } + + void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { + EXPECT_EQ(result->GetData().size(), 0U); + stream_ = result->GetStream(); + devtools_client_->GetIO()->Read( + stream_, base::BindOnce(&HeadlessPDFStreamBrowserTest::OnReadChunk, + base::Unretained(this))); + } + + void OnReadChunk(std::unique_ptr<io::ReadResult> result) { + base64_data_ = base64_data_ + result->GetData(); + if (result->GetEof()) { + OnPDFLoaded(); + } else { + devtools_client_->GetIO()->Read( + stream_, base::BindOnce(&HeadlessPDFStreamBrowserTest::OnReadChunk, + base::Unretained(this))); + } + } + + void OnPDFLoaded() { + EXPECT_GT(base64_data_.size(), 0U); + bool success; + protocol::Binary pdf_data = + protocol::Binary::fromBase64(base64_data_, &success); + EXPECT_TRUE(success); + EXPECT_GT(pdf_data.size(), 0U); + auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); + + int num_pages; + EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); + EXPECT_EQ(std::ceil(kDocHeight / kPaperHeight), num_pages); + + absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); + ASSERT_TRUE(tagged.has_value()); + EXPECT_FALSE(tagged.value()); + + FinishAsynchronousTest(); + } + + private: + std::string stream_; + std::string base64_data_; +}; + +HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessPDFStreamBrowserTest); + +class HeadlessPDFBrowserTestBase : public HeadlessAsyncDevTooledBrowserTest, + public page::Observer { + public: + void RunDevTooledTest() override { + ASSERT_TRUE(embedded_test_server()->Start()); + + devtools_client_->GetPage()->AddObserver(this); + + base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); + devtools_client_->GetPage()->Enable(run_loop.QuitClosure()); + run_loop.Run(); + + devtools_client_->GetPage()->Navigate( + embedded_test_server()->GetURL(GetUrl()).spec()); + } + + void OnLoadEventFired(const page::LoadEventFiredParams&) override { + devtools_client_->GetPage()->GetExperimental()->PrintToPDF( + GetPrintToPDFParams(), + base::BindOnce(&HeadlessPDFBrowserTestBase::OnPDFCreated, + base::Unretained(this))); + } + + void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { + ASSERT_TRUE(result); + protocol::Binary pdf_data = result->GetData(); + ASSERT_GT(pdf_data.size(), 0U); + auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); + int num_pages; + ASSERT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); + ASSERT_GE(num_pages, 1); + + CheckPDF(pdf_span, num_pages); + + FinishAsynchronousTest(); + } + + virtual const char* GetUrl() = 0; + virtual std::unique_ptr<page::PrintToPDFParams> GetPrintToPDFParams() { + return page::PrintToPDFParams::Builder() + .SetPrintBackground(true) + .SetPaperHeight(41) + .SetPaperWidth(41) + .SetMarginTop(0) + .SetMarginBottom(0) + .SetMarginLeft(0) + .SetMarginRight(0) + .Build(); + } + virtual void CheckPDF(base::span<const uint8_t> pdf_span, int num_pages) = 0; +}; + +class HeadlessPDFPageSizeRoundingBrowserTest + : public HeadlessPDFBrowserTestBase { + public: + const char* GetUrl() override { return "/red_square.html"; } + + void CheckPDF(base::span<const uint8_t> pdf_span, int num_pages) override { + EXPECT_THAT(num_pages, testing::Eq(1)); + } +}; + +HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessPDFPageSizeRoundingBrowserTest); + +#if BUILDFLAG(ENABLE_TAGGED_PDF) + +const char kExpectedStructTreeJSON[] = R"({ + "lang": "en", + "type": "Document", + "~children": [ { + "type": "H1", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "P", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "L", + "~children": [ { + "type": "LI", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "LI", + "~children": [ { + "type": "NonStruct" + } ] + } ] + }, { + "type": "Div", + "~children": [ { + "type": "Link", + "~children": [ { + "type": "NonStruct" + } ] + } ] + }, { + "type": "Table", + "~children": [ { + "type": "TR", + "~children": [ { + "type": "TH", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "TH", + "~children": [ { + "type": "NonStruct" + } ] + } ] + }, { + "type": "TR", + "~children": [ { + "type": "TD", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "TD", + "~children": [ { + "type": "NonStruct" + } ] + } ] + } ] + }, { + "type": "H2", + "~children": [ { + "type": "NonStruct" + } ] + }, { + "type": "Div", + "~children": [ { + "alt": "Car at the beach", + "type": "Figure" + } ] + }, { + "lang": "fr", + "type": "P", + "~children": [ { + "type": "NonStruct" + } ] + } ] +} +)"; + +const char kExpectedFigureOnlyStructTreeJSON[] = R"({ + "lang": "en", + "type": "Document", + "~children": [ { + "type": "Figure", + "~children": [ { + "alt": "Sample SVG image", + "type": "Figure" + }, { + "type": "NonStruct", + "~children": [ { + "type": "NonStruct" + } ] + } ] + } ] +} +)"; + +const char kExpectedFigureRoleOnlyStructTreeJSON[] = R"({ + "lang": "en", + "type": "Document", + "~children": [ { + "alt": "Text that describes the figure.", + "type": "Figure", + "~children": [ { + "alt": "Sample SVG image", + "type": "Figure" + }, { + "type": "P", + "~children": [ { + "type": "NonStruct" + } ] + } ] + } ] +} +)"; + +const char kExpectedImageOnlyStructTreeJSON[] = R"({ + "lang": "en", + "type": "Document", + "~children": [ { + "type": "Div", + "~children": [ { + "alt": "Sample SVG image", + "type": "Figure" + } ] + } ] +} +)"; + +const char kExpectedImageRoleOnlyStructTreeJSON[] = R"({ + "lang": "en", + "type": "Document", + "~children": [ { + "alt": "That cat is so cute", + "type": "Figure", + "~children": [ { + "type": "P", + "~children": [ { + "type": "NonStruct" + } ] + } ] + } ] +} +)"; + +struct TaggedPDFTestData { + const char* url; + const char* expected_json; +}; + +constexpr TaggedPDFTestData kTaggedPDFTestData[] = { + {"/structured_doc.html", kExpectedStructTreeJSON}, + {"/structured_doc_only_figure.html", kExpectedFigureOnlyStructTreeJSON}, + {"/structured_doc_only_figure_role.html", + kExpectedFigureRoleOnlyStructTreeJSON}, + {"/structured_doc_only_image.html", kExpectedImageOnlyStructTreeJSON}, + {"/structured_doc_only_image_role.html", + kExpectedImageRoleOnlyStructTreeJSON}, +}; + +class HeadlessTaggedPDFBrowserTest + : public HeadlessPDFBrowserTestBase, + public ::testing::WithParamInterface<TaggedPDFTestData> { + public: + const char* GetUrl() override { return GetParam().url; } + + void CheckPDF(base::span<const uint8_t> pdf_span, int num_pages) override { + EXPECT_THAT(num_pages, testing::Eq(1)); + + absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); + EXPECT_THAT(tagged, testing::Optional(true)); + + constexpr int kFirstPage = 0; + base::Value struct_tree = + chrome_pdf::GetPDFStructTreeForPage(pdf_span, kFirstPage); + std::string json; + base::JSONWriter::WriteWithOptions( + struct_tree, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json); + // Map Windows line endings to Unix by removing '\r'. + base::RemoveChars(json, "\r", &json); + + EXPECT_EQ(GetParam().expected_json, json); + } +}; + +HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessTaggedPDFBrowserTest); + +INSTANTIATE_TEST_SUITE_P(All, + HeadlessTaggedPDFBrowserTest, + ::testing::ValuesIn(kTaggedPDFTestData)); + +class HeadlessTaggedPDFDisabledBrowserTest + : public HeadlessPDFBrowserTestBase, + public ::testing::WithParamInterface<TaggedPDFTestData> { + public: + void SetUpCommandLine(base::CommandLine* command_line) override { + HeadlessPDFBrowserTestBase::SetUpCommandLine(command_line); + command_line->AppendSwitch(switches::kDisablePDFTagging); + } + + const char* GetUrl() override { return GetParam().url; } + + void CheckPDF(base::span<const uint8_t> pdf_span, int num_pages) override { + EXPECT_THAT(num_pages, testing::Eq(1)); + + absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); + EXPECT_THAT(tagged, testing::Optional(false)); + } +}; + +HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessTaggedPDFDisabledBrowserTest); + +INSTANTIATE_TEST_SUITE_P(All, + HeadlessTaggedPDFDisabledBrowserTest, + ::testing::ValuesIn(kTaggedPDFTestData)); + +#endif // BUILDFLAG(ENABLE_TAGGED_PDF) + +} // namespace headless
diff --git a/headless/test/headless_web_contents_browsertest.cc b/headless/test/headless_web_contents_browsertest.cc index b569bb4e..45a53ba 100644 --- a/headless/test/headless_web_contents_browsertest.cc +++ b/headless/test/headless_web_contents_browsertest.cc
@@ -35,8 +35,6 @@ #include "headless/public/headless_devtools_client.h" #include "headless/public/headless_web_contents.h" #include "headless/test/headless_browser_test.h" -#include "pdf/buildflags.h" -#include "printing/buildflags/buildflags.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -48,14 +46,6 @@ #include "ui/gfx/geometry/size_f.h" #include "url/gurl.h" -#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PDF) -#include "base/strings/string_number_conversions.h" -#include "pdf/pdf.h" -#include "printing/pdf_render_settings.h" -#include "printing/units.h" -#include "ui/gfx/geometry/rect.h" -#endif - using testing::ElementsAre; using testing::ElementsAreArray; using testing::Not; @@ -275,489 +265,6 @@ HeadlessWebContentsScreenshotWindowPositionTest, ::testing::Bool()); -#if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PDF) -class HeadlessWebContentsPDFTest : public HeadlessAsyncDevTooledBrowserTest { - public: - const double kPaperWidth = 10; - const double kPaperHeight = 15; - const double kDocHeight = 50; - // Number of color channels in a BGRA bitmap. - const int kColorChannels = 4; - const int kDpi = 300; - - void RunDevTooledTest() override { - std::string height_expression = "document.body.style.height = '" + - base::NumberToString(kDocHeight) + "in'"; - std::unique_ptr<runtime::EvaluateParams> params = - runtime::EvaluateParams::Builder() - .SetExpression("document.body.style.background = '#123456';" + - height_expression) - .Build(); - devtools_client_->GetRuntime()->Evaluate( - std::move(params), - base::BindOnce(&HeadlessWebContentsPDFTest::OnPageSetupCompleted, - base::Unretained(this))); - } - - void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { - devtools_client_->GetPage()->GetExperimental()->PrintToPDF( - page::PrintToPDFParams::Builder() - .SetPrintBackground(true) - .SetPaperHeight(kPaperHeight) - .SetPaperWidth(kPaperWidth) - .SetMarginTop(0) - .SetMarginBottom(0) - .SetMarginLeft(0) - .SetMarginRight(0) - .Build(), - base::BindOnce(&HeadlessWebContentsPDFTest::OnPDFCreated, - base::Unretained(this))); - } - - void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { - protocol::Binary pdf_data = result->GetData(); - EXPECT_GT(pdf_data.size(), 0U); - auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); - int num_pages; - EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); - EXPECT_EQ(std::ceil(kDocHeight / kPaperHeight), num_pages); - - constexpr chrome_pdf::RenderOptions options = { - .stretch_to_bounds = false, - .keep_aspect_ratio = true, - .autorotate = true, - .use_color = true, - .render_device_type = chrome_pdf::RenderDeviceType::kPrinter, - }; - for (int i = 0; i < num_pages; i++) { - absl::optional<gfx::SizeF> size_in_points = - chrome_pdf::GetPDFPageSizeByIndex(pdf_span, i); - ASSERT_TRUE(size_in_points.has_value()); - EXPECT_EQ(static_cast<int>(size_in_points.value().width()), - static_cast<int>(kPaperWidth * printing::kPointsPerInch)); - EXPECT_EQ(static_cast<int>(size_in_points.value().height()), - static_cast<int>(kPaperHeight * printing::kPointsPerInch)); - - gfx::Rect rect(kPaperWidth * kDpi, kPaperHeight * kDpi); - printing::PdfRenderSettings settings( - rect, gfx::Point(), gfx::Size(kDpi, kDpi), options.autorotate, - options.use_color, printing::PdfRenderSettings::Mode::NORMAL); - std::vector<uint8_t> page_bitmap_data(kColorChannels * - settings.area.size().GetArea()); - EXPECT_TRUE(chrome_pdf::RenderPDFPageToBitmap( - pdf_span, i, page_bitmap_data.data(), settings.area.size(), - settings.dpi, options)); - EXPECT_EQ(0x56, page_bitmap_data[0]); // B - EXPECT_EQ(0x34, page_bitmap_data[1]); // G - EXPECT_EQ(0x12, page_bitmap_data[2]); // R - } - FinishAsynchronousTest(); - } -}; - -HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsPDFTest); - -class HeadlessWebContentsPDFStreamTest - : public HeadlessAsyncDevTooledBrowserTest { - public: - const double kPaperWidth = 10; - const double kPaperHeight = 15; - const double kDocHeight = 50; - - void RunDevTooledTest() override { - std::string height_expression = "document.body.style.height = '" + - base::NumberToString(kDocHeight) + "in'"; - std::unique_ptr<runtime::EvaluateParams> params = - runtime::EvaluateParams::Builder() - .SetExpression(height_expression) - .Build(); - devtools_client_->GetRuntime()->Evaluate( - std::move(params), - base::BindOnce(&HeadlessWebContentsPDFStreamTest::OnPageSetupCompleted, - base::Unretained(this))); - } - - void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { - devtools_client_->GetPage()->GetExperimental()->PrintToPDF( - page::PrintToPDFParams::Builder() - .SetTransferMode(page::PrintToPDFTransferMode::RETURN_AS_STREAM) - .SetPaperHeight(kPaperHeight) - .SetPaperWidth(kPaperWidth) - .SetMarginTop(0) - .SetMarginBottom(0) - .SetMarginLeft(0) - .SetMarginRight(0) - .Build(), - base::BindOnce(&HeadlessWebContentsPDFStreamTest::OnPDFCreated, - base::Unretained(this))); - } - - void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { - EXPECT_EQ(result->GetData().size(), 0U); - stream_ = result->GetStream(); - devtools_client_->GetIO()->Read( - stream_, base::BindOnce(&HeadlessWebContentsPDFStreamTest::OnReadChunk, - base::Unretained(this))); - } - - void OnReadChunk(std::unique_ptr<io::ReadResult> result) { - base64_data_ = base64_data_ + result->GetData(); - if (result->GetEof()) { - OnPDFLoaded(); - } else { - devtools_client_->GetIO()->Read( - stream_, - base::BindOnce(&HeadlessWebContentsPDFStreamTest::OnReadChunk, - base::Unretained(this))); - } - } - - void OnPDFLoaded() { - EXPECT_GT(base64_data_.size(), 0U); - bool success; - protocol::Binary pdf_data = - protocol::Binary::fromBase64(base64_data_, &success); - EXPECT_TRUE(success); - EXPECT_GT(pdf_data.size(), 0U); - auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); - - int num_pages; - EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); - EXPECT_EQ(std::ceil(kDocHeight / kPaperHeight), num_pages); - - absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); - ASSERT_TRUE(tagged.has_value()); - EXPECT_FALSE(tagged.value()); - - FinishAsynchronousTest(); - } - - private: - std::string stream_; - std::string base64_data_; -}; - -HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsPDFStreamTest); - -class HeadlessWebContentsPDFPageSizeRoundingTest - : public HeadlessAsyncDevTooledBrowserTest, - public page::Observer { - public: - void RunDevTooledTest() override { - EXPECT_TRUE(embedded_test_server()->Start()); - - devtools_client_->GetPage()->AddObserver(this); - - base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); - devtools_client_->GetPage()->Enable(run_loop.QuitClosure()); - run_loop.Run(); - - devtools_client_->GetPage()->Navigate( - embedded_test_server()->GetURL("/red_square.html").spec()); - } - - void OnLoadEventFired(const page::LoadEventFiredParams&) override { - devtools_client_->GetPage()->GetExperimental()->PrintToPDF( - page::PrintToPDFParams::Builder() - .SetPrintBackground(true) - .SetPaperHeight(41) - .SetPaperWidth(41) - .SetMarginTop(0) - .SetMarginBottom(0) - .SetMarginLeft(0) - .SetMarginRight(0) - .Build(), - base::BindOnce( - &HeadlessWebContentsPDFPageSizeRoundingTest::OnPDFCreated, - base::Unretained(this))); - } - - void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { - protocol::Binary pdf_data = result->GetData(); - EXPECT_GT(pdf_data.size(), 0U); - auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); - int num_pages; - EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); - EXPECT_THAT(num_pages, testing::Eq(1)); - FinishAsynchronousTest(); - } -}; - -HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsPDFPageSizeRoundingTest); - -#if BUILDFLAG(ENABLE_TAGGED_PDF) - -const char kExpectedStructTreeJSON[] = R"({ - "lang": "en", - "type": "Document", - "~children": [ { - "type": "H1", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "P", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "L", - "~children": [ { - "type": "LI", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "LI", - "~children": [ { - "type": "NonStruct" - } ] - } ] - }, { - "type": "Div", - "~children": [ { - "type": "Link", - "~children": [ { - "type": "NonStruct" - } ] - } ] - }, { - "type": "Table", - "~children": [ { - "type": "TR", - "~children": [ { - "type": "TH", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "TH", - "~children": [ { - "type": "NonStruct" - } ] - } ] - }, { - "type": "TR", - "~children": [ { - "type": "TD", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "TD", - "~children": [ { - "type": "NonStruct" - } ] - } ] - } ] - }, { - "type": "H2", - "~children": [ { - "type": "NonStruct" - } ] - }, { - "type": "Div", - "~children": [ { - "alt": "Car at the beach", - "type": "Figure" - } ] - }, { - "lang": "fr", - "type": "P", - "~children": [ { - "type": "NonStruct" - } ] - } ] -} -)"; - -const char kExpectedFigureOnlyStructTreeJSON[] = R"({ - "lang": "en", - "type": "Document", - "~children": [ { - "type": "Figure", - "~children": [ { - "alt": "Sample SVG image", - "type": "Figure" - }, { - "type": "NonStruct", - "~children": [ { - "type": "NonStruct" - } ] - } ] - } ] -} -)"; - -const char kExpectedFigureRoleOnlyStructTreeJSON[] = R"({ - "lang": "en", - "type": "Document", - "~children": [ { - "alt": "Text that describes the figure.", - "type": "Figure", - "~children": [ { - "alt": "Sample SVG image", - "type": "Figure" - }, { - "type": "P", - "~children": [ { - "type": "NonStruct" - } ] - } ] - } ] -} -)"; - -const char kExpectedImageOnlyStructTreeJSON[] = R"({ - "lang": "en", - "type": "Document", - "~children": [ { - "type": "Div", - "~children": [ { - "alt": "Sample SVG image", - "type": "Figure" - } ] - } ] -} -)"; - -const char kExpectedImageRoleOnlyStructTreeJSON[] = R"({ - "lang": "en", - "type": "Document", - "~children": [ { - "alt": "That cat is so cute", - "type": "Figure", - "~children": [ { - "type": "P", - "~children": [ { - "type": "NonStruct" - } ] - } ] - } ] -} -)"; - -struct TaggedPDFTestData { - const char* url; - const char* expected_json; -}; - -constexpr TaggedPDFTestData kTaggedPDFTestData[] = { - {"/structured_doc.html", kExpectedStructTreeJSON}, - {"/structured_doc_only_figure.html", kExpectedFigureOnlyStructTreeJSON}, - {"/structured_doc_only_figure_role.html", - kExpectedFigureRoleOnlyStructTreeJSON}, - {"/structured_doc_only_image.html", kExpectedImageOnlyStructTreeJSON}, - {"/structured_doc_only_image_role.html", - kExpectedImageRoleOnlyStructTreeJSON}, -}; - -class HeadlessWebContentsTaggedPDFTestBase - : public HeadlessAsyncDevTooledBrowserTest, - public page::Observer { - public: - void RunDevTooledTest() override { - EXPECT_TRUE(embedded_test_server()->Start()); - - devtools_client_->GetPage()->AddObserver(this); - - base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); - devtools_client_->GetPage()->Enable(run_loop.QuitClosure()); - run_loop.Run(); - - devtools_client_->GetPage()->Navigate( - embedded_test_server()->GetURL(GetUrl()).spec()); - } - - void OnLoadEventFired(const page::LoadEventFiredParams&) override { - devtools_client_->GetPage()->GetExperimental()->PrintToPDF( - page::PrintToPDFParams::Builder() - .SetPrintBackground(true) - .SetPaperHeight(41) - .SetPaperWidth(41) - .SetMarginTop(0) - .SetMarginBottom(0) - .SetMarginLeft(0) - .SetMarginRight(0) - .Build(), - base::BindOnce(&HeadlessWebContentsTaggedPDFTestBase::OnPDFCreated, - base::Unretained(this))); - } - - void OnPDFCreated(std::unique_ptr<page::PrintToPDFResult> result) { - ASSERT_TRUE(result); - protocol::Binary pdf_data = result->GetData(); - EXPECT_GT(pdf_data.size(), 0U); - auto pdf_span = base::make_span(pdf_data.data(), pdf_data.size()); - int num_pages; - EXPECT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_span, &num_pages, nullptr)); - EXPECT_EQ(1, num_pages); - - CheckPDF(pdf_span); - - FinishAsynchronousTest(); - } - - virtual const char* GetUrl() = 0; - virtual void CheckPDF(base::span<const uint8_t> pdf_span) = 0; -}; - -class HeadlessWebContentsTaggedPDFTest - : public HeadlessWebContentsTaggedPDFTestBase, - public ::testing::WithParamInterface<TaggedPDFTestData> { - public: - const char* GetUrl() override { return GetParam().url; } - - void CheckPDF(base::span<const uint8_t> pdf_span) override { - absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); - EXPECT_THAT(tagged, testing::Optional(true)); - - constexpr int kFirstPage = 0; - base::Value struct_tree = - chrome_pdf::GetPDFStructTreeForPage(pdf_span, kFirstPage); - std::string json; - base::JSONWriter::WriteWithOptions( - struct_tree, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json); - // Map Windows line endings to Unix by removing '\r'. - base::RemoveChars(json, "\r", &json); - - EXPECT_EQ(GetParam().expected_json, json); - } -}; - -HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessWebContentsTaggedPDFTest); - -INSTANTIATE_TEST_SUITE_P(All, - HeadlessWebContentsTaggedPDFTest, - ::testing::ValuesIn(kTaggedPDFTestData)); - -class HeadlessWebContentsTaggedPDFDisabledTest - : public HeadlessWebContentsTaggedPDFTestBase, - public ::testing::WithParamInterface<TaggedPDFTestData> { - public: - void SetUpCommandLine(base::CommandLine* command_line) override { - HeadlessWebContentsTaggedPDFTestBase::SetUpCommandLine(command_line); - command_line->AppendSwitch(switches::kDisablePDFTagging); - } - - const char* GetUrl() override { return GetParam().url; } - - void CheckPDF(base::span<const uint8_t> pdf_span) override { - absl::optional<bool> tagged = chrome_pdf::IsPDFDocTagged(pdf_span); - EXPECT_THAT(tagged, testing::Optional(false)); - } -}; - -HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessWebContentsTaggedPDFDisabledTest); - -INSTANTIATE_TEST_SUITE_P(All, - HeadlessWebContentsTaggedPDFDisabledTest, - ::testing::ValuesIn(kTaggedPDFTestData)); - -#endif // BUILDFLAG(ENABLE_TAGGED_PDF) - -#endif // BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(ENABLE_PDF) - class HeadlessWebContentsSecurityTest : public HeadlessAsyncDevTooledBrowserTest, public security::ExperimentalObserver {
diff --git a/infra/config/dev/dev.star b/infra/config/dev/dev.star index bb154e30..b1b78f6 100644 --- a/infra/config/dev/dev.star +++ b/infra/config/dev/dev.star
@@ -32,6 +32,20 @@ groups = "project-chromium-admins", ), ], + bindings = [ + luci.binding( + roles = "role/weetbix.reader", + groups = "all", + ), + luci.binding( + roles = "role/weetbix.queryUser", + groups = "authenticated-users", + ), + luci.binding( + roles = "role/weetbix.editor", + groups = "project-chromium-committers", + ), + ], ) luci.logdog(
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 3162670..1665450 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -36126,12 +36126,12 @@ name: "linux-chromeos-rel" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" - dimensions: "cores:8" + dimensions: "cores:16" dimensions: "cpu:x86-64" dimensions: "free_space:standard" dimensions: "os:Ubuntu-18.04" dimensions: "pool:luci.chromium.ci" - dimensions: "ssd:0" + dimensions: "ssd:1" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" cipd_version: "latest" @@ -40029,13 +40029,11 @@ builders { name: "mac-osxbeta-rel" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" + dimensions: "builder:mac-osxbeta-rel" dimensions: "cores:8" dimensions: "cpu:x86-64" - dimensions: "free_space:standard" - dimensions: "os:Ubuntu-18.04" + dimensions: "os:Mac-12" dimensions: "pool:luci.chromium.ci" - dimensions: "ssd:0" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" cipd_version: "latest" @@ -74795,7 +74793,7 @@ builders { name: "mac-osxbeta-rel" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" + dimensions: "builder:mac-osxbeta-rel" dimensions: "cpu:x86-64" dimensions: "os:Mac-12" dimensions: "pool:luci.chromium.try"
diff --git a/infra/config/generated/luci/realms-dev.cfg b/infra/config/generated/luci/realms-dev.cfg index 10b523e..9b81b53b 100644 --- a/infra/config/generated/luci/realms-dev.cfg +++ b/infra/config/generated/luci/realms-dev.cfg
@@ -46,6 +46,18 @@ role: "role/swarming.taskTriggerer" principals: "group:mdb/chrome-troopers" } + bindings { + role: "role/weetbix.editor" + principals: "group:project-chromium-committers" + } + bindings { + role: "role/weetbix.queryUser" + principals: "group:authenticated-users" + } + bindings { + role: "role/weetbix.reader" + principals: "group:all" + } } realms { name: "ci"
diff --git a/infra/config/generated/luci/realms.cfg b/infra/config/generated/luci/realms.cfg index 173e380..80bd0b8 100644 --- a/infra/config/generated/luci/realms.cfg +++ b/infra/config/generated/luci/realms.cfg
@@ -51,6 +51,18 @@ role: "role/swarming.taskTriggerer" principals: "group:mdb/chrome-troopers" } + bindings { + role: "role/weetbix.editor" + principals: "group:project-chromium-committers" + } + bindings { + role: "role/weetbix.queryUser" + principals: "group:authenticated-users" + } + bindings { + role: "role/weetbix.reader" + principals: "group:all" + } } realms { name: "ci"
diff --git a/infra/config/main.star b/infra/config/main.star index f2da100..e002c448 100755 --- a/infra/config/main.star +++ b/infra/config/main.star
@@ -97,6 +97,18 @@ roles = "role/configs.validator", groups = "project-chromium-try-task-accounts", ), + luci.binding( + roles = "role/weetbix.reader", + groups = "all", + ), + luci.binding( + roles = "role/weetbix.queryUser", + groups = "authenticated-users", + ), + luci.binding( + roles = "role/weetbix.editor", + groups = "project-chromium-committers", + ), ], )
diff --git a/infra/config/subprojects/chromium/ci/chromium.chromiumos.star b/infra/config/subprojects/chromium/ci/chromium.chromiumos.star index 5df9931..eb4ccb19 100644 --- a/infra/config/subprojects/chromium/ci/chromium.chromiumos.star +++ b/infra/config/subprojects/chromium/ci/chromium.chromiumos.star
@@ -701,7 +701,10 @@ # This builder build 2 chrome(Ash and Lacros), so it need # more time. # TODO(crbug.com/1345687) We should reduce this timeout. + # And use normal machines. execution_timeout = 6 * time.hour, + cores = 16, + ssd = True, ) ci.builder(
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index ecff2bcc..714e780 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -750,6 +750,8 @@ short_name = "beta", ), main_console_view = None, + builderless = False, + os = os.MAC_DEFAULT, triggered_by = ["ci/Mac Builder"], )
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star index 832de6c..c0fbe04 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star
@@ -51,6 +51,7 @@ "ci/Mac Builder", "ci/mac-osxbeta-rel", ], + builderless = False, os = os.MAC_DEFAULT, )
diff --git a/ios/chrome/browser/DEPS b/ios/chrome/browser/DEPS index 3c83a28..5a45553 100644 --- a/ios/chrome/browser/DEPS +++ b/ios/chrome/browser/DEPS
@@ -191,6 +191,7 @@ ], "^ios_chrome_field_trials.mm": [ "+ios/chrome/browser/ui/first_run/fre_field_trial.h", + "+ios/chrome/browser/ui/first_run/trending_queries_field_trial.h", ], "^system_flags.mm": [ "+ios/chrome/browser/ui/ui_feature_flags.h",
diff --git a/ios/chrome/browser/autofill/form_structure_browsertest.mm b/ios/chrome/browser/autofill/form_structure_browsertest.mm index 279946f..24722a4d 100644 --- a/ios/chrome/browser/autofill/form_structure_browsertest.mm +++ b/ios/chrome/browser/autofill/form_structure_browsertest.mm
@@ -196,9 +196,7 @@ // TODO(crbug.com/1277480): Remove once launched. autofill::features::kAutofillEnableNameSurenameParsing, // TODO(crbug.com/1190334): Remove once launched. - autofill::features::kAutofillParseMerchantPromoCodeFields, - // TODO(crbug.com/1335549): Remove once launched. - autofill::features::kAutofillParseIbanFields}, + autofill::features::kAutofillParseMerchantPromoCodeFields}, // Disabled {}); }
diff --git a/ios/chrome/browser/follow/follow_tab_helper.h b/ios/chrome/browser/follow/follow_tab_helper.h index 97353b4..1a36ccc 100644 --- a/ios/chrome/browser/follow/follow_tab_helper.h +++ b/ios/chrome/browser/follow/follow_tab_helper.h
@@ -111,9 +111,9 @@ // Used to update the follow menu item. __weak id<FollowMenuUpdater> follow_menu_updater_ = nil; - // The recommended rss url of the current website. Nil if + // The recommended url of the current website. Nil if // the site is not recommended. - NSURL* recommended_rss_url_ = nil; + NSURL* recommended_url_ = nil; base::CancelableTaskTracker history_task_tracker_; base::WeakPtrFactory<FollowTabHelper> weak_ptr_factory_{this};
diff --git a/ios/chrome/browser/follow/follow_tab_helper.mm b/ios/chrome/browser/follow/follow_tab_helper.mm index 6e5d1b6..f88bd38 100644 --- a/ios/chrome/browser/follow/follow_tab_helper.mm +++ b/ios/chrome/browser/follow/follow_tab_helper.mm
@@ -176,15 +176,17 @@ return; } - recommended_rss_url_ = ios::GetChromeBrowserProvider() - .GetFollowProvider() - ->GetRecommendedSiteURL(web_page_urls); + recommended_url_ = ios::GetChromeBrowserProvider() + .GetFollowProvider() + ->GetRecommendedSiteURL(web_page_urls); // Do not show follow IPH if: // 1. The site is not recommended; - // 2. The IPH was shown too recently. - if (!recommended_rss_url_ || - !IsFollowIPHShownFrequencyEligible(recommended_rss_url_)) { + // 2. The recommended url is empty (it happens if there's an error when + // fetching); + // 3. The IPH was shown too recently. + if (!recommended_url_ || recommended_url_.absoluteString.length == 0 || + !IsFollowIPHShownFrequencyEligible(recommended_url_)) { return; } @@ -262,7 +264,7 @@ DCHECK(follow_iph_presenter_); [follow_iph_presenter_ presentFollowWhileBrowsingIPH]; if (!experimental_flags::ShouldAlwaysShowFollowIPH()) { - StoreFollowIPHPresentingTime(recommended_rss_url_); + StoreFollowIPHPresentingTime(recommended_url_); } }
diff --git a/ios/chrome/browser/ios_chrome_field_trials.mm b/ios/chrome/browser/ios_chrome_field_trials.mm index 0d32af7..ba3082a 100644 --- a/ios/chrome/browser/ios_chrome_field_trials.mm +++ b/ios/chrome/browser/ios_chrome_field_trials.mm
@@ -2,14 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ios/chrome/browser/ios_chrome_field_trials.h" +#import "ios/chrome/browser/ios_chrome_field_trials.h" -#include "base/check.h" -#include "base/path_service.h" -#include "components/metrics/persistent_histograms.h" -#include "ios/chrome/browser/application_context.h" -#include "ios/chrome/browser/chrome_paths.h" -#include "ios/chrome/browser/ui/first_run/fre_field_trial.h" +#import "base/check.h" +#import "base/path_service.h" +#import "components/metrics/persistent_histograms.h" +#import "ios/chrome/browser/application_context.h" +#import "ios/chrome/browser/chrome_paths.h" +#import "ios/chrome/browser/ui/first_run/fre_field_trial.h" +#import "ios/chrome/browser/ui/first_run/trending_queries_field_trial.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -33,4 +34,7 @@ DCHECK(low_entropy_provider); fre_field_trial::Create(*low_entropy_provider, feature_list, GetApplicationContext()->GetLocalState()); + trending_queries_field_trial::Create( + *low_entropy_provider, feature_list, + GetApplicationContext()->GetLocalState()); }
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index f18a70b..c990fb5 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -74,6 +74,7 @@ #import "ios/chrome/browser/ui/bookmarks/bookmark_utils_ios.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h" #include "ios/chrome/browser/ui/first_run/fre_field_trial.h" +#import "ios/chrome/browser/ui/first_run/trending_queries_field_trial.h" #import "ios/chrome/browser/ui/incognito_reauth/incognito_reauth_scene_agent.h" #import "ios/chrome/browser/ui/ui_feature_flags.h" #include "ios/chrome/browser/voice/voice_search_prefs_registration.h" @@ -170,6 +171,7 @@ update_client::RegisterPrefs(registry); variations::VariationsService::RegisterPrefs(registry); fre_field_trial::RegisterLocalStatePrefs(registry); + trending_queries_field_trial::RegisterLocalStatePrefs(registry); component_updater::RegisterComponentUpdateServicePrefs(registry); component_updater::AutofillStatesComponentInstallerPolicy::RegisterPrefs( registry);
diff --git a/ios/chrome/browser/safe_browsing/BUILD.gn b/ios/chrome/browser/safe_browsing/BUILD.gn index eba8507..676f62e8 100644 --- a/ios/chrome/browser/safe_browsing/BUILD.gn +++ b/ios/chrome/browser/safe_browsing/BUILD.gn
@@ -121,6 +121,7 @@ "//ios/chrome/browser/passwords:eg_test_support+eg2", "//ios/chrome/browser/ui/bookmarks:eg_test_support+eg2", "//ios/chrome/browser/ui/passwords:constants", + "//ios/chrome/browser/ui/settings/privacy:privacy_constants", "//ios/chrome/browser/ui/tab_switcher/tab_grid:features", "//ios/chrome/test/earl_grey:eg_test_support+eg2", "//ios/testing/earl_grey:eg_test_support+eg2",
diff --git a/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm b/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm index 00ec980..fae0f73e 100644 --- a/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm +++ b/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm
@@ -12,6 +12,7 @@ #include "components/strings/grit/components_strings.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_earl_grey.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_earl_grey_ui.h" +#import "ios/chrome/browser/ui/settings/privacy/privacy_constants.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" @@ -31,6 +32,7 @@ using chrome_test_util::BackButton; using chrome_test_util::ForwardButton; +using chrome_test_util::SettingsDoneButton; using chrome_test_util::TappableBookmarkNodeWithLabel; namespace { @@ -203,6 +205,24 @@ [super tearDown]; } +#pragma mark - Helper methods + +// Instantiates an ElementSelector to detect the enhanced protection message on +// interstitial page. +- (ElementSelector*)enhancedProtectionMessage { + NSString* selector = + @"(function() {" + " var element = document.getElementById('enhanced-protection-message');" + " if (element == null) return false;" + " if (element.classList.contains('hidden')) return false;" + " return true;" + "})()"; + NSString* description = @"Enhanced Safe Browsing message."; + return [ElementSelector selectorWithScript:selector + selectorDescription:description]; +} + +#pragma mark - Tests // Tests that safe pages are not blocked. - (void)testSafePage { [ChromeEarlGrey loadURL:_safeURL1]; @@ -417,17 +437,8 @@ // Disable Enhanced Safe Browsing and verify that a dark red box prompting to // turn on Enhanced Protection is visible. [ChromeEarlGrey setBoolValue:NO forUserPref:prefs::kSafeBrowsingEnhanced]; - NSString* selector = - @"(function() {" - " var element = document.getElementById('enhanced-protection-message');" - " if (element == null) return false;" - " if (element.classList.contains('hidden')) return false;" - " return true;" - "})()"; - NSString* description = @"Enhanced Safe Browsing message."; ElementSelector* enhancedSafeBrowsingMessage = - [ElementSelector selectorWithScript:selector - selectorDescription:description]; + [self enhancedProtectionMessage]; [ChromeEarlGrey loadURL:_safeURL1]; [ChromeEarlGrey waitForWebStateContainingText:_safeContent1]; @@ -446,6 +457,37 @@ waitForWebStateNotContainingElement:enhancedSafeBrowsingMessage]; } +- (void)testEnhancedSafeBrowsingLink { + // Disable Enhanced Safe Browsing and verify that a dark red box prompting to + // turn on Enhanced Protection is visible. + [ChromeEarlGrey setBoolValue:NO forUserPref:prefs::kSafeBrowsingEnhanced]; + ElementSelector* enhancedSafeBrowsingMessage = + [self enhancedProtectionMessage]; + + [ChromeEarlGrey loadURL:_safeURL1]; + [ChromeEarlGrey waitForWebStateContainingText:_safeContent1]; + [ChromeEarlGrey loadURL:_phishingURL]; + [ChromeEarlGrey waitForWebStateContainingElement:enhancedSafeBrowsingMessage]; + [ChromeEarlGrey tapWebStateElementWithID:@"enhanced-protection-link"]; + + [[EarlGrey + selectElementWithMatcher: + grey_accessibilityID(kSettingsSafeBrowsingEnhancedProtectionCellId)] + performAction:grey_tap()]; + GREYAssertTrue([ChromeEarlGrey userBooleanPref:prefs::kSafeBrowsingEnhanced], + @"Failed to toggle-on Enhanced Safe Browsing"); + [[EarlGrey selectElementWithMatcher:SettingsDoneButton()] + performAction:grey_tap()]; + + // Verify that a dark red box prompting to turn on Enhanced Protection is not + // visible. + [ChromeEarlGrey loadURL:_phishingURL]; + [ChromeEarlGrey waitForWebStateContainingText:l10n_util::GetStringUTF8( + IDS_PHISHING_V4_HEADING)]; + [ChromeEarlGrey + waitForWebStateNotContainingElement:enhancedSafeBrowsingMessage]; +} + // Tests displaying a warning for an unsafe page in incognito mode, and // proceeding past the warning. - (void)testWarningInIncognito {
diff --git a/ios/chrome/browser/ui/autofill/BUILD.gn b/ios/chrome/browser/ui/autofill/BUILD.gn index 6f364bba..3d4acdb 100644 --- a/ios/chrome/browser/ui/autofill/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/BUILD.gn
@@ -74,11 +74,14 @@ "card_unmask_prompt_view_bridge.mm", "card_unmask_prompt_view_controller.h", "card_unmask_prompt_view_controller.mm", + "create_card_unmask_prompt_view_bridge.h", + "create_card_unmask_prompt_view_bridge.mm", "legacy_card_unmask_prompt_view_bridge.h", "legacy_card_unmask_prompt_view_bridge.mm", ] deps = [ ":autofill_ui", + ":features", "//base", "//components/autofill/core/browser", "//components/strings",
diff --git a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.h b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.h index e00d4273..6449d43d 100644 --- a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.h +++ b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.h
@@ -10,6 +10,7 @@ @class CardUnmaskPromptViewController; @class UIViewController; +@class UINavigationController; namespace autofill { @@ -38,13 +39,20 @@ // Closes the view. void PerformClose(); + // Called when `navigation_controller_` was dismissed. + // This call destroys `this`. + void NavigationControllerDismissed(); + protected: + // The presented UINavigationController containing `prompt_view_controller_`. + UINavigationController* navigation_controller_; + // Created on `Show` and destroyed when 'this' is destroyed. - CardUnmaskPromptViewController* view_controller_; + CardUnmaskPromptViewController* prompt_view_controller_; private: - // Deletes self. This should only be called by CardUnmaskPromptViewController - // after it finishes dismissing its own UI elements. + // Deletes self. Called after CardUnmaskPromptViewController finishes + // dismissing its own UI elements. void DeleteSelf(); // The controller `this` queries for logic and state.
diff --git a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.mm b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.mm index 1ac25dce..0501e8da 100644 --- a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.mm +++ b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.mm
@@ -32,22 +32,19 @@ } void CardUnmaskPromptViewBridge::Show() { - view_controller_ = + prompt_view_controller_ = [[CardUnmaskPromptViewController alloc] initWithBridge:this]; - UINavigationController* navigation_controller = - [[UINavigationController alloc] - initWithRootViewController:view_controller_]; - [navigation_controller + navigation_controller_ = [[UINavigationController alloc] + initWithRootViewController:prompt_view_controller_]; + [navigation_controller_ setModalPresentationStyle:UIModalPresentationFormSheet]; - [navigation_controller + [navigation_controller_ setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; - // If this prompt is swiped away, it cannot be opened again. Work - // around this bug by preventing swipe-to-dismiss. - // TODO(crbug.com/1346060) - [navigation_controller setModalInPresentation:YES]; + navigation_controller_.presentationController.delegate = + prompt_view_controller_; - [base_view_controller_ presentViewController:navigation_controller + [base_view_controller_ presentViewController:navigation_controller_ animated:YES completion:nil]; } @@ -74,15 +71,19 @@ void CardUnmaskPromptViewBridge::PerformClose() { base::WeakPtr<CardUnmaskPromptViewBridge> weak_this = weak_ptr_factory_.GetWeakPtr(); - [view_controller_.navigationController + [navigation_controller_ dismissViewControllerAnimated:YES completion:^{ if (weak_this) { - weak_this->DeleteSelf(); + weak_this->NavigationControllerDismissed(); } }]; } +void CardUnmaskPromptViewBridge::NavigationControllerDismissed() { + DeleteSelf(); +} + void CardUnmaskPromptViewBridge::DeleteSelf() { delete this; }
diff --git a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.h b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.h index 0443362..a86152365 100644 --- a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.h +++ b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.h
@@ -20,7 +20,8 @@ // new CVC and expiration date. Once the card is verified the prompt is // dismissed and the operation requiring the card verification is continued // (e.g: the card is autofilled in a payment form). -@interface CardUnmaskPromptViewController : ChromeTableViewController +@interface CardUnmaskPromptViewController + : ChromeTableViewController <UIAdaptivePresentationControllerDelegate> // Designated initializer. `bridge` must not be null. - (instancetype)initWithBridge:(autofill::CardUnmaskPromptViewBridge*)bridge NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.mm b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.mm index 73584bf..c1370fd 100644 --- a/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.mm +++ b/ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.mm
@@ -31,4 +31,12 @@ return self; } +#pragma mark - UIAdaptivePresentationControllerDelegate +- (void)presentationControllerDidDismiss: + (UIPresentationController*)presentationController { + // Notify bridge that UI was dismissed. + _bridge->NavigationControllerDismissed(); + _bridge = nullptr; +} + @end
diff --git a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm index 065bcbc..6aeb3a6 100644 --- a/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm +++ b/ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.mm
@@ -9,7 +9,6 @@ #import "base/bind.h" #import "base/callback.h" #import "base/check.h" -#import "base/feature_list.h" #import "base/memory/ptr_util.h" #import "base/notreached.h" #import "base/strings/string_util.h" @@ -48,7 +47,7 @@ #import "ios/chrome/browser/translate/chrome_ios_translate_client.h" #import "ios/chrome/browser/ui/autofill/card_expiration_date_fix_flow_view_bridge.h" #import "ios/chrome/browser/ui/autofill/card_name_fix_flow_view_bridge.h" -#import "ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h" +#import "ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h" #import "ios/chrome/browser/webdata_services/web_data_service_factory.h" #import "ios/chrome/common/channel_info.h" #import "ios/public/provider/chrome/browser/risk_data/risk_data_api.h" @@ -71,13 +70,6 @@ std::move(delegate)); } -CardUnmaskPromptView* CreateCardUnmaskPromptViewBridge( - CardUnmaskPromptControllerImpl* unmask_controller, - UIViewController* base_view_controller) { - return new LegacyCardUnmaskPromptViewBridge(unmask_controller, - base_view_controller); -} - } // namespace ChromeAutofillClientIOS::ChromeAutofillClientIOS( @@ -230,7 +222,7 @@ UnmaskCardReason reason, base::WeakPtr<CardUnmaskDelegate> delegate) { unmask_controller_.ShowPrompt( - base::BindOnce(&CreateCardUnmaskPromptViewBridge, + base::BindOnce(&autofill::CreateCardUnmaskPromptViewBridge, base::Unretained(&unmask_controller_), base::Unretained(base_view_controller_)), card, reason, delegate);
diff --git a/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h b/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h new file mode 100644 index 0000000..d73949d --- /dev/null +++ b/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h
@@ -0,0 +1,24 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_AUTOFILL_CREATE_CARD_UNMASK_PROMPT_VIEW_BRIDGE_H_ +#define IOS_CHROME_BROWSER_UI_AUTOFILL_CREATE_CARD_UNMASK_PROMPT_VIEW_BRIDGE_H_ + +#import "components/autofill/core/browser/ui/payments/card_unmask_prompt_view.h" + +@class UIViewController; + +namespace autofill { + +class CardUnmaskPromptController; + +// Creates the view bridge for the iOS implementation of the Card Unmask +// Prompt. The implementation returned may vary based on +// kAutofillEnableNewCardUnmaskPromptView feature flag. +CardUnmaskPromptView* CreateCardUnmaskPromptViewBridge( + CardUnmaskPromptController* unmask_controller, + UIViewController* base_view_controller); +} // namespace autofill + +#endif // IOS_CHROME_BROWSER_UI_AUTOFILL_CREATE_CARD_UNMASK_PROMPT_VIEW_BRIDGE_H_
diff --git a/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.mm b/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.mm new file mode 100644 index 0000000..493c81d --- /dev/null +++ b/ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.mm
@@ -0,0 +1,31 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h" + +#import "base/feature_list.h" +#import "components/autofill/core/browser/ui/payments/card_unmask_prompt_controller.h" +#import "ios/chrome/browser/ui/autofill/card_unmask_prompt_view_bridge.h" +#import "ios/chrome/browser/ui/autofill/features.h" +#import "ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace autofill { + +CardUnmaskPromptView* CreateCardUnmaskPromptViewBridge( + CardUnmaskPromptController* unmask_controller, + UIViewController* base_view_controller) { + if (base::FeatureList::IsEnabled(kAutofillEnableNewCardUnmaskPromptView)) { + return new CardUnmaskPromptViewBridge(unmask_controller, + base_view_controller); + } + + return new LegacyCardUnmaskPromptViewBridge(unmask_controller, + base_view_controller); +} + +} // namespace autofill
diff --git a/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h b/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h index 99eab9f..b2a8580 100644 --- a/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h +++ b/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h
@@ -49,9 +49,9 @@ // Closes the view. void PerformClose(); - // Deletes self. This should only be called by CardUnmaskPromptViewController - // after it finishes dismissing its own UI elements. - void DeleteSelf(); + // Called when `view_controller` was dismissed. + // This call destroys `this`. + void NavigationControllerDismissed(); protected: // The presented UINavigationController. @@ -61,6 +61,10 @@ LegacyCardUnmaskPromptViewController* card_view_controller_; private: + // Deletes self. Called after LegacyCardUnmaskPromptViewController finishes + // dismissing its own UI elements. + void DeleteSelf(); + // The controller `this` queries for logic and state. CardUnmaskPromptController* controller_; // weak
diff --git a/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.mm b/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.mm index 623a8b1..3a4e40a 100644 --- a/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.mm +++ b/ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.mm
@@ -73,9 +73,12 @@ [view_controller_ setModalPresentationStyle:UIModalPresentationFormSheet]; [view_controller_ setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; - // If this prompt is swiped away, it cannot be opened again. Work - // around this bug by preventing swipe-to-dismiss. - [view_controller_ setModalInPresentation:YES]; + // This will notify the prompt vc when its navigation vc is dismissed, + // so `this` can be released and `controller_` notified that the prompt + // was dismissed. + view_controller_.presentationController.delegate = + static_cast<id<UIAdaptivePresentationControllerDelegate>>( + card_view_controller_); [base_view_controller_ presentViewController:view_controller_ animated:YES @@ -118,12 +121,17 @@ void LegacyCardUnmaskPromptViewBridge::PerformClose() { base::WeakPtr<LegacyCardUnmaskPromptViewBridge> weak_this = weak_ptr_factory_.GetWeakPtr(); - [view_controller_ dismissViewControllerAnimated:YES - completion:^{ - if (weak_this) { - weak_this->DeleteSelf(); - } - }]; + [view_controller_ + dismissViewControllerAnimated:YES + completion:^{ + if (weak_this) { + weak_this->NavigationControllerDismissed(); + } + }]; +} + +void LegacyCardUnmaskPromptViewBridge::NavigationControllerDismissed() { + DeleteSelf(); } void LegacyCardUnmaskPromptViewBridge::DeleteSelf() { @@ -132,7 +140,9 @@ } // namespace autofill -@interface LegacyCardUnmaskPromptViewController () <UITextFieldDelegate> { +@interface LegacyCardUnmaskPromptViewController () < + UIAdaptivePresentationControllerDelegate, + UITextFieldDelegate> { UIBarButtonItem* _cancelButton; UIBarButtonItem* _verifyButton; CVCItem* _CVCItem; @@ -527,4 +537,11 @@ } } +#pragma mark - UIAdaptivePresentationControllerDelegate +- (void)presentationControllerDidDismiss: + (UIPresentationController*)presentationController { + // Notify bridge that UI was dismissed. + _bridge->NavigationControllerDismissed(); + _bridge = nullptr; +} @end
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn index 784e081..8b9a2e7 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn
@@ -174,6 +174,7 @@ "//ios/chrome/browser/infobars", "//ios/chrome/browser/ui/autofill", "//ios/chrome/browser/ui/autofill:bridges", + "//ios/chrome/browser/ui/autofill:features", "//ios/chrome/browser/web_state_list:test_support", "//ios/chrome/browser/web_state_list:web_state_list", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm index a66a3a3..126e7ec7 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester.mm
@@ -6,23 +6,12 @@ #import "components/autofill/core/browser/browser_autofill_manager.h" #import "ios/chrome/browser/browser_state/chrome_browser_state.h" -#import "ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h" +#import "ios/chrome/browser/ui/autofill/create_card_unmask_prompt_view_bridge.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -namespace { - -autofill::CardUnmaskPromptView* CreateCardUnmaskPromptViewBridge( - autofill::CardUnmaskPromptControllerImpl* controller, - UIViewController* base_view_controller) { - return new autofill::LegacyCardUnmaskPromptViewBridge(controller, - base_view_controller); -} - -} - FullCardRequester::FullCardRequester(UIViewController* base_view_controller, ChromeBrowserState* browser_state) : base_view_controller_(base_view_controller), @@ -49,7 +38,7 @@ autofill::AutofillClient::UnmaskCardReason reason, base::WeakPtr<autofill::CardUnmaskDelegate> delegate) { unmask_controller_.ShowPrompt( - base::BindOnce(&CreateCardUnmaskPromptViewBridge, + base::BindOnce(&autofill::CreateCardUnmaskPromptViewBridge, base::Unretained(&unmask_controller_), base::Unretained(base_view_controller_)), card, reason, delegate);
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester_unittest.mm b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester_unittest.mm index 1b9aea6..73f6f31 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester_unittest.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/full_card_requester_unittest.mm
@@ -8,6 +8,7 @@ #import "base/mac/foundation_util.h" #import "base/test/ios/wait_util.h" +#import "base/test/scoped_feature_list.h" #import "base/time/time.h" #import "components/autofill/core/browser/autofill_test_utils.h" #import "components/autofill/core/browser/browser_autofill_manager.h" @@ -18,7 +19,9 @@ #import "components/prefs/pref_service.h" #import "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #import "ios/chrome/browser/infobars/infobar_manager_impl.h" +#import "ios/chrome/browser/ui/autofill/card_unmask_prompt_view_controller.h" #import "ios/chrome/browser/ui/autofill/chrome_autofill_client_ios.h" +#import "ios/chrome/browser/ui/autofill/features.h" #import "ios/chrome/browser/ui/autofill/legacy_card_unmask_prompt_view_bridge.h" #import "ios/chrome/test/scoped_key_window.h" #import "ios/web/public/js_messaging/web_frames_manager.h" @@ -129,6 +132,8 @@ return personal_data_manager_.GetCreditCards(); } + base::test::ScopedFeatureList scoped_feature_list_; + private: web::WebTaskEnvironment task_environment_; std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; @@ -139,10 +144,14 @@ AutofillAgent* autofill_agent_; }; -// Tests that the FullCardRequester presents and dismisses the card unmask -// prompt view controller, when the full card is requested and when the user -// enters the CVC/expiration information respectively. -TEST_F(PaymentRequestFullCardRequesterTest, PresentAndDismiss) { +// Tests that the FullCardRequester presents and dismisses the legacy card +// unmask prompt, when the new prompt feature flag is disabled, the full card is +// requested and when the user enters the CVC/expiration information +// respectively. +TEST_F(PaymentRequestFullCardRequesterTest, PresentAndDismissLegacyPrompt) { + scoped_feature_list_.InitAndDisableFeature( + kAutofillEnableNewCardUnmaskPromptView); + UIViewController* base_view_controller = [[UIViewController alloc] init]; ScopedKeyWindow scoped_key_window_; [scoped_key_window_.Get() setRootViewController:base_view_controller]; @@ -167,6 +176,7 @@ UINavigationController* navigation_controller = base::mac::ObjCCast<UINavigationController>( base_view_controller.presentedViewController); + EXPECT_TRUE([navigation_controller.topViewController isMemberOfClass:[LegacyCardUnmaskPromptViewController class]]); @@ -182,3 +192,55 @@ true, base::Seconds(10)); EXPECT_EQ(nil, base_view_controller.presentedViewController); } + +// Tests that the FullCardRequester presents and dismisses the new card unmask +// prompt, when the new prompt feature flag is enabled, the full card is +// requested and when the user enters the CVC/expiration information +// respectively. +// This test will fail until the new cvc prompt is fully implemented. +// TODO(crbug.com/1347184) +TEST_F(PaymentRequestFullCardRequesterTest, + DISABLED_PresentAndDismissNewPrompt) { + scoped_feature_list_.InitAndEnableFeature( + kAutofillEnableNewCardUnmaskPromptView); + + UIViewController* base_view_controller = [[UIViewController alloc] init]; + ScopedKeyWindow scoped_key_window_; + [scoped_key_window_.Get() setRootViewController:base_view_controller]; + + FullCardRequester full_card_requester(base_view_controller, browser_state()); + + EXPECT_EQ(nil, base_view_controller.presentedViewController); + web::WebFrame* main_frame = + web_state()->GetWebFramesManager()->GetMainWebFrame(); + autofill::BrowserAutofillManager* autofill_manager = + autofill::AutofillDriverIOS::FromWebStateAndWebFrame(web_state(), + main_frame) + ->autofill_manager(); + FakeResultDelegate* fake_result_delegate = new FakeResultDelegate; + full_card_requester.GetFullCard(*credit_cards()[0], autofill_manager, + fake_result_delegate->GetWeakPtr()); + + // Spin the run loop to trigger the animation. + base::test::ios::SpinRunLoopWithMaxDelay(base::Seconds(1.0)); + EXPECT_TRUE([base_view_controller.presentedViewController + isMemberOfClass:[UINavigationController class]]); + UINavigationController* navigation_controller = + base::mac::ObjCCast<UINavigationController>( + base_view_controller.presentedViewController); + + EXPECT_TRUE([navigation_controller.topViewController + isMemberOfClass:[CardUnmaskPromptViewController class]]); + + full_card_requester.OnUnmaskVerificationResult( + autofill::AutofillClient::PaymentsRpcResult::kSuccess); + + // Wait until the view controller is ordered to be dismissed and the animation + // completes. + base::test::ios::WaitUntilCondition( + ^bool { + return !base_view_controller.presentedViewController; + }, + true, base::Seconds(10)); + EXPECT_EQ(nil, base_view_controller.presentedViewController); +}
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm index 9e23868..f3fb458 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
@@ -41,6 +41,7 @@ const char kTrendingQueriesHideShortcutsParam[] = "hide_shortcuts"; const char kTrendingQueriesDisabledFeedParam[] = "disabled_feed_only"; const char kTrendingQueriesSignedOutParam[] = "signed_out_only"; + // A parameter to indicate whether the native UI is enabled for the discover // feed. const char kDiscoverFeedIsNativeUIEnabled[] = "DiscoverFeedIsNativeUIEnabled";
diff --git a/ios/chrome/browser/ui/first_run/BUILD.gn b/ios/chrome/browser/ui/first_run/BUILD.gn index 87917ce3..99d3e0c 100644 --- a/ios/chrome/browser/ui/first_run/BUILD.gn +++ b/ios/chrome/browser/ui/first_run/BUILD.gn
@@ -9,6 +9,8 @@ "fre_field_trial.h", "ios_first_run_field_trials.cc", "ios_first_run_field_trials.h", + "trending_queries_field_trial.cc", + "trending_queries_field_trial.h", ] deps = [ "//base", @@ -18,6 +20,7 @@ "//components/version_info", "//ios/chrome/browser/first_run", "//ios/chrome/browser/ui:feature_flags", + "//ios/chrome/browser/ui/content_suggestions:feature_flags", "//ios/chrome/common", ] } @@ -189,6 +192,7 @@ sources = [ "first_run_util_unittest.mm", "fre_field_trial_unittest.mm", + "trending_queries_field_trial_unittest.mm", "welcome_to_chrome_view_controller_unittest.mm", ] deps = [ @@ -206,6 +210,7 @@ "//ios/chrome/browser/main:test_support", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/authentication", + "//ios/chrome/browser/ui/content_suggestions:feature_flags", "//ios/chrome/browser/ui/fancy_ui", "//ios/chrome/browser/ui/util", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc new file mode 100644 index 0000000..263073d3 --- /dev/null +++ b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.cc
@@ -0,0 +1,187 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/first_run/trending_queries_field_trial.h" + +#import "base/feature_list.h" +#import "base/metrics/field_trial.h" +#import "base/metrics/field_trial_params.h" +#import "components/prefs/pref_registry_simple.h" +#import "components/prefs/pref_service.h" +#import "components/version_info/version_info.h" +#import "ios/chrome/browser/first_run/first_run.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" +#import "ios/chrome/browser/ui/first_run/ios_first_run_field_trials.h" +#import "ios/chrome/common/channel_info.h" + +namespace { +// String local state preference with the name of the assigned trial group. +// Empty if no group has been assigned yet. +const char kTrialVersionPrefName[] = "trending_queries.trial_group"; +// Default local state pref value. +const int kDefaultPrefValue = -1; +// The current trial version; should be updated when the experiment is modified. +const int kCurrentTrialVersion = 1; + +// Group names for the Trending Queries feature. +const char kTrendingQueriesEnabledAllUsersGroup[] = "EnabledAllUsers-V1"; +const char kTrendingQueriesEnabledAllUsersHideShortcutsGroup[] = + "EnabledAllUsersHideShortcuts-V1"; +const char kTrendingQueriesEnabledDisabledFeedGroup[] = + "EnabledDisabledFeed-V1"; +const char kTrendingQueriesEnabledSignedOutGroup[] = "EnabledSignedOut-V1"; +const char kTrendingQueriesControlGroup[] = "Control-V1"; +const char kTrendingQueriesDefaultGroup[] = "Default"; + +// Returns a map of the group weights for each arm. +std::map<variations::VariationID, int> GetGroupWeights() { + std::map<variations::VariationID, int> weight_by_id = { + {kTrendingQueriesEnabledAllUsersID, 0}, + {kTrendingQueriesEnabledAllUsersHideShortcutsID, 0}, + {kTrendingQueriesEnabledDisabledFeedID, 0}, + {kTrendingQueriesEnabledSignedOutID, 0}, + {kTrendingQueriesControlID, 0}}; + switch (GetChannel()) { + case version_info::Channel::UNKNOWN: + case version_info::Channel::CANARY: + case version_info::Channel::DEV: + case version_info::Channel::BETA: + weight_by_id[kTrendingQueriesEnabledAllUsersID] = 10; + weight_by_id[kTrendingQueriesEnabledAllUsersHideShortcutsID] = 10; + weight_by_id[kTrendingQueriesEnabledDisabledFeedID] = 10; + weight_by_id[kTrendingQueriesEnabledSignedOutID] = 10; + weight_by_id[kTrendingQueriesControlID] = 10; + break; + case version_info::Channel::STABLE: + break; + } + return weight_by_id; +} + +} // namespace + +namespace trending_queries_field_trial { + +// Creates the trial config, initializes the trial that puts clients into +// different groups, and returns the version number of the current trial. There +// are 5 groups other than the default group: +// - Control +// - Enabled for All users +// - Enabled for All users and Hide Shortcuts +// - Enabled for signed out users +// - Enabled for users that had the feed disabled +int CreateTrendingQueriesTrial( + std::map<variations::VariationID, int> weight_by_id, + const base::FieldTrial::EntropyProvider& low_entropy_provider, + base::FeatureList* feature_list) { + FirstRunFieldTrialConfig config(kTrendingQueriesModule.name); + + // Control group. + config.AddGroup(kTrendingQueriesControlGroup, kTrendingQueriesControlID, + weight_by_id[kTrendingQueriesControlID]); + + // Experiment Groups + config.AddGroup(kTrendingQueriesEnabledAllUsersGroup, + kTrendingQueriesEnabledAllUsersID, + weight_by_id[kTrendingQueriesEnabledAllUsersID]); + base::FieldTrialParams params; + params[kTrendingQueriesHideShortcutsParam] = "false"; + params[kTrendingQueriesDisabledFeedParam] = "false"; + params[kTrendingQueriesSignedOutParam] = "false"; + base::AssociateFieldTrialParams(kTrendingQueriesModule.name, + kTrendingQueriesEnabledAllUsersGroup, params); + + config.AddGroup(kTrendingQueriesEnabledAllUsersHideShortcutsGroup, + kTrendingQueriesEnabledAllUsersHideShortcutsID, + weight_by_id[kTrendingQueriesEnabledAllUsersHideShortcutsID]); + params[kTrendingQueriesHideShortcutsParam] = "true"; + params[kTrendingQueriesDisabledFeedParam] = "false"; + params[kTrendingQueriesSignedOutParam] = "false"; + base::AssociateFieldTrialParams( + kTrendingQueriesModule.name, + kTrendingQueriesEnabledAllUsersHideShortcutsGroup, params); + + config.AddGroup(kTrendingQueriesEnabledDisabledFeedGroup, + kTrendingQueriesEnabledDisabledFeedID, + weight_by_id[kTrendingQueriesEnabledDisabledFeedID]); + params[kTrendingQueriesHideShortcutsParam] = "false"; + params[kTrendingQueriesDisabledFeedParam] = "true"; + params[kTrendingQueriesSignedOutParam] = "false"; + base::AssociateFieldTrialParams(kTrendingQueriesModule.name, + kTrendingQueriesEnabledDisabledFeedGroup, + params); + + config.AddGroup(kTrendingQueriesEnabledSignedOutGroup, + kTrendingQueriesEnabledSignedOutID, + weight_by_id[kTrendingQueriesEnabledSignedOutID]); + params[kTrendingQueriesHideShortcutsParam] = "true"; + params[kTrendingQueriesDisabledFeedParam] = "false"; + params[kTrendingQueriesSignedOutParam] = "true"; + base::AssociateFieldTrialParams(kTrendingQueriesModule.name, + kTrendingQueriesEnabledSignedOutGroup, + params); + scoped_refptr<base::FieldTrial> trial = config.CreateOneTimeRandomizedTrial( + kTrendingQueriesDefaultGroup, low_entropy_provider); + + // Finalize the group choice and activates the trial - similar to a variation + // config that's marked with |starts_active| true. This is required for + // studies that register variation ids, so they don't reveal extra information + // beyond the low-entropy source. + const std::string& group_name = trial->group_name(); + if (group_name == kTrendingQueriesEnabledAllUsersGroup || + group_name == kTrendingQueriesEnabledAllUsersHideShortcutsGroup || + group_name == kTrendingQueriesEnabledDisabledFeedGroup || + group_name == kTrendingQueriesEnabledSignedOutGroup) { + feature_list->RegisterFieldTrialOverride( + kTrendingQueriesModule.name, base::FeatureList::OVERRIDE_ENABLE_FEATURE, + trial.get()); + } + + return kCurrentTrialVersion; +} + +void RegisterLocalStatePrefs(PrefRegistrySimple* registry) { + registry->RegisterIntegerPref(kTrialVersionPrefName, kDefaultPrefValue); +} + +void Create(const base::FieldTrial::EntropyProvider& low_entropy_provider, + base::FeatureList* feature_list, + PrefService* local_state) { + // The client would not be assigned to any group because features controlled + // by the experiment is already overridden from the command line. This handles + // scenarios where FRE is forced for testing purposes. + // Also return early if the feature is already enabled for this client. This + // is needed for explicit flag settings in chrome://flags. + if (feature_list->IsFeatureOverriddenFromCommandLine( + kTrendingQueriesModule.name) || + IsTrendingQueriesModuleEnabled()) { + return; + } + + if (local_state->GetInteger(kTrialVersionPrefName) != kDefaultPrefValue) { + // User has already been bucketed. + return; + } + + // Create trial and group for the first time, and store the experiment + // version in prefs for subsequent runs. + int trial_version = CreateTrendingQueriesTrial( + GetGroupWeights(), low_entropy_provider, feature_list); + // Persist the experiment version for subsequent runs. + local_state->SetInteger(kTrialVersionPrefName, trial_version); +} + +namespace testing { + +int CreateTrendingQueriesTrialForTesting( + std::map<variations::VariationID, int> weights_by_id, + const base::FieldTrial::EntropyProvider& low_entropy_provider, + base::FeatureList* feature_list) { + return CreateTrendingQueriesTrial(weights_by_id, low_entropy_provider, + feature_list); +} + +} // namespace testing + +} // namespace trending_queries_field_trial
diff --git a/ios/chrome/browser/ui/first_run/trending_queries_field_trial.h b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.h new file mode 100644 index 0000000..09dc36f5 --- /dev/null +++ b/ios/chrome/browser/ui/first_run/trending_queries_field_trial.h
@@ -0,0 +1,50 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_FIRST_RUN_TRENDING_QUERIES_FIELD_TRIAL_H_ +#define IOS_CHROME_BROWSER_UI_FIRST_RUN_TRENDING_QUERIES_FIELD_TRIAL_H_ + +#include "base/metrics/field_trial.h" +#include "components/variations/variations_associated_data.h" + +class PrefService; +class PrefRegistrySimple; + +namespace { + +// Variation IDs for Trending Queries experiment arms. +const variations::VariationID kTrendingQueriesEnabledAllUsersID = 3350760; +const variations::VariationID kTrendingQueriesEnabledAllUsersHideShortcutsID = + 3350761; +const variations::VariationID kTrendingQueriesEnabledDisabledFeedID = 3350762; +const variations::VariationID kTrendingQueriesEnabledSignedOutID = 3350763; +const variations::VariationID kTrendingQueriesControlID = 3350764; + +} // namespace + +namespace trending_queries_field_trial { + +void RegisterLocalStatePrefs(PrefRegistrySimple* registry); + +// Creates a field trial to control the Trending Queries feature so that it is +// shown on the NTP after first run. +// +// The trial group chosen on first run is persisted to local state prefs. +void Create(const base::FieldTrial::EntropyProvider& low_entropy_provider, + base::FeatureList* feature_list, + PrefService* local_state); + +namespace testing { + +// Exposes CreateTrendingQueriesTrial() for testing FieldTrial set-up. +int CreateTrendingQueriesTrialForTesting( + std::map<variations::VariationID, int> weights_by_id, + const base::FieldTrial::EntropyProvider& low_entropy_provider, + base::FeatureList* feature_list); + +} // namespace testing + +} // namespace trending_queries_field_trial + +#endif // IOS_CHROME_BROWSER_UI_FIRST_RUN_TRENDING_QUERIES_FIELD_TRIAL_H_
diff --git a/ios/chrome/browser/ui/first_run/trending_queries_field_trial_unittest.mm b/ios/chrome/browser/ui/first_run/trending_queries_field_trial_unittest.mm new file mode 100644 index 0000000..4953248 --- /dev/null +++ b/ios/chrome/browser/ui/first_run/trending_queries_field_trial_unittest.mm
@@ -0,0 +1,134 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/first_run/trending_queries_field_trial.h" + +#import "base/feature_list.h" +#import "base/metrics/field_trial.h" +#import "base/metrics/field_trial_param_associator.h" +#import "base/test/mock_entropy_provider.h" +#import "base/test/scoped_feature_list.h" +#import "components/variations/variations_associated_data.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" +#import "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +// Tests for field trial creation for the Trending Queries feature. +class TrendingQueriesFieldTrialTest : public PlatformTest { + protected: + void SetUp() override { + std::map<variations::VariationID, int> weight_by_id_ = { + {kTrendingQueriesEnabledAllUsersID, 0}, + {kTrendingQueriesEnabledAllUsersHideShortcutsID, 0}, + {kTrendingQueriesEnabledDisabledFeedID, 0}, + {kTrendingQueriesEnabledSignedOutID, 0}, + {kTrendingQueriesControlID, 0}}; + } + + void TearDown() override { + scoped_feature_list_.Reset(); + base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting(); + } + + base::test::ScopedFeatureList scoped_feature_list_; + std::map<variations::VariationID, int> weight_by_id_; + base::MockEntropyProvider low_entropy_provider_; +}; + +// Tests control field trial. +TEST_F(TrendingQueriesFieldTrialTest, TestControl) { + auto feature_list = std::make_unique<base::FeatureList>(); + weight_by_id_[kTrendingQueriesControlID] = 100; + trending_queries_field_trial::testing::CreateTrendingQueriesTrialForTesting( + weight_by_id_, low_entropy_provider_, feature_list.get()); + + // Substitute the existing feature list with the one with field trial + // configurations we are testing, and check assertions. + scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); + ASSERT_TRUE(base::FieldTrialList::IsTrialActive(kTrendingQueriesModule.name)); + EXPECT_FALSE(base::FeatureList::IsEnabled(kTrendingQueriesModule)); +} + +// Tests kTrendingQueriesEnabledAllUsersID field trial. +TEST_F(TrendingQueriesFieldTrialTest, TestEnabledAllUsers) { + auto feature_list = std::make_unique<base::FeatureList>(); + weight_by_id_[kTrendingQueriesEnabledAllUsersID] = 100; + trending_queries_field_trial::testing::CreateTrendingQueriesTrialForTesting( + weight_by_id_, low_entropy_provider_, feature_list.get()); + + // Substitute the existing feature list with the one with field trial + // configurations we are testing, and check assertions. + scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); + ASSERT_TRUE(base::FieldTrialList::IsTrialActive(kTrendingQueriesModule.name)); + EXPECT_TRUE(base::FeatureList::IsEnabled(kTrendingQueriesModule)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesHideShortcutsParam, true)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesDisabledFeedParam, true)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesSignedOutParam, true)); +} + +// Tests kTrendingQueriesEnabledAllUsersHideShortcutsID field trial. +TEST_F(TrendingQueriesFieldTrialTest, TestEnabledHideShortcuts) { + auto feature_list = std::make_unique<base::FeatureList>(); + weight_by_id_[kTrendingQueriesEnabledAllUsersHideShortcutsID] = 100; + trending_queries_field_trial::testing::CreateTrendingQueriesTrialForTesting( + weight_by_id_, low_entropy_provider_, feature_list.get()); + + // Substitute the existing feature list with the one with field trial + // configurations we are testing, and check assertions. + scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); + ASSERT_TRUE(base::FieldTrialList::IsTrialActive(kTrendingQueriesModule.name)); + EXPECT_TRUE(base::FeatureList::IsEnabled(kTrendingQueriesModule)); + EXPECT_TRUE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesHideShortcutsParam, false)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesDisabledFeedParam, true)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesSignedOutParam, true)); +} + +// Tests kTrendingQueriesEnabledDisabledFeedID field trial. +TEST_F(TrendingQueriesFieldTrialTest, TestEnabledDisabledFeed) { + auto feature_list = std::make_unique<base::FeatureList>(); + weight_by_id_[kTrendingQueriesEnabledDisabledFeedID] = 100; + trending_queries_field_trial::testing::CreateTrendingQueriesTrialForTesting( + weight_by_id_, low_entropy_provider_, feature_list.get()); + + // Substitute the existing feature list with the one with field trial + // configurations we are testing, and check assertions. + scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); + ASSERT_TRUE(base::FieldTrialList::IsTrialActive(kTrendingQueriesModule.name)); + EXPECT_TRUE(base::FeatureList::IsEnabled(kTrendingQueriesModule)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesHideShortcutsParam, true)); + EXPECT_TRUE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesDisabledFeedParam, false)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesSignedOutParam, true)); +} + +// Tests kTrendingQueriesEnabledSignedOutID field trial. +TEST_F(TrendingQueriesFieldTrialTest, TestEnabledSignedOut) { + auto feature_list = std::make_unique<base::FeatureList>(); + weight_by_id_[kTrendingQueriesEnabledSignedOutID] = 100; + trending_queries_field_trial::testing::CreateTrendingQueriesTrialForTesting( + weight_by_id_, low_entropy_provider_, feature_list.get()); + + // Substitute the existing feature list with the one with field trial + // configurations we are testing, and check assertions. + scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); + ASSERT_TRUE(base::FieldTrialList::IsTrialActive(kTrendingQueriesModule.name)); + EXPECT_TRUE(base::FeatureList::IsEnabled(kTrendingQueriesModule)); + EXPECT_TRUE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesHideShortcutsParam, false)); + EXPECT_FALSE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesDisabledFeedParam, true)); + EXPECT_TRUE(base::GetFieldTrialParamByFeatureAsBool( + kTrendingQueriesModule, kTrendingQueriesSignedOutParam, false)); +}
diff --git a/ios/chrome/browser/web/web_performance_metrics/BUILD.gn b/ios/chrome/browser/web/web_performance_metrics/BUILD.gn index 50afbe87..4817adc 100644 --- a/ios/chrome/browser/web/web_performance_metrics/BUILD.gn +++ b/ios/chrome/browser/web/web_performance_metrics/BUILD.gn
@@ -3,7 +3,7 @@ # found in the LICENSE file. import("//ios/build/config.gni") -import("//ios/web/public/js_messaging/optimize_js.gni") +import("//ios/web/public/js_messaging/optimize_ts.gni") source_set("web_performance_metrics") { configs += [ "//build/config/compiler:enable_arc" ] @@ -39,9 +39,9 @@ sources = [ "web_performance_metrics_java_script_feature_unittest.mm" ] } -optimize_js("web_performance_metrics_js") { +optimize_ts("web_performance_metrics_js") { visibility = [ ":web_performance_metrics" ] - primary_script = "resources/web_performance_metrics.js" - sources = [ "resources/web_performance_metrics.js" ] + sources = [ "resources/web_performance_metrics.ts" ] + deps = [ "//ios/web/public/js_messaging:util_scripts" ] }
diff --git a/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js b/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.ts similarity index 71% rename from ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js rename to ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.ts index 7ab2f7d..505ede2ad 100644 --- a/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.js +++ b/ios/chrome/browser/web/web_performance_metrics/resources/web_performance_metrics.ts
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import {sendWebKitMessage} from "//ios/web/public/js_messaging/resources/utils.js"; + const EVENT_TYPES = [ 'mousedown', 'keydown', @@ -19,17 +21,18 @@ // will only be called for the main frame and // subframes that are same-origin relative to the // main frame. -function processPaintEvents(paintEvents, observer) { +function processPaintEvents(paintEvents: PerformanceObserverEntryList, + observer: PerformanceObserver): void { for (const event of paintEvents.getEntriesByName(FIRST_CONTENTFUL_PAINT)){ // The performance.timing.navigationStart property has been deprecated. // TODO(crbug.com/1273083) - let response = { + const response = { 'metric' : 'FirstContentfulPaint', 'frameNavigationStartTime' : performance.timing.navigationStart, 'value' : event.startTime, } - __gCrWeb.common.sendWebKitMessage( + sendWebKitMessage( WEB_PERFORMANCE_METRICS_HANDLER_NAME, response); @@ -39,21 +42,21 @@ // Sends the First Input Delay time for // each frame in a website to the browser. -function processInputEvent(inputEvent) { - let currentTime = performance.now(); - let delta = currentTime - inputEvent.timeStamp; - let response = { +function processInputEvent(inputEvent: Event): void { + const currentTime = performance.now(); + const delta = currentTime - inputEvent.timeStamp; + const response = { 'metric' : 'FirstInputDelay', 'value' : delta, 'cached' : loadedFromCache } - __gCrWeb.common.sendWebKitMessage( + sendWebKitMessage( WEB_PERFORMANCE_METRICS_HANDLER_NAME, response); EVENT_TYPES.forEach((type) => { - removeEventListenerFromWindow(type, processInputEvent, { capture: true }); + window.removeEventListener(type, processInputEvent, { capture: true }); }); } @@ -63,7 +66,7 @@ // event listeners to capture and forward // the Web Performance Metrics back to the // browser. -function processPageShowEvent(pageshow) { +function processPageShowEvent(pageshow: PageTransitionEvent): void { if (pageshow.persisted) { loadedFromCache = true; registerInputEventListeners(); @@ -74,9 +77,9 @@ // used for collecting the First Input Delay // upon the user navigating away from the // webpage -function processPageHideEvent() { +function processPageHideEvent(): void { EVENT_TYPES.forEach((type) => { - removeEventListenerFromWindow(type, processInputEvent, { capture: true }); + window.removeEventListener(type, processInputEvent, { capture: true }); }); loadedFromCache = false; } @@ -85,8 +88,8 @@ // Once the PerformanceObserver receives the // 'first-contentful-paint' event, it captures the time of the // event and forwards the result to the browser. -function registerPerformanceObserver(){ - let observer = new PerformanceObserver(processPaintEvents); +function registerPerformanceObserver(): void { + const observer = new PerformanceObserver(processPaintEvents); observer.observe({ entryTypes : ['paint'] }); } @@ -94,9 +97,9 @@ // event type. Once the event listener receives an event, // it calculates the first input delay and forwards the // result ot the browser. -function registerInputEventListeners() { +function registerInputEventListeners(): void { EVENT_TYPES.forEach((type) => { - addEventListenerToWindow(type, + window.addEventListener(type, processInputEvent, {capture: true, passive: true}); @@ -105,29 +108,17 @@ // Registers passive event listeners for the pageshow // and pagehide events -function registerPageCacheListeners() { - addEventListenerToWindow('pageshow', +function registerPageCacheListeners(): void { + window.addEventListener('pageshow', processPageShowEvent, {capture: true, passive: true}); - addEventListenerToWindow('pagehide', + window.addEventListener('pagehide', processPageHideEvent, { capture: true, passive: true}); } -// Wrapper function for adding an event listener to the -// window. -function addEventListenerToWindow(type, callback, options) { - window.addEventListener(type, callback, options); -} - -// Wrapper function for removing an event listener from the -// window. -function removeEventListenerFromWindow(type, callback, options) { - window.removeEventListener(type, callback, options); -} - registerPerformanceObserver(); registerInputEventListeners(); registerPageCacheListeners();
diff --git a/ios/chrome/test/earl_grey/scoped_allow_crash_on_startup.mm b/ios/chrome/test/earl_grey/scoped_allow_crash_on_startup.mm index 9c664be3..9de2dd6 100644 --- a/ios/chrome/test/earl_grey/scoped_allow_crash_on_startup.mm +++ b/ios/chrome/test/earl_grey/scoped_allow_crash_on_startup.mm
@@ -77,9 +77,10 @@ containsString:@"Couldn’t communicate with a helper application. Try " @"your operation again. If that fails, quit and " @"relaunch the application and try again."] || - [description containsString:@" crashed in "]) { - [[NSException exceptionWithName:@"XCTIssue" reason:description - userInfo:nil] raise]; + [description containsString:@" crashed in "] || + [description containsString:@"Failed to get matching snapshot"]) { + // Ignore these exceptions, since we expect to crash. + return; } INVOKE_ORIGINAL_IMP1(void, @selector(swizzledRecordIssue:), issue); }
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index 58f745ee..14ed13a 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -598,9 +598,7 @@ // Enable VP9 k-SVC decoding with HW decoder for webrtc use case. const base::Feature kVp9kSVCHWDecoding { "Vp9kSVCHWDecoding", -// TODO(crbug.com/1325698): Remove defined(ARCH_CPU_X86_FAMILY) once this is -// enabled by default on ChromeOS ARM devices. -#if defined(ARCH_CPU_X86_FAMILY) && BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(IS_CHROMEOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT
diff --git a/media/cdm/cdm_capability.cc b/media/cdm/cdm_capability.cc index a0a427a0..c731bcf 100644 --- a/media/cdm/cdm_capability.cc +++ b/media/cdm/cdm_capability.cc
@@ -8,6 +8,27 @@ namespace media { +VideoCodecInfo::VideoCodecInfo() = default; + +VideoCodecInfo::VideoCodecInfo( + base::flat_set<VideoCodecProfile> video_codec_profiles, + bool supports_clear_lead) + : video_codec_profiles(std::move(video_codec_profiles)), + supports_clear_lead(supports_clear_lead) {} + +VideoCodecInfo::VideoCodecInfo( + base::flat_set<VideoCodecProfile> video_codec_profiles) + : video_codec_profiles(std::move(video_codec_profiles)) {} + +VideoCodecInfo::VideoCodecInfo(const VideoCodecInfo& other) = default; + +VideoCodecInfo::~VideoCodecInfo() = default; + +bool operator==(const VideoCodecInfo& lhs, const VideoCodecInfo& rhs) { + return lhs.video_codec_profiles == rhs.video_codec_profiles && + lhs.supports_clear_lead == rhs.supports_clear_lead; +} + CdmCapability::CdmCapability() = default; CdmCapability::CdmCapability(
diff --git a/media/cdm/cdm_capability.h b/media/cdm/cdm_capability.h index 1fb346d4..92aea1d 100644 --- a/media/cdm/cdm_capability.h +++ b/media/cdm/cdm_capability.h
@@ -17,10 +17,32 @@ namespace media { +struct MEDIA_EXPORT VideoCodecInfo { + VideoCodecInfo(); + VideoCodecInfo(base::flat_set<VideoCodecProfile> video_codec_profiles, + bool supports_clear_lead); + VideoCodecInfo(base::flat_set<VideoCodecProfile> video_codec_profiles); + VideoCodecInfo(const VideoCodecInfo& other); + ~VideoCodecInfo(); + + // Set of VideoCodecProfiles supported. If no profiles for a + // particular codec are specified, then it is assumed that all + // profiles are supported by the CDM. + base::flat_set<VideoCodecProfile> video_codec_profiles; + + // We default to supports_clear_lead = true because in majority of cases, + // the CDM does support clear lead. In a few cases, (b/231241602), we + // need to adjust this boolean to handle cases where clear lead results + // in issues for the user. + bool supports_clear_lead = true; +}; + +bool MEDIA_EXPORT operator==(const VideoCodecInfo& lhs, + const VideoCodecInfo& rhs); + // Capabilities supported by a Content Decryption Module. struct MEDIA_EXPORT CdmCapability { - using VideoCodecMap = std::map<VideoCodec, std::vector<VideoCodecProfile>>; - + using VideoCodecMap = std::map<VideoCodec, VideoCodecInfo>; CdmCapability(); CdmCapability(std::vector<AudioCodec> audio_codecs, VideoCodecMap video_codecs, @@ -35,11 +57,8 @@ // separately. std::vector<AudioCodec> audio_codecs; - // Map of video codecs and associated profiles supported by the CDM - // (e.g. vp8). This is the set of codecs supported by the media pipeline - // using the CDM. For a supported VideoCodec, if the vector of - // VideoCodecProfiles is empty, then it assumes that all profiles of the - // specified codecs may actually be supported. + // Map of video codecs and a struct containing the associated profiles + // supported by the CDM (e.g. vp8) and whether clear lead is supported. VideoCodecMap video_codecs; // List of encryption schemes supported by the CDM (e.g. cenc).
diff --git a/media/mojo/mojom/cdm_capability_mojom_traits.cc b/media/mojo/mojom/cdm_capability_mojom_traits.cc index 7377c3c6..62d7648 100644 --- a/media/mojo/mojom/cdm_capability_mojom_traits.cc +++ b/media/mojo/mojom/cdm_capability_mojom_traits.cc
@@ -22,6 +22,20 @@ } // namespace // static +bool StructTraits<media::mojom::VideoCodecInfoDataView, media::VideoCodecInfo>:: + Read(media::mojom::VideoCodecInfoDataView input, + media::VideoCodecInfo* output) { + std::vector<media::VideoCodecProfile> video_codec_profiles; + if (!input.ReadVideoCodecProfiles(&video_codec_profiles)) { + return false; + } + + *output = media::VideoCodecInfo(std::move(video_codec_profiles), + input.supports_clear_lead()); + return true; +} + +// static bool StructTraits<media::mojom::CdmCapabilityDataView, media::CdmCapability>:: Read(media::mojom::CdmCapabilityDataView input, media::CdmCapability* output) { @@ -37,12 +51,6 @@ if (!input.ReadVideoCodecs(&video_codecs)) return false; - // Ensure that the VideoCodecProfiles in each entry are unique. - for (const auto& codec : video_codecs) { - if (!AreUnique(codec.second)) - return false; - } - std::vector<media::EncryptionScheme> encryption_schemes; if (!input.ReadEncryptionSchemes(&encryption_schemes)) return false;
diff --git a/media/mojo/mojom/cdm_capability_mojom_traits.h b/media/mojo/mojom/cdm_capability_mojom_traits.h index 0480528e..5144f2f 100644 --- a/media/mojo/mojom/cdm_capability_mojom_traits.h +++ b/media/mojo/mojom/cdm_capability_mojom_traits.h
@@ -18,6 +18,22 @@ namespace mojo { template <> +struct StructTraits<media::mojom::VideoCodecInfoDataView, + media::VideoCodecInfo> { + static const base::flat_set<media::VideoCodecProfile>& video_codec_profiles( + const media::VideoCodecInfo& input) { + return input.video_codec_profiles; + } + + static const bool& supports_clear_lead(const media::VideoCodecInfo& input) { + return input.supports_clear_lead; + } + + static bool Read(media::mojom::VideoCodecInfoDataView input, + media::VideoCodecInfo* output); +}; + +template <> struct StructTraits<media::mojom::CdmCapabilityDataView, media::CdmCapability> { static const std::vector<media::AudioCodec>& audio_codecs( const media::CdmCapability& input) {
diff --git a/media/mojo/mojom/key_system_support.mojom b/media/mojo/mojom/key_system_support.mojom index c001fc6c..7c0437e 100644 --- a/media/mojo/mojom/key_system_support.mojom +++ b/media/mojo/mojom/key_system_support.mojom
@@ -7,6 +7,18 @@ import "media/mojo/mojom/content_decryption_module.mojom"; import "media/mojo/mojom/media_types.mojom"; +struct VideoCodecInfo { + // Array of VideoCodecProfiles supported. If no profiles for a + // particular codec are specified, then it is assumed that all + // profiles are supported by the CDM. + array<VideoCodecProfile> video_codec_profiles; + + // A boolean that contains info about whether the video codec + // supports clear lead. This defaults to true except for specific + // cases involving Windows codecs. + bool supports_clear_lead = true; +}; + // TODO(xhwang): Use "set" instead of "array" if supported by mojom. struct CdmCapability { // List of audio codecs supported by the CDM (e.g. opus). This does not @@ -14,11 +26,9 @@ // codec profiles separately. The list of supported codecs should be unique. array<AudioCodec> audio_codecs; - // Map from video codecs to associated profiles supported by the CDM - // (e.g. vp8). If no profiles for a particular codec are specified, then - // it is assumed that all profiles are supported by the CDM. The list of - // profiles for each codec should be unique. - map<VideoCodec, array<VideoCodecProfile>> video_codecs; + // Map of video codecs and a struct containing the associated profiles + // supported by the CDM (e.g. vp8) and whether clear lead is supported. + map<VideoCodec, VideoCodecInfo> video_codecs; array<EncryptionScheme> encryption_schemes; array<CdmSessionType> session_types;
diff --git a/media/mojo/services/media_foundation_service.cc b/media/mojo/services/media_foundation_service.cc index 57f2063..2bff81b 100644 --- a/media/mojo/services/media_foundation_service.cc +++ b/media/mojo/services/media_foundation_service.cc
@@ -317,7 +317,7 @@ if (IsTypeSupportedInternal(cdm_factory, key_system, is_hw_secure, type)) { // IsTypeSupported() does not support querying profiling, so specify {} // to indicate all relevant profiles should be considered supported. - const std::vector<media::VideoCodecProfile> kAllProfiles = {}; + const media::VideoCodecInfo kAllProfiles; capability.video_codecs.emplace(video_codec, kAllProfiles); } } @@ -350,9 +350,9 @@ // of the encryption schemes which work for all codecs. base::flat_set<EncryptionScheme> intersection( std::begin(kAllEncryptionSchemes), std::end(kAllEncryptionSchemes)); - for (auto codec : capability.video_codecs) { + for (const auto& [video_codec, _] : capability.video_codecs) { const auto schemes = GetSupportedEncryptionSchemes( - cdm_factory, key_system, is_hw_secure, codec.first, robustness); + cdm_factory, key_system, is_hw_secure, video_codec, robustness); intersection = base::STLSetIntersection<base::flat_set<EncryptionScheme>>( intersection, schemes); }
diff --git a/native_client_sdk/PRESUBMIT.py b/native_client_sdk/PRESUBMIT.py deleted file mode 100644 index 4c7cea13..0000000 --- a/native_client_sdk/PRESUBMIT.py +++ /dev/null
@@ -1,43 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Top-level presubmit script for native_client_sdk. - -See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts -for more details on the presubmit API built into depot_tools. -""" - -USE_PYTHON3 = True - - -def CommonChecks(input_api, output_api): - output = [] - disabled_warnings = [ - 'F0401', # Unable to import module - 'R0401', # Cyclic import - 'W0613', # Unused argument - 'W0403', # relative import warnings - 'E1103', # subprocess.communicate() generates these :( - 'R0201', # method could be function (doesn't reference self) - ] - files_to_skip = [ - r'src[\\\/]build_tools[\\\/]tests[\\\/].*', - r'src[\\\/]build_tools[\\\/]sdk_tools[\\\/]third_party[\\\/].*', - r'src[\\\/]doc[\\\/]*', - r'src[\\\/]gonacl_appengine[\\\/]*', - ] - canned = input_api.canned_checks - output.extend(canned.RunPylint(input_api, output_api, - files_to_skip=files_to_skip, - disabled_warnings=disabled_warnings, - version='1.5')) - return output - - -def CheckChangeOnUpload(input_api, output_api): - return CommonChecks(input_api, output_api) - - -def CheckChangeOnCommit(input_api, output_api): - return CommonChecks(input_api, output_api)
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index 1bfe204..91d210fa 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -56,6 +56,7 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/base/features.h" @@ -75,6 +76,7 @@ namespace net { static constexpr int kMinutesInTwelveHours = 12 * 60; +static constexpr int kMinutesInTwentyFourHours = 24 * 60; namespace { @@ -493,18 +495,32 @@ base::TimeDelta clock_skew = (current - server_time); // Record the magnitude (absolute value) of the skew in minutes. int clock_skew_magnitude = clock_skew.magnitude().InMinutes(); + // Determine the new expiry with clock skew factored in. + Time adjusted_expiry = parsed_expiry + (current - server_time); if (clock_skew.is_positive() || clock_skew.is_zero()) { UMA_HISTOGRAM_CUSTOM_COUNTS("Cookie.ClockSkew.AddMinutes", clock_skew_magnitude, 1, kMinutesInTwelveHours, 100); + UMA_HISTOGRAM_CUSTOM_COUNTS("Cookie.ClockSkew.AddMinutes12To24Hours", + clock_skew_magnitude, kMinutesInTwelveHours, + kMinutesInTwentyFourHours, 100); + // Also record the range of minutes added that allowed the cookie to + // avoid expiring immediately. + if (parsed_expiry <= Time::Now() && adjusted_expiry > Time::Now()) { + UMA_HISTOGRAM_CUSTOM_COUNTS( + "Cookie.ClockSkew.WithoutAddMinutesExpires", clock_skew_magnitude, + 1, kMinutesInTwentyFourHours, 100); + } } else if (clock_skew.is_negative()) { // These histograms only support positive numbers, so negative skews // will be converted to positive (via magnitude) before recording. UMA_HISTOGRAM_CUSTOM_COUNTS("Cookie.ClockSkew.SubtractMinutes", clock_skew_magnitude, 1, kMinutesInTwelveHours, 100); + UMA_HISTOGRAM_CUSTOM_COUNTS( + "Cookie.ClockSkew.SubtractMinutes12To24Hours", clock_skew_magnitude, + kMinutesInTwelveHours, kMinutesInTwentyFourHours, 100); } - Time adjusted_expiry = parsed_expiry + (current - server_time); // Record if we were going to expire the cookie before we added the clock // skew. UMA_HISTOGRAM_BOOLEAN( @@ -600,6 +616,11 @@ CookiePrefix prefix = GetCookiePrefix(parsed_cookie.Name()); bool is_cookie_prefix_valid = IsCookiePrefixValid(prefix, url, parsed_cookie); RecordCookiePrefixMetrics(prefix, is_cookie_prefix_valid); + + if (parsed_cookie.Name() == "") { + is_cookie_prefix_valid = !HasHiddenPrefixName(parsed_cookie.Value()); + } + if (!is_cookie_prefix_valid) { DVLOG(net::cookie_util::kVlogSetCookies) << "Create() failed because the cookie violated prefix rules."; @@ -811,6 +832,11 @@ net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX); } + if (name == "" && HasHiddenPrefixName(value)) { + status->AddExclusionReason( + net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX); + } + if (!IsCookieSamePartyValid(same_party, secure, same_site)) { status->AddExclusionReason( net::CookieInclusionStatus::EXCLUDE_INVALID_SAMEPARTY); @@ -1529,6 +1555,9 @@ break; } + if (name_ == "" && HasHiddenPrefixName(value_)) + return false; + if (!IsCookieSamePartyValid(same_party_, secure_, same_site_)) return false; @@ -1652,6 +1681,40 @@ } } +// static +bool CanonicalCookie::HasHiddenPrefixName( + const base::StringPiece cookie_value) { + // Skip BWS as defined by HTTPSEM as SP or HTAB (0x20 or 0x9). + base::StringPiece value_without_BWS = + base::TrimString(cookie_value, " \t", base::TRIM_LEADING); + + const base::StringPiece host_prefix = "__Host-"; + + // Compare the value to the host_prefix. + if (base::StartsWith(value_without_BWS, host_prefix)) { + // The prefix matches, now check if the value string contains a subsequent + // '='. + if (value_without_BWS.find_first_of('=', host_prefix.size()) != + base::StringPiece::npos) { + // This value contains a hidden prefix name. + return true; + } + return false; + } + + // Do a similar check for the secure prefix + const base::StringPiece secure_prefix = "__Secure-"; + + if (base::StartsWith(value_without_BWS, secure_prefix)) { + if (value_without_BWS.find_first_of('=', secure_prefix.size()) != + base::StringPiece::npos) { + return true; + } + } + + return false; +} + bool CanonicalCookie::IsRecentlyCreated(base::TimeDelta age_threshold) const { return (base::Time::Now() - creation_date_) <= age_threshold; }
diff --git a/net/cookies/canonical_cookie.h b/net/cookies/canonical_cookie.h index 87785e92..1ddf1b15 100644 --- a/net/cookies/canonical_cookie.h +++ b/net/cookies/canonical_cookie.h
@@ -11,6 +11,7 @@ #include <vector> #include "base/gtest_prod_util.h" +#include "base/strings/string_piece.h" #include "base/time/time.h" #include "net/base/net_export.h" #include "net/cookies/cookie_access_result.h" @@ -430,6 +431,7 @@ private: FRIEND_TEST_ALL_PREFIXES(CanonicalCookieTest, TestPrefixHistograms); + FRIEND_TEST_ALL_PREFIXES(CanonicalCookieTest, TestHasHiddenPrefixName); // This constructor does not validate or canonicalize their inputs; // the resulting CanonicalCookies should not be relied on to be canonical @@ -494,6 +496,9 @@ CookieEffectiveSameSite GetEffectiveSameSite( CookieAccessSemantics access_semantics) const; + // Checks for values that could be misinterpreted as a cookie name prefix. + static bool HasHiddenPrefixName(const base::StringPiece cookie_value); + // Returns whether the cookie was created at most |age_threshold| ago. bool IsRecentlyCreated(base::TimeDelta age_threshold) const;
diff --git a/net/cookies/canonical_cookie_unittest.cc b/net/cookies/canonical_cookie_unittest.cc index 538d0bc..df637f65 100644 --- a/net/cookies/canonical_cookie_unittest.cc +++ b/net/cookies/canonical_cookie_unittest.cc
@@ -2483,6 +2483,18 @@ absl::nullopt /* cookie_partition_key */, &status)); EXPECT_TRUE(status.HasExactlyExclusionReasonsForTesting( {CookieInclusionStatus::EXCLUDE_INVALID_PREFIX})); + + // Hidden __Secure- prefixes should be rejected. + EXPECT_FALSE(CanonicalCookie::Create( + https_url, "=__Secure-A=B; Secure", creation_time, server_time, + absl::nullopt /* cookie_partition_key */, &status)); + EXPECT_TRUE(status.HasExactlyExclusionReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_INVALID_PREFIX})); + + // While tricky, this isn't considered hidden and is fine. + EXPECT_TRUE(CanonicalCookie::Create( + https_url, "A=__Secure-A=B; Secure", creation_time, server_time, + absl::nullopt /* cookie_partition_key */)); } TEST(CanonicalCookieTest, HostCookiePrefix) { @@ -2567,6 +2579,18 @@ EXPECT_TRUE(CanonicalCookie::Create( https_url, "__HostA=B; Domain=" + domain + "; Secure;", creation_time, server_time, absl::nullopt /* cookie_partition_key */)); + + // Hidden __Host- prefixes should be rejected. + EXPECT_FALSE(CanonicalCookie::Create( + https_url, "=__Host-A=B; Path=/; Secure;", creation_time, server_time, + absl::nullopt /* cookie_partition_key */, &status)); + EXPECT_TRUE(status.HasExactlyExclusionReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_INVALID_PREFIX})); + + // While tricky, this isn't considered hidden and is fine. + EXPECT_TRUE(CanonicalCookie::Create( + https_url, "A=__Host-A=B; Path=/; Secure;", creation_time, server_time, + absl::nullopt /* cookie_partition_key */)); } TEST(CanonicalCookieTest, CanCreateSecureCookiesFromAnyScheme) { @@ -3031,6 +3055,31 @@ CookiePartitionKey::FromURLForTesting( GURL("https://toplevelsite.com"))) ->IsCanonical()); + + // Hidden cookie prefixes. + EXPECT_FALSE(CanonicalCookie::CreateUnsafeCookieForTesting( + "", "__Secure-a=b", "x.y", "/", base::Time(), base::Time(), + base::Time(), base::Time(), true, false, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_LOW, false) + ->IsCanonical()); + + EXPECT_FALSE(CanonicalCookie::CreateUnsafeCookieForTesting( + "", "__Host-a=b", "x.y", "/", base::Time(), base::Time(), + base::Time(), base::Time(), true, false, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_LOW, false) + ->IsCanonical()); + + EXPECT_TRUE(CanonicalCookie::CreateUnsafeCookieForTesting( + "a", "__Secure-a=b", "x.y", "/", base::Time(), base::Time(), + base::Time(), base::Time(), true, false, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_LOW, false) + ->IsCanonical()); + + EXPECT_TRUE(CanonicalCookie::CreateUnsafeCookieForTesting( + "a", "__Host-a=b", "x.y", "/", base::Time(), base::Time(), + base::Time(), base::Time(), true, false, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_LOW, false) + ->IsCanonical()); } TEST(CanonicalCookieTest, TestSetCreationDate) { @@ -3683,6 +3732,39 @@ false /*same_party*/, absl::nullopt /*partition_key*/, &status)); EXPECT_TRUE(status.IsInclude()); + // Cookies with hidden prefixes should be rejected. + + EXPECT_FALSE(CanonicalCookie::CreateSanitizedCookie( + GURL("https://www.foo.com"), "", "__Host-A=B", "", "/", two_hours_ago, + one_hour_from_now, one_hour_ago, true, false, + CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT, + false /*same_party*/, absl::nullopt /*partition_key*/, &status)); + EXPECT_TRUE(status.HasExactlyExclusionReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_INVALID_PREFIX})); + + EXPECT_FALSE(CanonicalCookie::CreateSanitizedCookie( + GURL("https://www.foo.com"), "", "__Secure-A=B", "", "/", two_hours_ago, + one_hour_from_now, one_hour_ago, true, false, + CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT, + false /*same_party*/, absl::nullopt /*partition_key*/, &status)); + EXPECT_TRUE(status.HasExactlyExclusionReasonsForTesting( + {CookieInclusionStatus::EXCLUDE_INVALID_PREFIX})); + + // While tricky, this aren't considered hidden prefixes and should succeed. + EXPECT_TRUE(CanonicalCookie::CreateSanitizedCookie( + GURL("https://www.foo.com"), "A", "__Host-A=B", "", "/", two_hours_ago, + one_hour_from_now, one_hour_ago, true, false, + CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT, + false /*same_party*/, absl::nullopt /*partition_key*/, &status)); + EXPECT_TRUE(status.IsInclude()); + + EXPECT_TRUE(CanonicalCookie::CreateSanitizedCookie( + GURL("https://www.foo.com"), "A", "__Secure-A=B", "", "/", two_hours_ago, + one_hour_from_now, one_hour_ago, true, false, + CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT, + false /*same_party*/, absl::nullopt /*partition_key*/, &status)); + EXPECT_TRUE(status.IsInclude()); + // SameParty attribute requires Secure and forbids SameSite=Strict. EXPECT_TRUE(CanonicalCookie::CreateSanitizedCookie( GURL("https://www.foo.com"), "A", "B", ".www.foo.com", "/", two_hours_ago, @@ -5273,4 +5355,47 @@ histograms.ExpectBucketCount(kFromStorageWithValidLengthHistogram, kValid, 1); } +TEST(CanonicalCookieTest, TestHasHiddenPrefixName) { + const struct { + const char* value; + bool result; + } kTestCases[] = { + {"", false}, + {" ", false}, + {"foobar=", false}, + {"foo=bar", false}, + {" \t ", false}, + {"\t", false}, + {"__Secure-abc", false}, + {"__Secur=e-abc", false}, + {"__Secureabc", false}, + {"__Host-abc", false}, + {"__Hos=t-abc", false}, + {"_Host", false}, + {" __Secure-abc", false}, + {"\t__Host-", false}, + {"a__Host-abc=123", false}, + {"a__Secure-abc=123", false}, + {"__Host-abc=", true}, + {"__Host-abc=123", true}, + {" __Host-abc=123", true}, + {" __Host-abc=", true}, + {"\t\t\t\t\t__Host-abc=123", true}, + {"\t __Host-abc=", true}, + {"__Secure-abc=", true}, + {"__Secure-abc=123", true}, + {" __Secure-abc=123", true}, + {" __Secure-abc=", true}, + {"\t\t\t\t\t__Secure-abc=123", true}, + {"\t __Secure-abc=", true}, + {"__Secure-abc=123=d=4=fg=", true}, + }; + + for (auto test_case : kTestCases) { + EXPECT_EQ(CanonicalCookie::HasHiddenPrefixName(test_case.value), + test_case.result) + << test_case.value << " failed check"; + } +} + } // namespace net
diff --git a/net/url_request/url_request.h b/net/url_request/url_request.h index 1ead2510..532ce52 100644 --- a/net/url_request/url_request.h +++ b/net/url_request/url_request.h
@@ -85,13 +85,6 @@ // class NET_EXPORT URLRequest : public base::SupportsUserData { public: - // Callback function implemented by protocol handlers to create new jobs. - // The factory may return NULL to indicate an error, which will cause other - // factories to be queried. If no factory handles the request, then the - // default job will be used. - typedef URLRequestJob*(ProtocolFactory)(URLRequest* request, - const std::string& scheme); - // Max number of http redirects to follow. The Fetch spec says: "If // request's redirect count is twenty, return a network error." // https://fetch.spec.whatwg.org/#http-redirect-fetch
diff --git a/net/url_request/url_request_filter.cc b/net/url_request/url_request_filter.cc index 9a19dde..a07bf83 100644 --- a/net/url_request/url_request_filter.cc +++ b/net/url_request/url_request_filter.cc
@@ -70,10 +70,6 @@ DCHECK(OnMessageLoopForInterceptorRemoval()); int removed = hostname_interceptor_map_.erase(make_pair(scheme, hostname)); DCHECK(removed); - - // Note that we don't unregister from the URLRequest ProtocolFactory as - // this would leave no protocol factory for the remaining hostname and URL - // handlers. } bool URLRequestFilter::AddUrlInterceptor( @@ -96,9 +92,6 @@ DCHECK(OnMessageLoopForInterceptorRemoval()); size_t removed = url_interceptor_map_.erase(url.spec()); DCHECK(removed); - // Note that we don't unregister from the URLRequest ProtocolFactory as - // this would leave no protocol factory for the remaining hostname and URL - // handlers. } void URLRequestFilter::ClearHandlers() {
diff --git a/net/url_request/url_request_filter.h b/net/url_request/url_request_filter.h index 134f029..48d7a7e9 100644 --- a/net/url_request/url_request_filter.h +++ b/net/url_request/url_request_filter.h
@@ -59,8 +59,7 @@ void RemoveUrlHandler(const GURL& url); - // Clear all the existing URL handlers and unregister with the - // ProtocolFactory. Resets the hit count. + // Clear all the existing URL and hostname handlers. Resets the hit count. void ClearHandlers(); // Returns the number of times a handler was used to service a request.
diff --git a/remoting/host/policy_watcher.cc b/remoting/host/policy_watcher.cc index e82e73f..e03ac1e 100644 --- a/remoting/host/policy_watcher.cc +++ b/remoting/host/policy_watcher.cc
@@ -176,35 +176,34 @@ std::unique_ptr<base::DictionaryValue> PolicyWatcher::GetDefaultPolicies() { auto result = std::make_unique<base::DictionaryValue>(); result->SetBoolKey(key::kRemoteAccessHostFirewallTraversal, true); - result->SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) - result->SetBoolKey(key::kRemoteAccessHostMatchUsername, false); -#endif result->Set(key::kRemoteAccessHostClientDomainList, std::make_unique<base::ListValue>()); result->Set(key::kRemoteAccessHostDomainList, std::make_unique<base::ListValue>()); + result->SetBoolKey(key::kRemoteAccessHostAllowRelayedConnection, true); + result->SetStringKey(key::kRemoteAccessHostUdpPortRange, ""); + result->SetIntKey(key::kRemoteAccessHostClipboardSizeBytes, -1); + result->SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) + result->SetBoolKey(key::kRemoteAccessHostMatchUsername, false); +#endif +#if !BUILDFLAG(IS_CHROMEOS) + result->SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); result->SetStringKey(key::kRemoteAccessHostTokenUrl, std::string()); result->SetStringKey(key::kRemoteAccessHostTokenValidationUrl, std::string()); result->SetStringKey(key::kRemoteAccessHostTokenValidationCertificateIssuer, std::string()); result->SetBoolKey(key::kRemoteAccessHostAllowClientPairing, true); result->SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, true); - result->SetBoolKey(key::kRemoteAccessHostAllowRelayedConnection, true); - result->SetStringKey(key::kRemoteAccessHostUdpPortRange, ""); - -#if BUILDFLAG(IS_WIN) - result->SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, - false); -#endif - result->SetIntKey(key::kRemoteAccessHostClipboardSizeBytes, -1); - result->SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); -#if !BUILDFLAG(IS_CHROMEOS_ASH) result->SetBoolKey(key::kRemoteAccessHostAllowFileTransfer, true); result->SetBoolKey(key::kRemoteAccessHostEnableUserInterface, true); result->SetBoolKey(key::kRemoteAccessHostAllowRemoteAccessConnections, true); result->SetIntKey(key::kRemoteAccessHostMaximumSessionDurationMinutes, 0); #endif +#if BUILDFLAG(IS_WIN) + result->SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, + false); +#endif return result; } @@ -302,6 +301,7 @@ } } +#if !BUILDFLAG(IS_CHROMEOS) namespace { void CopyDictionaryValue(const base::DictionaryValue& from, base::DictionaryValue& to, @@ -312,6 +312,7 @@ } } } // namespace +#endif std::unique_ptr<base::DictionaryValue> PolicyWatcher::StoreNewAndReturnChangedPolicies( @@ -330,6 +331,7 @@ iter.Advance(); } +#if !BUILDFLAG(IS_CHROMEOS) // If one of ThirdPartyAuthConfig policies changed, we need to include all. if (changed_policies->FindKey(key::kRemoteAccessHostTokenUrl) || changed_policies->FindKey(key::kRemoteAccessHostTokenValidationUrl) || @@ -342,6 +344,7 @@ CopyDictionaryValue(*new_policies, *changed_policies, key::kRemoteAccessHostTokenValidationCertificateIssuer); } +#endif // Save the new policies. effective_policies_.swap(new_policies);
diff --git a/remoting/host/policy_watcher_unittest.cc b/remoting/host/policy_watcher_unittest.cc index 968da96..8cf2b5d7 100644 --- a/remoting/host/policy_watcher_unittest.cc +++ b/remoting/host/policy_watcher_unittest.cc
@@ -143,10 +143,14 @@ unknown_policies_.SetStringKey("UnknownPolicyTwo", std::string()); unknown_policies_.SetBoolKey("RemoteAccessHostUnknownPolicyThree", true); +#if !BUILDFLAG(IS_CHROMEOS) pairing_true_.SetBoolKey(key::kRemoteAccessHostAllowClientPairing, true); pairing_false_.SetBoolKey(key::kRemoteAccessHostAllowClientPairing, false); gnubby_auth_true_.SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, true); gnubby_auth_false_.SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, false); + curtain_true_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, true); + curtain_false_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); +#endif relay_true_.SetBoolKey(key::kRemoteAccessHostAllowRelayedConnection, true); relay_false_.SetBoolKey(key::kRemoteAccessHostAllowRelayedConnection, false); @@ -160,12 +164,11 @@ port_range_malformed_domain_full_.SetKey(key::kRemoteAccessHostDomainList, host_domain.Clone()); - curtain_true_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, true); - curtain_false_.SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) username_true_.SetBoolKey(key::kRemoteAccessHostMatchUsername, true); username_false_.SetBoolKey(key::kRemoteAccessHostMatchUsername, false); #endif +#if !BUILDFLAG(IS_CHROMEOS) third_party_auth_partial_.SetStringKey(key::kRemoteAccessHostTokenUrl, "https://token.com"); third_party_auth_partial_.SetStringKey( @@ -177,6 +180,7 @@ third_party_auth_cert_empty_.MergeDictionary(&third_party_auth_partial_); third_party_auth_cert_empty_.SetStringKey( key::kRemoteAccessHostTokenValidationCertificateIssuer, ""); +#endif #if BUILDFLAG(IS_WIN) remote_assistance_uiaccess_true_.SetBoolKey( @@ -321,9 +325,12 @@ dict.SetStringKey(key::kRemoteAccessHostUdpPortRange, ""); dict.SetKey(key::kRemoteAccessHostClientDomainList, base::ListValue()); dict.SetKey(key::kRemoteAccessHostDomainList, base::ListValue()); + dict.SetInteger(key::kRemoteAccessHostClipboardSizeBytes, -1); + dict.SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) dict.SetBoolKey(key::kRemoteAccessHostMatchUsername, false); #endif +#if !BUILDFLAG(IS_CHROMEOS) dict.SetBoolKey(key::kRemoteAccessHostRequireCurtain, false); dict.SetStringKey(key::kRemoteAccessHostTokenUrl, ""); dict.SetStringKey(key::kRemoteAccessHostTokenValidationUrl, ""); @@ -331,18 +338,15 @@ ""); dict.SetBoolKey(key::kRemoteAccessHostAllowClientPairing, true); dict.SetBoolKey(key::kRemoteAccessHostAllowGnubbyAuth, true); -#if BUILDFLAG(IS_WIN) - dict.SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, - false); -#endif - dict.SetInteger(key::kRemoteAccessHostClipboardSizeBytes, -1); - dict.SetBoolKey(key::kRemoteAccessHostAllowRemoteSupportConnections, true); -#if !BUILDFLAG(IS_CHROMEOS_ASH) dict.SetBoolKey(key::kRemoteAccessHostAllowFileTransfer, true); dict.SetBoolKey(key::kRemoteAccessHostEnableUserInterface, true); dict.SetBoolKey(key::kRemoteAccessHostAllowRemoteAccessConnections, true); dict.SetIntKey(key::kRemoteAccessHostMaximumSessionDurationMinutes, 0); #endif +#if BUILDFLAG(IS_WIN) + dict.SetBoolKey(key::kRemoteAccessHostAllowUiAccessForRemoteAssistance, + false); +#endif ASSERT_THAT(&dict, IsPolicies(&GetDefaultValues())) << "Sanity check that defaults expected by the test code " @@ -562,7 +566,7 @@ "RemoteAccessHostdomain", "RemoteAccessHostPolicyForFutureVersion")); -#if !BUILDFLAG(IS_CHROMEOS_ASH) +#if !BUILDFLAG(IS_CHROMEOS) TEST_F(PolicyWatcherTest, PairingFalseThenTrue) { testing::InSequence sequence; EXPECT_CALL(mock_policy_callback_, @@ -592,7 +596,7 @@ SetPolicies(gnubby_auth_false_); SetPolicies(gnubby_auth_true_); } -#endif // !BUILDFLAG(IS_CHROMEOS_ASH) +#endif // !BUILDFLAG(IS_CHROMEOS) TEST_F(PolicyWatcherTest, RemoteAssistanceUiAccess) { testing::InSequence sequence; @@ -722,15 +726,6 @@ i.Advance()) { expected_schema[i.key()] = i.value().type(); } -#if BUILDFLAG(IS_CHROMEOS_ASH) - // Me2Me Policies are not supported on ChromeOS. - expected_schema.erase(key::kRemoteAccessHostAllowGnubbyAuth); - expected_schema.erase(key::kRemoteAccessHostAllowClientPairing); - expected_schema.erase(key::kRemoteAccessHostRequireCurtain); - expected_schema.erase(key::kRemoteAccessHostTokenUrl); - expected_schema.erase(key::kRemoteAccessHostTokenValidationUrl); - expected_schema.erase(key::kRemoteAccessHostTokenValidationCertificateIssuer); -#endif std::map<std::string, base::Value::Type> actual_schema; const policy::Schema* schema = GetPolicySchema();
diff --git a/testing/buildbot/chromium.android.fyi.json b/testing/buildbot/chromium.android.fyi.json index e8396ba3..0561bb5 100644 --- a/testing/buildbot/chromium.android.fyi.json +++ b/testing/buildbot/chromium.android.fyi.json
@@ -8389,91 +8389,6 @@ "--additional-apk=apks/WebLayerShellSystemWebView.apk", "--test-runner-outdir", ".", - "--implementation-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--client-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android30.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_client_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_client_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android30", - "path": ".android_emulator/generic_android30" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android30" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_client_from_99" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", "--client-outdir", ".", "--test-expectations", @@ -8893,91 +8808,6 @@ "test": "weblayer_skew_tests", "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", "variant_id": "with_impl_from_104" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", - "--client-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", - "--implementation-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--impl-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android30.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_impl_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_impl_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android30", - "path": ".android_emulator/generic_android30" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android30" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_impl_from_99" } ] },
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 6914b80b..a32e426 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -46685,91 +46685,6 @@ "--additional-apk=apks/WebLayerShellSystemWebView.apk", "--test-runner-outdir", ".", - "--implementation-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--client-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_client_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_client_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android29", - "path": ".android_emulator/generic_android29" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android29" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_client_from_99" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", "--client-outdir", ".", "--test-expectations", @@ -47189,91 +47104,6 @@ "test": "weblayer_skew_tests", "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", "variant_id": "with_impl_from_104" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", - "--client-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", - "--implementation-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--impl-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_impl_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_impl_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android29", - "path": ".android_emulator/generic_android29" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android29" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_impl_from_99" } ] }, @@ -47709,91 +47539,6 @@ "--additional-apk=apks/ChromePublic.apk", "--test-runner-outdir", ".", - "--implementation-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--client-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests_with_chrome with_client_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests_with_chrome with_client_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android23", - "path": ".android_emulator/generic_android23" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android23" - } - ] - }, - "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": "weblayer_skew_tests_with_chrome", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests_with_chrome/", - "variant_id": "with_client_from_99" - }, - { - "args": [ - "--additional-apk=apks/ChromePublic.apk", - "--test-runner-outdir", - ".", "--client-outdir", ".", "--test-expectations", @@ -48213,91 +47958,6 @@ "test": "weblayer_skew_tests_with_chrome", "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests_with_chrome/", "variant_id": "with_impl_from_104" - }, - { - "args": [ - "--additional-apk=apks/ChromePublic.apk", - "--test-runner-outdir", - ".", - "--client-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/AOSP_SystemWebView.apk", - "--implementation-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--impl-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests_with_chrome with_impl_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests_with_chrome with_impl_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android23", - "path": ".android_emulator/generic_android23" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android23" - } - ] - }, - "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": "weblayer_skew_tests_with_chrome", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests_with_chrome/", - "variant_id": "with_impl_from_99" } ] }, @@ -48801,91 +48461,6 @@ "--additional-apk=apks/WebLayerShellSystemWebView.apk", "--test-runner-outdir", ".", - "--implementation-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--client-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_client_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_client_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android27", - "path": ".android_emulator/generic_android27" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android27" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_client_from_99" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", "--client-outdir", ".", "--test-expectations", @@ -49305,91 +48880,6 @@ "test": "weblayer_skew_tests", "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", "variant_id": "with_impl_from_104" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", - "--client-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--implementation-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--impl-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_impl_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_impl_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android27", - "path": ".android_emulator/generic_android27" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android27" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_impl_from_99" } ] }, @@ -49893,91 +49383,6 @@ "--additional-apk=apks/WebLayerShellSystemWebView.apk", "--test-runner-outdir", ".", - "--implementation-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--client-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--client-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_client_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_client_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android28", - "path": ".android_emulator/generic_android28" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android28" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_client_from_99" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", "--client-outdir", ".", "--test-expectations", @@ -50397,91 +49802,6 @@ "test": "weblayer_skew_tests", "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", "variant_id": "with_impl_from_104" - }, - { - "args": [ - "--additional-apk=apks/WebLayerShellSystemWebView.apk", - "--test-runner-outdir", - ".", - "--client-outdir", - ".", - "--test-expectations", - "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--webview-apk-path=apks/SystemWebView.apk", - "--implementation-outdir", - "../../weblayer_instrumentation_test_M99/out/Release", - "--impl-version=99", - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "weblayer_skew_tests with_impl_from_99" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "name": "weblayer_skew_tests with_impl_from_99", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M99", - "revision": "version:99.0.4844.88" - }, - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4|e2-standard-4", - "os": "Ubuntu-18.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "generic_android28", - "path": ".android_emulator/generic_android28" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "generic_android28" - } - ] - }, - "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": "weblayer_skew_tests", - "test_id_prefix": "ninja://weblayer/browser/android/javatests:weblayer_skew_tests/", - "variant_id": "with_impl_from_99" } ] },
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 6e2c84a..bbd30f3 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -1061,7 +1061,7 @@ "--browser=cros-chrome", "--passthrough", "-v", - "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --force_high_performance_gpu --disable-features=BackgroundVideoPauseOptimization --disable-background-media-suspend", + "--extra-browser-args=--log-level=0 --js-flags=--expose-gc --force_high_performance_gpu --disable-features=BackgroundVideoPauseOptimization --disable-background-media-suspend --disable-renderer-backgrounding", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", "--jobs=1", "--remote=127.0.0.1",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 589e5f5..60fa6f22 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -3715,7 +3715,7 @@ 'mac_optional_gpu_tests_rel': { 'args': [ # Added to debug crbug.com/1293967. - '--extra-browser-args=--disable-background-media-suspend', + '--extra-browser-args=--disable-background-media-suspend --disable-renderer-backgrounding', ], }, }, @@ -3767,7 +3767,7 @@ 'chromeos-amd64-generic-rel': { 'args': [ # Added to debug crbug.com/1293967. - '--extra-browser-args=--disable-features=BackgroundVideoPauseOptimization --disable-background-media-suspend', + '--extra-browser-args=--disable-features=BackgroundVideoPauseOptimization --disable-background-media-suspend --disable-renderer-backgrounding', ], 'swarming': { 'quickrun_shards': 40,
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 224d905e..66f4bc0 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -6915,13 +6915,11 @@ 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', ] } }, @@ -6934,13 +6932,11 @@ 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', ] } }, @@ -6958,13 +6954,11 @@ 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_ONE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_TWO_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_THREE_MILESTONE', 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FOUR_MILESTONE', - 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE', ] } },
diff --git a/testing/buildbot/tryserver.chromium.mac.json b/testing/buildbot/tryserver.chromium.mac.json index e113983a..6e582003 100644 --- a/testing/buildbot/tryserver.chromium.mac.json +++ b/testing/buildbot/tryserver.chromium.mac.json
@@ -1258,7 +1258,7 @@ "--browser=release", "--passthrough", "-v", - "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=gl --use-cmd-decoder=passthrough --force_high_performance_gpu --disable-background-media-suspend", + "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-gl=angle --use-angle=gl --use-cmd-decoder=passthrough --force_high_performance_gpu --disable-background-media-suspend --disable-renderer-backgrounding", "--read-abbreviated-json-results-from=../../content/test/data/gpu/webgl_conformance_tests_output.json", "--jobs=4" ],
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index 0f31fb2..9377691 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -647,30 +647,6 @@ ] } }, - 'WEBLAYER_10_AND_M_IMPL_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE': { - 'args': [ - '--test-runner-outdir', - '.', - '--client-outdir', - '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/AOSP_SystemWebView.apk', - '--implementation-outdir', - '../../weblayer_instrumentation_test_M99/out/Release', - '--impl-version=99' - ], - 'identifier': 'with_impl_from_99', - 'swarming': { - 'cipd_packages': [ - { - 'cipd_package': 'chromium/testing/weblayer-x86', - 'location': 'weblayer_instrumentation_test_M99', - 'revision': 'version:99.0.4844.88' - } - ] - } - }, 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MILESTONE': { 'args': [ '--webview-apk-path=apks/SystemWebView.apk', @@ -791,30 +767,6 @@ ] } }, - 'WEBLAYER_IMPL_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE': { - 'args': [ - '--test-runner-outdir', - '.', - '--client-outdir', - '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', - '--implementation-outdir', - '../../weblayer_instrumentation_test_M99/out/Release', - '--impl-version=99' - ], - 'identifier': 'with_impl_from_99', - 'swarming': { - 'cipd_packages': [ - { - 'cipd_package': 'chromium/testing/weblayer-x86', - 'location': 'weblayer_instrumentation_test_M99', - 'revision': 'version:99.0.4844.88' - } - ] - } - }, 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MILESTONE': { 'args': [ '--webview-apk-path=apks/SystemWebView.apk', @@ -935,30 +887,6 @@ ] } }, - 'WEBLAYER_CLIENT_SKEW_TESTS_NTH_MINUS_FIVE_MILESTONE': { - 'args': [ - '--test-runner-outdir', - '.', - '--implementation-outdir', - '.', - '--test-expectations', - '../../weblayer/browser/android/javatests/skew/expectations.txt', - '--webview-apk-path=apks/SystemWebView.apk', - '--client-outdir', - '../../weblayer_instrumentation_test_M99/out/Release', - '--client-version=99' - ], - 'identifier': 'with_client_from_99', - 'swarming': { - 'cipd_packages': [ - { - 'cipd_package': 'chromium/testing/weblayer-x86', - 'location': 'weblayer_instrumentation_test_M99', - 'revision': 'version:99.0.4844.88' - } - ] - } - }, 'CROS_ATLAS_RELEASE_LKGM': { 'skylab': { 'cros_board': 'atlas', @@ -1253,4 +1181,4 @@ 'win10_nvidia_gtx_1660_stable', ], }, -} \ No newline at end of file +}
diff --git a/testing/scripts/run_finch_smoke_tests_android.py b/testing/scripts/run_finch_smoke_tests_android.py index 77af282..cd2cbab 100755 --- a/testing/scripts/run_finch_smoke_tests_android.py +++ b/testing/scripts/run_finch_smoke_tests_android.py
@@ -74,12 +74,14 @@ from skia_gold_infra import finch_skia_gold_utils from run_wpt_tests import add_emulator_args, get_device +LOGCAT_TAG = 'finch_test_runner_py' LOGCAT_FILTERS = [ 'chromium:v', 'cr_*:v', 'DEBUG:I', 'StrictMode:D', - 'WebView*:v' + 'WebView*:v', + '%s:I' % LOGCAT_TAG ] logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) @@ -144,6 +146,23 @@ # for Chrome and WebLayer. return True + @contextlib.contextmanager + def _archive_logcat(self, filename, endpoint_name): + with logcat_monitor.LogcatMonitor( + self._device.adb, + filter_specs=LOGCAT_FILTERS, + output_file=filename, + check_error=False): + try: + self._device.RunShellCommand(['log', '-p', 'i', '-t', LOGCAT_TAG, + 'START {}'.format(endpoint_name)], + check_return=True) + yield + finally: + self._device.RunShellCommand(['log', '-p', 'i', '-t', LOGCAT_TAG, + 'END {}'.format(endpoint_name)], + check_return=True) + def parse_args(self, args=None): super(FinchTestCase, self).parse_args(args) if (not self.options.finch_seed_path or @@ -290,10 +309,6 @@ return _process_test_leaves(results_dict['tests']) @contextlib.contextmanager - def _install_apks(self): - yield - - @contextlib.contextmanager def install_apks(self): """Install apks for testing""" self._device.Uninstall(self.browser_package_name) @@ -323,11 +338,18 @@ self.layout_test_results_subdir = ('%s_smoke_test_artifacts' % test_run_variation) self.test_specific_browser_args = extra_browser_args or [] - - # Make sure the browser is not running before the tests run - self.stop_browser() - ret = super(FinchTestCase, self).run_test() - self.stop_browser() + logcat_file = os.path.join( + os.path.dirname(self.options.isolated_script_test_output), + self.layout_test_results_subdir, + '{}_{}_test_run_logcat.txt'.format(self.product_name(), + test_run_variation)) + with self._archive_logcat(logcat_file, + '{} {} tests'.format(self.product_name(), + test_run_variation)): + # Make sure the browser is not running before the tests run + self.stop_browser() + ret = super(FinchTestCase, self).run_test() + self.stop_browser() self._include_variation_prefix(test_run_variation) self.process_and_upload_results() @@ -539,29 +561,36 @@ Returns: None """ - app_data_dir = posixpath.join( - self._device.GetApplicationDataDirectory(self.browser_package_name), - self.app_user_sub_dir()) - self._device.RunShellCommand(['mkdir', '-p', app_data_dir], - run_as=self.browser_package_name) + logcat_file = os.path.join( + os.path.dirname(self.options.isolated_script_test_output), + 'install_seed_for_on_device.txt') - seed_path = posixpath.join(app_data_dir, 'variations_seed') - seed_new_path = posixpath.join(app_data_dir, 'variations_seed_new') - seed_stamp = posixpath.join(app_data_dir, 'variations_stamp') + with self._archive_logcat( + logcat_file, + 'install seed on device {}'.format(self._device.serial)): + app_data_dir = posixpath.join( + self._device.GetApplicationDataDirectory(self.browser_package_name), + self.app_user_sub_dir()) + self._device.RunShellCommand(['mkdir', '-p', app_data_dir], + run_as=self.browser_package_name) - self._device.adb.Push(self.options.finch_seed_path, seed_path) - self._device.adb.Push(self.options.finch_seed_path, seed_new_path) - self._device.RunShellCommand( - ['touch', seed_stamp], check_return=True, - run_as=self.browser_package_name) + seed_path = posixpath.join(app_data_dir, 'variations_seed') + seed_new_path = posixpath.join(app_data_dir, 'variations_seed_new') + seed_stamp = posixpath.join(app_data_dir, 'variations_stamp') - # We need to make the WebView shell package an owner of the seeds, - # see crbug.com/1191169#c19 - user_id = self._device.GetUidForPackage(self.browser_package_name) - logger.info('Setting owner of seed files to %r', user_id) - self._device.RunShellCommand(['chown', user_id, seed_path], as_root=True) - self._device.RunShellCommand( - ['chown', user_id, seed_new_path], as_root=True) + self._device.adb.Push(self.options.finch_seed_path, seed_path) + self._device.adb.Push(self.options.finch_seed_path, seed_new_path) + self._device.RunShellCommand( + ['touch', seed_stamp], check_return=True, + run_as=self.browser_package_name) + + # We need to make the WebView shell package an owner of the seeds, + # see crbug.com/1191169#c19 + user_id = self._device.GetUidForPackage(self.browser_package_name) + logger.info('Setting owner of seed files to %r', user_id) + self._device.RunShellCommand(['chown', user_id, seed_path], as_root=True) + self._device.RunShellCommand( + ['chown', user_id, seed_new_path], as_root=True) class WebLayerFinchTestCase(FinchTestCase):
diff --git a/third_party/android_deps/BUILD.gn b/third_party/android_deps/BUILD.gn index 5b3cda05..f462bc1 100644 --- a/third_party/android_deps/BUILD.gn +++ b/third_party/android_deps/BUILD.gn
@@ -1174,7 +1174,7 @@ # This is generated, do not edit. Update BuildConfigGenerator.groovy instead. android_aar_prebuilt("com_google_android_material_material_java") { aar_path = - "libs/com_google_android_material_material/material-1.6.0-alpha01.aar" + "libs/com_google_android_material_material/material-1.7.0-alpha02.aar" info_path = "libs/com_google_android_material_material/com_google_android_material_material.info" # Material Design is pulled in via Doubledown, thus this target should not
diff --git a/third_party/android_deps/build.gradle b/third_party/android_deps/build.gradle index 853a75e..4306596 100644 --- a/third_party/android_deps/build.gradle +++ b/third_party/android_deps/build.gradle
@@ -40,7 +40,7 @@ // Note about the configuration names: they are defined in buildSrc/ChromiumPlugin // Replacement for com.android.support:design - compile 'com.google.android.material:material:1.6.0-alpha01' + compile 'com.google.android.material:material:1.7.0-alpha02' compile 'com.google.android.play:core:1.10.0'
diff --git a/third_party/android_deps/libs/com_google_android_material_material/README.chromium b/third_party/android_deps/libs/com_google_android_material_material/README.chromium index 3bee109..82e7afc 100644 --- a/third_party/android_deps/libs/com_google_android_material_material/README.chromium +++ b/third_party/android_deps/libs/com_google_android_material_material/README.chromium
@@ -1,7 +1,7 @@ Name: Material Components for Android Short Name: material URL: https://github.com/material-components/material-components-android -Version: 1.6.0-alpha01 +Version: 1.7.0-alpha02 License: Android Software Development Kit License License File: LICENSE CPEPrefix: unknown
diff --git a/third_party/android_deps/libs/com_google_android_material_material/cipd.yaml b/third_party/android_deps/libs/com_google_android_material_material/cipd.yaml index 39c1086..22d58b0d 100644 --- a/third_party/android_deps/libs/com_google_android_material_material/cipd.yaml +++ b/third_party/android_deps/libs/com_google_android_material_material/cipd.yaml
@@ -3,8 +3,8 @@ # found in the LICENSE file. # To create CIPD package run the following command. -# cipd create --pkg-def cipd.yaml -tag version:2@1.6.0-alpha01.cr1 +# cipd create --pkg-def cipd.yaml -tag version:2@1.7.0-alpha02.cr1 package: chromium/third_party/android_deps/libs/com_google_android_material_material description: "Material Components for Android" data: -- file: material-1.6.0-alpha01.aar +- file: material-1.7.0-alpha02.aar
diff --git a/third_party/android_deps/libs/com_google_android_material_material/com_google_android_material_material.info b/third_party/android_deps/libs/com_google_android_material_material/com_google_android_material_material.info index 25e2fe6..8e6edd59 100644 --- a/third_party/android_deps/libs/com_google_android_material_material/com_google_android_material_material.info +++ b/third_party/android_deps/libs/com_google_android_material_material/com_google_android_material_material.info
@@ -47,7 +47,6 @@ "res/animator/mtrl_fab_transformation_sheet_collapse_spec.xml", "res/animator/mtrl_fab_transformation_sheet_expand_spec.xml", "res/animator-v21/design_appbar_state_list_animator.xml", - "res/color/checkbox_themeable_attribute_color.xml", "res/color/design_box_stroke_color.xml", "res/color/design_error.xml", "res/color/design_icon_tint.xml", @@ -77,6 +76,8 @@ "res/color/m3_default_color_primary_text.xml", "res/color/m3_default_color_secondary_text.xml", "res/color/m3_elevated_chip_background_color.xml", + "res/color/m3_filled_icon_button_container_color_selector.xml", + "res/color/m3_filled_icon_button_icon_color_selector.xml", "res/color/m3_highlighted_text.xml", "res/color/m3_hint_foreground.xml", "res/color/m3_navigation_bar_item_with_indicator_icon_tint.xml", @@ -84,12 +85,14 @@ "res/color/m3_navigation_bar_ripple_color_selector.xml", "res/color/m3_navigation_item_background_color.xml", "res/color/m3_navigation_item_icon_tint.xml", + "res/color/m3_navigation_item_ripple_color.xml", "res/color/m3_navigation_item_text_color.xml", "res/color/m3_popupmenu_overlay_color.xml", "res/color/m3_primary_text_disable_only.xml", "res/color/m3_radiobutton_ripple_tint.xml", "res/color/m3_selection_control_button_tint.xml", "res/color/m3_selection_control_ripple_color_selector.xml", + "res/color/m3_simple_item_ripple_color.xml", "res/color/m3_slider_active_track_color.xml", "res/color/m3_slider_halo_color.xml", "res/color/m3_slider_inactive_track_color.xml", @@ -177,15 +180,15 @@ "res/color/mtrl_outlined_icon_tint.xml", "res/color/mtrl_outlined_stroke_color.xml", "res/color/mtrl_popupmenu_overlay_color.xml", + "res/color/mtrl_switch_thumb_tint.xml", + "res/color/mtrl_switch_track_decoration_tint.xml", + "res/color/mtrl_switch_track_tint.xml", "res/color/mtrl_tabs_colored_ripple_color.xml", "res/color/mtrl_tabs_icon_color_selector.xml", "res/color/mtrl_tabs_icon_color_selector_colored.xml", "res/color/mtrl_tabs_legacy_text_color_selector.xml", "res/color/mtrl_tabs_ripple_color.xml", "res/color/mtrl_text_btn_text_color_selector.xml", - "res/color/radiobutton_themeable_attribute_color.xml", - "res/color/test_mtrl_calendar_day.xml", - "res/color/test_mtrl_calendar_day_selected.xml", "res/color-night-v8/material_timepicker_button_stroke.xml", "res/color-night-v8/material_timepicker_clockface.xml", "res/color-night-v8/material_timepicker_modebutton_tint.xml", @@ -235,9 +238,20 @@ "res/drawable/mtrl_navigation_bar_item_background.xml", "res/drawable/mtrl_popupmenu_background.xml", "res/drawable/mtrl_popupmenu_background_overlay.xml", + "res/drawable/mtrl_switch_thumb.xml", + "res/drawable/mtrl_switch_thumb_checked.xml", + "res/drawable/mtrl_switch_thumb_checked_pressed.xml", + "res/drawable/mtrl_switch_thumb_checked_unchecked.xml", + "res/drawable/mtrl_switch_thumb_pressed.xml", + "res/drawable/mtrl_switch_thumb_pressed_checked.xml", + "res/drawable/mtrl_switch_thumb_pressed_unchecked.xml", + "res/drawable/mtrl_switch_thumb_unchecked.xml", + "res/drawable/mtrl_switch_thumb_unchecked_checked.xml", + "res/drawable/mtrl_switch_thumb_unchecked_pressed.xml", + "res/drawable/mtrl_switch_track.xml", + "res/drawable/mtrl_switch_track_decoration.xml", "res/drawable/mtrl_tabs_default_indicator.xml", "res/drawable/navigation_empty_icon.xml", - "res/drawable/test_custom_background.xml", "res/drawable-v21/m3_tabs_background.xml", "res/drawable-v21/material_cursor_drawable.xml", "res/drawable-v21/mtrl_navigation_bar_item_background.xml", @@ -248,10 +262,24 @@ "res/drawable-v23/m3_tabs_background.xml", "res/drawable-v23/m3_tabs_transparent_background.xml", "res/drawable-v23/mtrl_popupmenu_background_overlay.xml", + "res/interpolator/m3_sys_motion_easing_emphasized.xml", + "res/interpolator/m3_sys_motion_easing_emphasized_accelerate.xml", + "res/interpolator/m3_sys_motion_easing_emphasized_decelerate.xml", + "res/interpolator/m3_sys_motion_easing_linear.xml", + "res/interpolator/m3_sys_motion_easing_standard.xml", + "res/interpolator/m3_sys_motion_easing_standard_accelerate.xml", + "res/interpolator/m3_sys_motion_easing_standard_decelerate.xml", "res/interpolator/mtrl_fast_out_linear_in.xml", "res/interpolator/mtrl_fast_out_slow_in.xml", "res/interpolator/mtrl_linear.xml", "res/interpolator/mtrl_linear_out_slow_in.xml", + "res/interpolator-v21/m3_sys_motion_easing_emphasized.xml", + "res/interpolator-v21/m3_sys_motion_easing_emphasized_accelerate.xml", + "res/interpolator-v21/m3_sys_motion_easing_emphasized_decelerate.xml", + "res/interpolator-v21/m3_sys_motion_easing_linear.xml", + "res/interpolator-v21/m3_sys_motion_easing_standard.xml", + "res/interpolator-v21/m3_sys_motion_easing_standard_accelerate.xml", + "res/interpolator-v21/m3_sys_motion_easing_standard_decelerate.xml", "res/interpolator-v21/mtrl_fast_out_linear_in.xml", "res/interpolator-v21/mtrl_fast_out_slow_in.xml", "res/interpolator-v21/mtrl_linear_out_slow_in.xml", @@ -273,6 +301,7 @@ "res/layout/m3_alert_dialog.xml", "res/layout/m3_alert_dialog_actions.xml", "res/layout/m3_alert_dialog_title.xml", + "res/layout/m3_auto_complete_simple_item.xml", "res/layout/material_radial_view_group.xml", "res/layout/mtrl_alert_dialog.xml", "res/layout/mtrl_alert_dialog_actions.xml", @@ -280,24 +309,10 @@ "res/layout/mtrl_alert_select_dialog_item.xml", "res/layout/mtrl_alert_select_dialog_multichoice.xml", "res/layout/mtrl_alert_select_dialog_singlechoice.xml", + "res/layout/mtrl_auto_complete_simple_item.xml", "res/layout/mtrl_layout_snackbar.xml", "res/layout/mtrl_layout_snackbar_include.xml", "res/layout/mtrl_navigation_rail_item.xml", - "res/layout/test_action_chip.xml", - "res/layout/test_chip_zero_corner_radius.xml", - "res/layout/test_design_checkbox.xml", - "res/layout/test_design_radiobutton.xml", - "res/layout/test_navigation_bar_item_layout.xml", - "res/layout/test_reflow_chipgroup.xml", - "res/layout/test_toolbar.xml", - "res/layout/test_toolbar_custom_background.xml", - "res/layout/test_toolbar_elevation.xml", - "res/layout/test_toolbar_surface.xml", - "res/layout/text_view_with_line_height_from_appearance.xml", - "res/layout/text_view_with_line_height_from_layout.xml", - "res/layout/text_view_with_line_height_from_style.xml", - "res/layout/text_view_with_theme_line_height.xml", - "res/layout/text_view_without_line_height.xml", "res/layout-sw600dp-v13/design_layout_snackbar.xml", "res/layout-sw600dp-v13/mtrl_layout_snackbar.xml", "res/values/values.xml", @@ -400,12 +415,7 @@ "res/values-zh-rCN/values-zh-rCN.xml", "res/values-zh-rHK/values-zh-rHK.xml", "res/values-zh-rTW/values-zh-rTW.xml", - "res/values-zu/values-zu.xml", - "res/xml/standalone_badge.xml", - "res/xml/standalone_badge_gravity_bottom_end.xml", - "res/xml/standalone_badge_gravity_bottom_start.xml", - "res/xml/standalone_badge_gravity_top_start.xml", - "res/xml/standalone_badge_offset.xml" + "res/values-zu/values-zu.xml" ] subjar_tuples = [] subjars = []
diff --git a/third_party/apache-portable-runtime/BUILD.gn b/third_party/apache-portable-runtime/BUILD.gn index d66a9b8..0918a5d 100644 --- a/third_party/apache-portable-runtime/BUILD.gn +++ b/third_party/apache-portable-runtime/BUILD.gn
@@ -4,6 +4,19 @@ import("//build/config/android/config.gni") +# In a separate config so that the -Wno flag shows up after -Wall. +config("apr_warnings") { + if (is_clang) { + cflags = [ + # TODO(https://crbug.com/1347085): Investigate, fix. + "-Wno-int-conversion", + + # TODO(https://crbug.com/1347226): Investigate, fix. + "-Wno-deprecated-declarations", + ] + } +} + # Builds 'Apache Portable Runtime'. See http://apr.apache.org static_library("apr") { sources = [ @@ -107,5 +120,11 @@ "src/include", "src/include/arch/unix", ] - cflags = [ "-w" ] + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + "//build/config/compiler:no_chromium_code", + + # Must be after no_chromium_code so -Wno flags show up after -Wall. + ":apr_warnings", + ] }
diff --git a/third_party/blink/common/frame/frame_visual_properties_mojom_traits.cc b/third_party/blink/common/frame/frame_visual_properties_mojom_traits.cc index ca61988..731e7e1 100644 --- a/third_party/blink/common/frame/frame_visual_properties_mojom_traits.cc +++ b/third_party/blink/common/frame/frame_visual_properties_mojom_traits.cc
@@ -19,7 +19,7 @@ !data.ReadMaxSizeForAutoResize(&out->max_size_for_auto_resize) || !data.ReadVisibleViewportSize(&out->visible_viewport_size) || !data.ReadCompositorViewport(&out->compositor_viewport) || - !data.ReadScreenSpaceRect(&out->screen_space_rect) || + !data.ReadRectInLocalRoot(&out->rect_in_local_root) || !data.ReadLocalFrameSize(&out->local_frame_size) || !data.ReadRootWidgetWindowSegments(&out->root_widget_window_segments) || !data.ReadLocalSurfaceId(&out->local_surface_id) ||
diff --git a/third_party/blink/perf_tests/paint/wavy-decorations-long.html b/third_party/blink/perf_tests/paint/wavy-decorations-long.html deleted file mode 100644 index 09432c6..0000000 --- a/third_party/blink/perf_tests/paint/wavy-decorations-long.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Wavy decoration painting: one long decoration</title> -<script src="../resources/runner.js"></script> -<script src="resources/paint.js"></script> -<style> -* { - text-decoration-skip: none; - text-decoration-skip-ink: none; -} -main { - text-decoration: red wavy underline; -} -main.blue { - text-decoration: blue wavy underline; -} -</style> -<main>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </main> -<script> - const main = document.querySelector("main"); - main.innerHTML = main.innerHTML.repeat(420); - - measurePaint({ - description: "Measure frame time for painting wavy decorations with one long decoration", - run: () => void document.querySelector("main").classList.toggle("blue"), - }); -</script>
diff --git a/third_party/blink/perf_tests/paint/wavy-decorations-many.html b/third_party/blink/perf_tests/paint/wavy-decorations-many.html deleted file mode 100644 index 921242c..0000000 --- a/third_party/blink/perf_tests/paint/wavy-decorations-many.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Wavy decoration painting: many short decorations</title> -<script src="../resources/runner.js"></script> -<script src="resources/paint.js"></script> -<style> -* { - text-decoration-skip: none; - text-decoration-skip-ink: none; -} -main > span { - text-decoration: red wavy underline; -} -main.blue > span { - text-decoration: blue wavy underline; -} -</style> -<main><span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet,</span> <span>consectetur</span> <span>adipiscing</span> <span>elit,</span> <span>sed</span> <span>do</span> <span>eiusmod</span> <span>tempor</span> <span>incididunt</span> <span>ut</span> <span>labore</span> <span>et</span> <span>dolore</span> <span>magna</span> <span>aliqua.</span> </main> -<script> - const main = document.querySelector("main"); - main.innerHTML = main.innerHTML.repeat(420); - - measurePaint({ - description: "Measure frame time for painting wavy decorations with many short decorations", - run: () => void document.querySelector("main").classList.toggle("blue"), - }); -</script>
diff --git a/third_party/blink/public/common/frame/frame_visual_properties.h b/third_party/blink/public/common/frame/frame_visual_properties.h index fd670818..049f444 100644 --- a/third_party/blink/public/common/frame/frame_visual_properties.h +++ b/third_party/blink/public/common/frame/frame_visual_properties.h
@@ -42,8 +42,8 @@ // The size of the compositor viewport, to match the sub-frame's surface. gfx::Rect compositor_viewport; - // The screen's coordinate space. - gfx::Rect screen_space_rect; + // The frame's rect relative to the first ancestor local root frame. + gfx::Rect rect_in_local_root; // The size of the frame in its parent's coordinate space. gfx::Size local_frame_size;
diff --git a/third_party/blink/public/common/frame/frame_visual_properties_mojom_traits.h b/third_party/blink/public/common/frame/frame_visual_properties_mojom_traits.h index 819ea52..c4dfe183 100644 --- a/third_party/blink/public/common/frame/frame_visual_properties_mojom_traits.h +++ b/third_party/blink/public/common/frame/frame_visual_properties_mojom_traits.h
@@ -75,9 +75,9 @@ return r.compositor_viewport; } - static const gfx::Rect& screen_space_rect( + static const gfx::Rect& rect_in_local_root( const blink::FrameVisualProperties& r) { - return r.screen_space_rect; + return r.rect_in_local_root; } static const gfx::Size& local_frame_size(
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index 81e3ce7..f5207237 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -705,7 +705,9 @@ AttributionUntrustworthyOrigin UntrustworthyReportingOrigin InsecureContext + # TODO(apaseltiner): Rename this to InvalidRegisterSourceHeader InvalidHeader + InvalidRegisterTriggerHeader # Details for issues around "Attribution Reporting API" usage. # Explainer: https://github.com/WICG/attribution-reporting-api
diff --git a/third_party/blink/public/mojom/frame/frame_visual_properties.mojom b/third_party/blink/public/mojom/frame/frame_visual_properties.mojom index b8b0d8a..8dff365 100644 --- a/third_party/blink/public/mojom/frame/frame_visual_properties.mojom +++ b/third_party/blink/public/mojom/frame/frame_visual_properties.mojom
@@ -70,7 +70,8 @@ // for what, and how they should relate or not. gfx.mojom.Rect compositor_viewport; - gfx.mojom.Rect screen_space_rect; + // The frame's rect relative to the nearest ancestor local root frame. + gfx.mojom.Rect rect_in_local_root; gfx.mojom.Size local_frame_size;
diff --git a/third_party/blink/public/mojom/page/widget.mojom b/third_party/blink/public/mojom/page/widget.mojom index 64fc609..be0f6e9 100644 --- a/third_party/blink/public/mojom/page/widget.mojom +++ b/third_party/blink/public/mojom/page/widget.mojom
@@ -206,7 +206,7 @@ // Request that this popup be dismissed. RequestClosePopup(); - // Request the popup be shown. + // Request the popup be shown. Rects are relative to screen origin in DIPs. ShowPopup(gfx.mojom.Rect initial_rect, gfx.mojom.Rect anchor_rect) => (); // Request that the browser change the bounds of the widget.
diff --git a/third_party/blink/public/web/web_local_frame_client.h b/third_party/blink/public/web/web_local_frame_client.h index a31447c..acb427e 100644 --- a/third_party/blink/public/web/web_local_frame_client.h +++ b/third_party/blink/public/web/web_local_frame_client.h
@@ -669,10 +669,6 @@ ax::mojom::EventFrom event_from, ax::mojom::Action event_from_action) {} - // Adds automatic label annotations for |obj| and stores them - // in |dst|. This method assumes the object is an image. - virtual void AddImageAnnotations(WebAXObject& obj, ui::AXNodeData* dst) {} - // Audio Output Devices API -------------------------------------------- // Checks that the given audio sink exists and is authorized. The result is
diff --git a/third_party/blink/renderer/core/css/transition.css b/third_party/blink/renderer/core/css/transition.css index 7c1fde2..1d51045e 100644 --- a/third_party/blink/renderer/core/css/transition.css +++ b/third_party/blink/renderer/core/css/transition.css
@@ -12,6 +12,7 @@ html::page-transition { position: fixed; inset: 0; + pointer-events: none; } html::page-transition-container(*) { @@ -23,6 +24,8 @@ /* The transform applied to the container includes any translation necessary for the original element's transform-origin. */ transform-origin: top left; + + pointer-events: auto; } ::page-transition-image-wrapper(*) {
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc index f9e77d6c..74464a1 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc +++ b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
@@ -832,18 +832,6 @@ return elements_to_reveal.size(); } -static bool CheckSelfIfInclusive(const Node* node, bool inclusive_check) { - if (inclusive_check) { - if (auto* element = DynamicTo<Element>(node)) { - if (auto* context = element->GetDisplayLockContext()) { - if (!context->ShouldPaintChildren()) - return true; - } - } - } - return false; -} - bool DisplayLockUtilities::IsDisplayLockedPreventingPaint( const Node* node, bool inclusive_check) { @@ -851,10 +839,8 @@ // result. Otherwise, fallback to get-element versions. if (memoizer_) { auto result = memoizer_->IsNodeLocked(node); - if (result) { - // The memoizer can only be used for non-inclusive checks. - return *result || CheckSelfIfInclusive(node, inclusive_check); - } + if (result) + return *result; } else { return inclusive_check ? DisplayLockUtilities::LockedInclusiveAncestorPreventingPaint( @@ -862,7 +848,7 @@ : DisplayLockUtilities::LockedAncestorPreventingPaint(*node); } - // Do some sanity checks that we can early out on. + // Do some sanity checks that we cwan early out on. if (!node->isConnected() || node->GetDocument() .GetDisplayLockDocumentState() @@ -874,8 +860,14 @@ // Handle the inclusive check -- that is, check the node itself. Note that // it's important not to memoize that since the memoization consists of // ancestor checks only. - if (CheckSelfIfInclusive(node, inclusive_check)) - return true; + if (inclusive_check) { + if (auto* element = DynamicTo<Element>(node)) { + if (auto* context = element->GetDisplayLockContext()) { + if (!context->ShouldPaintChildren()) + return true; + } + } + } // Walk up the ancestor chain, and consult with both the memoizer and check // directly if we're skipping paint. When we find a result (or finish the
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc index 040ccc2f..5bcb20d7 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_style_tracker.cc
@@ -39,8 +39,9 @@ const char* kElementSetModificationError = "The element set cannot be modified at this transition state."; -const char* kPaintContainmentNotSatisfied = - "Dropping element from transition. Shared element must contain paint"; +const char* kContainmentNotSatisfied = + "Dropping element from transition. Shared element must contain paint or " + "layout"; const char* kDuplicateTagBaseError = "Unexpected duplicate page transition tag: "; @@ -667,7 +668,8 @@ // TODO(khushalsagar) : Switch paint containment and disallow fragmentation // to implicit constraints. See crbug.com/1277121. auto* layout_object = element_data->target_element->GetLayoutObject(); - if (!layout_object || !layout_object->ShouldApplyPaintContainment()) { + if (!layout_object || (!layout_object->ShouldApplyPaintContainment() && + !layout_object->ShouldApplyLayoutContainment())) { element_data->target_element = nullptr; // If we had a valid |target_element| there must be an associated snapshot @@ -832,10 +834,12 @@ // TODO(vmpstr): Should this work for replaced elements as well? if (object) { - if (object->ShouldApplyPaintContainment()) + if (object->ShouldApplyPaintContainment() || + object->ShouldApplyLayoutContainment()) { continue; + } - AddConsoleError(kPaintContainmentNotSatisfied, + AddConsoleError(kContainmentNotSatisfied, {DOMNodeIds::IdForNode(active_element)}); } @@ -844,6 +848,7 @@ // support nulls as a valid active element. // Invalidate the element since we should no longer be compositing it. + // TODO(vmpstr): Should we abort the transition instead?0 auto* box = active_element->GetLayoutBox(); if (box && box->HasSelfPaintingLayer()) box->SetNeedsPaintPropertyUpdate();
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 3261df4..89f67f2 100644 --- a/third_party/blink/renderer/core/frame/attribution_response_parsing.cc +++ b/third_party/blink/renderer/core/frame/attribution_response_parsing.cc
@@ -19,8 +19,6 @@ #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" -#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" -#include "third_party/blink/renderer/platform/network/http_names.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -512,23 +510,4 @@ return true; } -mojom::blink::AttributionTriggerDataPtr ParseAttributionTriggerData( - const ResourceResponse& response) { - auto trigger_data = mojom::blink::AttributionTriggerData::New(); - - // Verify the current url is trustworthy and capable of registering triggers. - scoped_refptr<const SecurityOrigin> reporting_origin = - SecurityOrigin::Create(response.CurrentRequestUrl()); - if (!reporting_origin->IsPotentiallyTrustworthy()) - return nullptr; - trigger_data->reporting_origin = std::move(reporting_origin); - - const AtomicString& trigger_json = response.HttpHeaderField( - http_names::kAttributionReportingRegisterTrigger); - if (!ParseTriggerRegistrationHeader(trigger_json, *trigger_data)) - return nullptr; - - return trigger_data; -} - } // namespace blink::attribution_response_parsing
diff --git a/third_party/blink/renderer/core/frame/attribution_response_parsing.h b/third_party/blink/renderer/core/frame/attribution_response_parsing.h index 7a39c08..5c06057 100644 --- a/third_party/blink/renderer/core/frame/attribution_response_parsing.h +++ b/third_party/blink/renderer/core/frame/attribution_response_parsing.h
@@ -20,7 +20,6 @@ namespace blink { class JSONValue; -class ResourceResponse; namespace attribution_response_parsing { @@ -108,11 +107,6 @@ const JSONValue* json, WTF::HashMap<String, uint32_t>& values); -// Returns the attribution trigger data parsed from the response. Returns -// `nullptr` in case of error. -mojom::blink::AttributionTriggerDataPtr ParseAttributionTriggerData( - const ResourceResponse& response); - } // namespace attribution_response_parsing } // namespace blink
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 74581ff..8f821228 100644 --- a/third_party/blink/renderer/core/frame/attribution_src_loader.cc +++ b/third_party/blink/renderer/core/frame/attribution_src_loader.cc
@@ -175,7 +175,8 @@ private: void HandleSourceRegistration(const ResourceResponse& response, uint64_t request_id); - void HandleTriggerRegistration(const ResourceResponse& response); + void HandleTriggerRegistration(const ResourceResponse& response, + uint64_t request_id); // RawResourceClient: String DebugName() const override; @@ -509,7 +510,7 @@ if (can_process_trigger && headers.Contains(http_names::kAttributionReportingRegisterTrigger)) { type_ = SrcType::kTrigger; - HandleTriggerRegistration(response); + HandleTriggerRegistration(response, request_id); } } @@ -524,6 +525,7 @@ // Verify the current url is trustworthy and capable of registering sources. scoped_refptr<const SecurityOrigin> reporting_origin = SecurityOrigin::Create(response.CurrentRequestUrl()); + // TODO(apaseltiner): Report DevTools issue if this fails. if (!reporting_origin->IsPotentiallyTrustworthy()) return; source_data->reporting_origin = std::move(reporting_origin); @@ -534,7 +536,7 @@ if (!attribution_response_parsing::ParseSourceRegistrationHeader( source_json, *source_data)) { LogAuditIssue(loader_->local_frame_->DomWindow(), - AttributionReportingIssueType::kInvalidHeader, + AttributionReportingIssueType::kInvalidRegisterSourceHeader, /*element=*/nullptr, request_id, /*invalid_parameter=*/source_json); return; @@ -544,15 +546,30 @@ } void AttributionSrcLoader::ResourceClient::HandleTriggerRegistration( - const ResourceResponse& response) { + const ResourceResponse& response, + uint64_t request_id) { DCHECK_EQ(type_, SrcType::kTrigger); - // TODO(apaseltiner): Report DevTools issue(s) if this fails. - mojom::blink::AttributionTriggerDataPtr trigger_data = - attribution_response_parsing::ParseAttributionTriggerData(response); + auto trigger_data = mojom::blink::AttributionTriggerData::New(); - if (!trigger_data) + // Verify the current url is trustworthy and capable of registering triggers. + scoped_refptr<const SecurityOrigin> reporting_origin = + SecurityOrigin::Create(response.CurrentRequestUrl()); + // TODO(apaseltiner): Report DevTools issue if this fails. + if (!reporting_origin->IsPotentiallyTrustworthy()) return; + trigger_data->reporting_origin = std::move(reporting_origin); + + const AtomicString& trigger_json = response.HttpHeaderField( + http_names::kAttributionReportingRegisterTrigger); + if (!attribution_response_parsing::ParseTriggerRegistrationHeader( + trigger_json, *trigger_data)) { + LogAuditIssue(loader_->local_frame_->DomWindow(), + AttributionReportingIssueType::kInvalidRegisterTriggerHeader, + /*element=*/nullptr, request_id, + /*invalid_parameter=*/trigger_json); + return; + } data_host_->TriggerDataAvailable(std::move(trigger_data)); }
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index d22a8596..6e074c3 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -2865,6 +2865,10 @@ DCHECK(GetFrame().IsLocalRoot()); + absl::optional<MobileFriendlinessChecker::PaintScope> mf_scope; + if (mobile_friendliness_checker_) + mf_scope.emplace(*mobile_friendliness_checker_); + auto* layout_view = GetLayoutView(); DCHECK(layout_view);
diff --git a/third_party/blink/renderer/core/frame/remote_frame.cc b/third_party/blink/renderer/core/frame/remote_frame.cc index ec69891..eff70d1 100644 --- a/third_party/blink/renderer/core/frame/remote_frame.cc +++ b/third_party/blink/renderer/core/frame/remote_frame.cc
@@ -514,8 +514,8 @@ } void RemoteFrame::FrameRectsChanged(const gfx::Size& local_frame_size, - const gfx::Rect& screen_space_rect) { - pending_visual_properties_.screen_space_rect = screen_space_rect; + const gfx::Rect& rect_in_local_root) { + pending_visual_properties_.rect_in_local_root = rect_in_local_root; pending_visual_properties_.local_frame_size = local_frame_size; SynchronizeVisualProperties(); } @@ -937,8 +937,8 @@ pending_visual_properties_.max_size_for_auto_resize || sent_visual_properties_->local_frame_size != pending_visual_properties_.local_frame_size || - sent_visual_properties_->screen_space_rect.size() != - pending_visual_properties_.screen_space_rect.size() || + sent_visual_properties_->rect_in_local_root.size() != + pending_visual_properties_.rect_in_local_root.size() || sent_visual_properties_->screen_infos != pending_visual_properties_.screen_infos || sent_visual_properties_->zoom_level != @@ -972,8 +972,8 @@ capture_sequence_number_changed); bool rect_changed = !sent_visual_properties_ || - sent_visual_properties_->screen_space_rect != - pending_visual_properties_.screen_space_rect; + sent_visual_properties_->rect_in_local_root != + pending_visual_properties_.rect_in_local_root; bool visual_properties_changed = synchronized_props_changed || rect_changed; if (visual_properties_changed && propagate) {
diff --git a/third_party/blink/renderer/core/frame/remote_frame_view.cc b/third_party/blink/renderer/core/frame/remote_frame_view.cc index 3fe8a41..a3e89445 100644 --- a/third_party/blink/renderer/core/frame/remote_frame_view.cc +++ b/third_party/blink/renderer/core/frame/remote_frame_view.cc
@@ -280,10 +280,10 @@ // any remote frames, if any, is accounted for by the embedder. needs_frame_rect_propagation_ = false; gfx::Rect frame_rect(FrameRect()); - gfx::Rect screen_space_rect = frame_rect; + gfx::Rect rect_in_local_root = frame_rect; if (LocalFrameView* parent = ParentFrameView()) { - screen_space_rect = parent->ConvertToRootFrame(screen_space_rect); + rect_in_local_root = parent->ConvertToRootFrame(rect_in_local_root); } gfx::Size frame_size = frame_rect.size(); @@ -293,7 +293,7 @@ gfx::Size(frozen_size->width.Ceil(), frozen_size->height.Ceil()); } } - remote_frame_->FrameRectsChanged(frame_size, screen_space_rect); + remote_frame_->FrameRectsChanged(frame_size, rect_in_local_root); } void RemoteFrameView::Paint(GraphicsContext& context,
diff --git a/third_party/blink/renderer/core/frame/visual_viewport.cc b/third_party/blink/renderer/core/frame/visual_viewport.cc index b33fc5b..34ed2aa 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport.cc
@@ -817,6 +817,10 @@ } ScrollOffset VisualViewport::MaximumScrollOffset() const { + return MaximumScrollOffsetAtScale(scale_); +} + +ScrollOffset VisualViewport::MaximumScrollOffsetAtScale(float scale) const { if (!IsActiveViewport()) return ScrollOffset(); @@ -830,14 +834,14 @@ frame_view_size.Enlarge(0, browser_controls_adjustment_ / min_scale); } - frame_view_size.Scale(scale_); + frame_view_size.Scale(scale); frame_view_size = gfx::SizeF(ToFlooredSize(frame_view_size)); gfx::SizeF viewport_size(size_); viewport_size.Enlarge(0, ceilf(browser_controls_adjustment_)); gfx::SizeF max_position = frame_view_size - viewport_size; - max_position.Scale(1 / scale_); + max_position.Scale(1 / scale); return ScrollOffset(max_position.width(), max_position.height()); }
diff --git a/third_party/blink/renderer/core/frame/visual_viewport.h b/third_party/blink/renderer/core/frame/visual_viewport.h index c3c2a09..49ef3647 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport.h +++ b/third_party/blink/renderer/core/frame/visual_viewport.h
@@ -212,6 +212,7 @@ gfx::Vector2d MinimumScrollOffsetInt() const override; gfx::Vector2d MaximumScrollOffsetInt() const override; ScrollOffset MaximumScrollOffset() const override; + ScrollOffset MaximumScrollOffsetAtScale(float scale) const; // Note: Because scrollbars are conceptually owned by the LayoutView, // ContentsSize includes the main frame's scrollbars. This is necessary for // correct cc Layer sizing.
diff --git a/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/third_party/blink/renderer/core/frame/visual_viewport_test.cc index 5f7a6369f..dc9db2aa 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport_test.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -1836,6 +1836,28 @@ scrollable_area->MaximumScrollOffset()); } +// Tests that the scroll offset is consistent when scale specified. +TEST_P(VisualViewportTest, MaxScrollOffsetAtScale) { + InitializeWithDesktopSettings(); + WebView()->MainFrameViewWidget()->Resize(gfx::Size(101, 201)); + NavigateTo("about:blank"); + + VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport(); + + WebView()->SetPageScaleFactor(0.1); + EXPECT_EQ(ScrollOffset(), visual_viewport.MaximumScrollOffsetAtScale(1.0)); + + WebView()->SetPageScaleFactor(2); + EXPECT_EQ(ScrollOffset(), visual_viewport.MaximumScrollOffsetAtScale(1.0)); + + WebView()->SetPageScaleFactor(5); + EXPECT_EQ(ScrollOffset(), visual_viewport.MaximumScrollOffsetAtScale(1.0)); + + WebView()->SetPageScaleFactor(10); + EXPECT_EQ(ScrollOffset(101. / 2., 201. / 2.), + visual_viewport.MaximumScrollOffsetAtScale(2.0)); +} + // Tests that the slow scrolling after an impl scroll on the visual viewport is // continuous. crbug.com/453460 was caused by the impl-path not updating the // ScrollAnimatorBase class.
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 542c95bc..216a32c 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
@@ -2847,14 +2847,14 @@ } void WebFrameWidgetImpl::PresentationCallbackForMeaningfulLayout( - base::TimeTicks) { + base::TimeTicks first_paint_time) { // |local_root_| may be null if the widget has shut down between when this // callback was requested and when it was resolved by the compositor. if (local_root_) local_root_->ViewImpl()->DidFirstVisuallyNonEmptyPaint(); if (widget_base_) - widget_base_->DidFirstVisuallyNonEmptyPaint(); + widget_base_->DidFirstVisuallyNonEmptyPaint(first_paint_time); } void WebFrameWidgetImpl::RequestAnimationAfterDelay(
diff --git a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc index 727770a..1c8886e 100644 --- a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc +++ b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
@@ -65,43 +65,41 @@ return scanner.ScanRun(value_run, V8AlignSetting(align).AsString()); } -} // namespace - -static const CSSValueID kDisplayWritingModeMap[] = {CSSValueID::kHorizontalTb, - CSSValueID::kVerticalRl, - CSSValueID::kVerticalLr}; +const CSSValueID kDisplayWritingModeMap[] = {CSSValueID::kHorizontalTb, + CSSValueID::kVerticalRl, + CSSValueID::kVerticalLr}; static_assert(std::size(kDisplayWritingModeMap) == - VTTCue::kNumberOfWritingDirections, + static_cast<size_t>(VTTCue::WritingDirection::kMaxValue) + 1, "displayWritingModeMap should have the same number of elements " "as VTTCue::NumberOfWritingDirections"); -static const CSSValueID kDisplayAlignmentMap[] = { +const CSSValueID kDisplayAlignmentMap[] = { CSSValueID::kStart, CSSValueID::kCenter, CSSValueID::kEnd, CSSValueID::kLeft, CSSValueID::kRight}; static_assert(std::size(kDisplayAlignmentMap) == V8AlignSetting::kEnumSize, "displayAlignmentMap should have the same number of elements as " "VTTCue::NumberOfAlignments"); -static const String& HorizontalKeyword() { +const String& HorizontalKeyword() { return g_empty_string; } -static const String& VerticalGrowingLeftKeyword() { +const String& VerticalGrowingLeftKeyword() { DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl")); return verticalrl; } -static const String& VerticalGrowingRightKeyword() { +const String& VerticalGrowingRightKeyword() { DEFINE_STATIC_LOCAL(const String, verticallr, ("lr")); return verticallr; } -static bool IsInvalidPercentage(double value) { +bool IsInvalidPercentage(double value) { DCHECK(std::isfinite(value)); return value < 0 || value > 100; } -static bool IsInvalidPercentage(double value, ExceptionState& exception_state) { +bool IsInvalidPercentage(double value, ExceptionState& exception_state) { if (IsInvalidPercentage(value)) { exception_state.ThrowDOMException( DOMExceptionCode::kIndexSizeError, @@ -113,6 +111,8 @@ return false; } +} // namespace + VTTCueBackgroundBox::VTTCueBackgroundBox(Document& document) : HTMLDivElement(document) { SetShadowPseudoId(TextTrackCue::CueShadowPseudoId()); @@ -143,7 +143,7 @@ line_position_(std::numeric_limits<double>::quiet_NaN()), text_position_(std::numeric_limits<double>::quiet_NaN()), cue_size_(100), - writing_direction_(kHorizontal), + writing_direction_(WritingDirection::kHorizontal), vtt_node_tree_(nullptr), cue_background_box_(MakeGarbageCollected<VTTCueBackgroundBox>(document)), snap_to_lines_(true), @@ -168,11 +168,11 @@ const String& VTTCue::vertical() const { switch (writing_direction_) { - case kHorizontal: + case WritingDirection::kHorizontal: return HorizontalKeyword(); - case kVerticalGrowingLeft: + case WritingDirection::kVerticalGrowingLeft: return VerticalGrowingLeftKeyword(); - case kVerticalGrowingRight: + case WritingDirection::kVerticalGrowingRight: return VerticalGrowingRightKeyword(); default: NOTREACHED(); @@ -183,11 +183,11 @@ void VTTCue::setVertical(const String& value) { WritingDirection direction = writing_direction_; if (value == HorizontalKeyword()) - direction = kHorizontal; + direction = WritingDirection::kHorizontal; else if (value == VerticalGrowingLeftKeyword()) - direction = kVerticalGrowingLeft; + direction = WritingDirection::kVerticalGrowingLeft; else if (value == VerticalGrowingRightKeyword()) - direction = kVerticalGrowingRight; + direction = WritingDirection::kVerticalGrowingRight; else NOTREACHED(); @@ -534,7 +534,8 @@ // 'tb'. Otherwise, if the cue writing direction is vertical growing left, // then let block-flow be 'lr'. Otherwise, the cue writing direction is // vertical growing right; let block-flow be 'rl'. - display_parameters.writing_mode = kDisplayWritingModeMap[writing_direction_]; + display_parameters.writing_mode = + kDisplayWritingModeMap[static_cast<size_t>(writing_direction_)]; // Resolve the cue alignment to one of the values {start, end, center}. AlignSetting computed_cue_alignment = CalculateComputedCueAlignment(); @@ -568,7 +569,7 @@ // 7. Determine the value of x-position or y-position for cue as per the // appropriate rules from the following list: - if (writing_direction_ == kHorizontal) { + if (writing_direction_ == WritingDirection::kHorizontal) { switch (computed_cue_alignment) { case AlignSetting::kStart: display_parameters.position.set_x(computed_text_position); @@ -611,12 +612,12 @@ // yet calculated for cue as per the appropriate rules from the following // list: if (!snap_to_lines_) { - if (writing_direction_ == kHorizontal) + if (writing_direction_ == WritingDirection::kHorizontal) display_parameters.position.set_y(computed_line_position); else display_parameters.position.set_x(computed_line_position); } else { - if (writing_direction_ == kHorizontal) + if (writing_direction_ == WritingDirection::kHorizontal) display_parameters.position.set_y(0); else display_parameters.position.set_x(0); @@ -750,7 +751,7 @@ UseCounter::Count(GetDocument(), WebFeature::kVTTCueRender); - if (writing_direction_ != kHorizontal) + if (writing_direction_ != WritingDirection::kHorizontal) UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderVertical); if (!snap_to_lines_) @@ -787,24 +788,25 @@ } VTTCue::CueSetting VTTCue::SettingName(VTTScanner& input) const { - CueSetting parsed_setting = kNone; - if (input.Scan("vertical")) - parsed_setting = kVertical; - else if (input.Scan("line")) - parsed_setting = kLine; - else if (input.Scan("position")) - parsed_setting = kPosition; - else if (input.Scan("size")) - parsed_setting = kSize; - else if (input.Scan("align")) - parsed_setting = kAlign; - else if (RuntimeEnabledFeatures::WebVTTRegionsEnabled() && - input.Scan("region")) - parsed_setting = kRegionId; + CueSetting parsed_setting = CueSetting::kNone; + if (input.Scan("vertical")) { + parsed_setting = CueSetting::kVertical; + } else if (input.Scan("line")) { + parsed_setting = CueSetting::kLine; + } else if (input.Scan("position")) { + parsed_setting = CueSetting::kPosition; + } else if (input.Scan("size")) { + parsed_setting = CueSetting::kSize; + } else if (input.Scan("align")) { + parsed_setting = CueSetting::kAlign; + } else if (RuntimeEnabledFeatures::WebVTTRegionsEnabled() && + input.Scan("region")) { + parsed_setting = CueSetting::kRegionId; + } // Verify that a ':' follows. - if (parsed_setting != kNone && input.Scan(':')) + if (parsed_setting != CueSetting::kNone && input.Scan(':')) return parsed_setting; - return kNone; + return CueSetting::kNone; } static bool ScanPercentage(VTTScanner& input, double& number) { @@ -864,22 +866,22 @@ // 4. Run the appropriate substeps that apply for the value of name, as // follows: switch (name) { - case kVertical: { + case CueSetting::kVertical: { // If name is a case-sensitive match for "vertical" // 1. If value is a case-sensitive match for the string "rl", then // let cue's WebVTT cue writing direction be vertical // growing left. if (input.ScanRun(value_run, VerticalGrowingLeftKeyword())) - writing_direction_ = kVerticalGrowingLeft; + writing_direction_ = WritingDirection::kVerticalGrowingLeft; // 2. Otherwise, if value is a case-sensitive match for the string // "lr", then let cue's WebVTT cue writing direction be // vertical growing right. else if (input.ScanRun(value_run, VerticalGrowingRightKeyword())) - writing_direction_ = kVerticalGrowingRight; + writing_direction_ = WritingDirection::kVerticalGrowingRight; break; } - case kLine: { + case CueSetting::kLine: { // If name is a case-sensitive match for "line" // Steps 1 - 2 skipped. double number; @@ -935,7 +937,7 @@ // Steps 7 - 9 skipped. break; } - case kPosition: { + case CueSetting::kPosition: { // If name is a case-sensitive match for "position". double number; // Steps 1 - 2 skipped. @@ -952,7 +954,7 @@ // Steps 5 - 7 skipped. break; } - case kSize: { + case CueSetting::kSize: { // If name is a case-sensitive match for "size" double number; // 1. If parse a percentage string from value doesn't fail, let @@ -966,7 +968,7 @@ cue_size_ = number; break; } - case kAlign: { + case CueSetting::kAlign: { // If name is a case-sensitive match for "align" // 1. If value is a case-sensitive match for the string "start", // then let cue's WebVTT cue text alignment be start alignment. @@ -994,13 +996,13 @@ cue_alignment_ = AlignSetting::kRight; break; } - case kRegionId: + case CueSetting::kRegionId: if (region_map) { auto it = region_map->find(input.ExtractString(value_run)); region_ = it != region_map->end() ? it->value : nullptr; } break; - case kNone: + case CueSetting::kNone: break; }
diff --git a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h index 218c59b0..764f97a 100644 --- a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h +++ b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h
@@ -145,11 +145,11 @@ double CalculateComputedLinePosition() const; - enum WritingDirection { + enum class WritingDirection { kHorizontal = 0, kVerticalGrowingLeft, kVerticalGrowingRight, - kNumberOfWritingDirections + kMaxValue = kVerticalGrowingRight }; WritingDirection GetWritingDirection() const { return writing_direction_; } @@ -179,7 +179,7 @@ double CalculateComputedTextPosition() const; AlignSetting CalculateComputedCueAlignment() const; - enum CueSetting { + enum class CueSetting { kNone, kVertical, kLine,
diff --git a/third_party/blink/renderer/core/inspector/inspector_audits_issue.cc b/third_party/blink/renderer/core/inspector/inspector_audits_issue.cc index e964fff52..e7f801ef 100644 --- a/third_party/blink/renderer/core/inspector/inspector_audits_issue.cc +++ b/third_party/blink/renderer/core/inspector/inspector_audits_issue.cc
@@ -149,8 +149,11 @@ case AttributionReportingIssueType::kInsecureContext: return protocol::Audits::AttributionReportingIssueTypeEnum:: InsecureContext; - case AttributionReportingIssueType::kInvalidHeader: + case AttributionReportingIssueType::kInvalidRegisterSourceHeader: return protocol::Audits::AttributionReportingIssueTypeEnum::InvalidHeader; + case AttributionReportingIssueType::kInvalidRegisterTriggerHeader: + return protocol::Audits::AttributionReportingIssueTypeEnum:: + InvalidRegisterTriggerHeader; } }
diff --git a/third_party/blink/renderer/core/inspector/inspector_audits_issue.h b/third_party/blink/renderer/core/inspector/inspector_audits_issue.h index c15aa3e..ad2c671 100644 --- a/third_party/blink/renderer/core/inspector/inspector_audits_issue.h +++ b/third_party/blink/renderer/core/inspector/inspector_audits_issue.h
@@ -106,7 +106,8 @@ kPermissionPolicyDisabled, kUntrustworthyReportingOrigin, kInsecureContext, - kInvalidHeader, + kInvalidRegisterSourceHeader, + kInvalidRegisterTriggerHeader, }; enum class SharedArrayBufferIssueType {
diff --git a/third_party/blink/renderer/core/layout/layout_text.cc b/third_party/blink/renderer/core/layout/layout_text.cc index 5c33864..dafcef15 100644 --- a/third_party/blink/renderer/core/layout/layout_text.cc +++ b/third_party/blink/renderer/core/layout/layout_text.cc
@@ -1856,57 +1856,6 @@ } } -LayoutUnit LayoutText::PhysicalAreaSize() const { - NOT_DESTROYED(); - // This is not accurate when |this| starts or ends at the middle of a line, - // but we prefer performance over accuracy. - if (IsInLayoutNGInlineFormattingContext()) { - NGInlineCursor cursor; - cursor.MoveTo(*this); - if (!cursor) - return LayoutUnit(0); - PhysicalRect rect = cursor.Current().RectInContainerFragment(); - cursor.MoveToLastForSameLayoutObject(); - rect.Unite(cursor.Current().RectInContainerFragment()); - return rect.Width() * rect.Height(); - } - - if (const auto* first_text_box = FirstTextBox()) { - if (const auto* last_text_box = LastTextBox()) { - LayoutUnit width = - std::max(first_text_box->LogicalRight(), - last_text_box->LogicalRight()) - - std::min(first_text_box->LogicalLeft(), last_text_box->LogicalLeft()); - LayoutUnit height = - last_text_box->LogicalBottom() - first_text_box->LogicalTop(); - return width * height; - } - } - return LayoutUnit(0); -} - -LayoutUnit LayoutText::PhysicalRightOffset() const { - NOT_DESTROYED(); - // This is not accurate when |this| starts or ends at the middle of a line, - // but we prefer performance over accuracy. - if (IsInLayoutNGInlineFormattingContext()) { - NGInlineCursor cursor; - cursor.MoveTo(*this); - if (!cursor) - return LayoutUnit(0); - PhysicalRect rect = cursor.Current().RectInContainerFragment(); - return rect.offset.left + rect.size.width; - } - - if (const auto* first_text_box = FirstTextBox()) { - if (const auto* last_text_box = LastTextBox()) { - return std::max(first_text_box->FrameRect().MaxX(), - last_text_box->FrameRect().MaxX()); - } - } - return LayoutUnit(0); -} - bool LayoutText::CanOptimizeSetText() const { NOT_DESTROYED(); // If we have only one line of text and "contain: layout size" we can avoid
diff --git a/third_party/blink/renderer/core/layout/layout_text.h b/third_party/blink/renderer/core/layout/layout_text.h index e345f6941..33c0afe2 100644 --- a/third_party/blink/renderer/core/layout/layout_text.h +++ b/third_party/blink/renderer/core/layout/layout_text.h
@@ -420,12 +420,6 @@ void LogicalStartingPointAndHeight(LogicalOffset& logical_starting_point, LayoutUnit& logical_height) const; - // Returns the size of area occupied by this LayoutText. - LayoutUnit PhysicalAreaSize() const; - - // Returns the rightmost offset occupied by this LayoutText. - LayoutUnit PhysicalRightOffset() const; - // For LayoutShiftTracker. Saves the value of LogicalStartingPoint() value // during the previous paint invalidation. LogicalOffset PreviousLogicalStartingPoint() const {
diff --git a/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc b/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc index 262fffe..ab03f78b7 100644 --- a/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc +++ b/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc
@@ -158,17 +158,6 @@ if (result.InnerNode()->IsDescendantOf(InnerEditorElement()) || result.InnerNode() == GetNode() || (container && container == result.InnerNode())) { - PhysicalOffset inner_editor_accumulated_offset = accumulated_offset; - if (container && EditingViewPortElement()) { - if (EditingViewPortElement()->GetLayoutBox()) { - inner_editor_accumulated_offset += - EditingViewPortElement()->GetLayoutBox()->PhysicalLocation(); - } - if (container->GetLayoutBox()) { - inner_editor_accumulated_offset += - container->GetLayoutBox()->PhysicalLocation(); - } - } HitInnerEditorElement(*this, *InnerEditorElement(), result, hit_test_location, accumulated_offset); }
diff --git a/third_party/blink/renderer/core/layout/ng/layout_ng_text_control_single_line.cc b/third_party/blink/renderer/core/layout/ng/layout_ng_text_control_single_line.cc index 60b7dc9..8fa73b8d 100644 --- a/third_party/blink/renderer/core/layout/ng/layout_ng_text_control_single_line.cc +++ b/third_party/blink/renderer/core/layout/ng/layout_ng_text_control_single_line.cc
@@ -64,17 +64,9 @@ // - we hit regions not in any decoration buttons. Element* container = ContainerElement(); HTMLElement* inner_editor = InnerEditorElement(); - Element* view_port = EditingViewPortElement(); if (result.InnerNode()->IsDescendantOf(inner_editor) || result.InnerNode() == GetNode() || (container && container == result.InnerNode())) { - PhysicalOffset inner_editor_accumulated_offset = accumulated_offset; - if (container && view_port) { - if (auto* view_port_box = view_port->GetLayoutBox()) - inner_editor_accumulated_offset += view_port_box->PhysicalLocation(); - if (auto* container_box = container->GetLayoutBox()) - inner_editor_accumulated_offset += container_box->PhysicalLocation(); - } LayoutTextControl::HitInnerEditorElement( *this, *inner_editor, result, hit_test_location, accumulated_offset); }
diff --git a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.cc b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.cc index 65a92618..82e93a9 100644 --- a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.cc +++ b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.cc
@@ -20,6 +20,9 @@ #include "third_party/blink/renderer/core/html/html_anchor_element.h" #include "third_party/blink/renderer/core/html/html_image_element.h" #include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h" +#include "third_party/blink/renderer/core/layout/geometry/physical_offset.h" +#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h" +#include "third_party/blink/renderer/core/layout/geometry/physical_size.h" #include "third_party/blink/renderer/core/layout/layout_image.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/layout/layout_view.h" @@ -64,9 +67,18 @@ MobileFriendlinessChecker::~MobileFriendlinessChecker() = default; -void MobileFriendlinessChecker::NotifyPaint() { +void MobileFriendlinessChecker::NotifyPaintBegin() { DCHECK(frame_view_->GetFrame().Client()->IsLocalFrameClientImpl()); DCHECK(frame_view_->GetFrame().IsOutermostMainFrame()); + + ignore_beyond_viewport_scope_count_ = + frame_view_->LayoutViewport()->MaximumScrollOffset().x() == 0 && + frame_view_->GetPage() + ->GetVisualViewport() + .MaximumScrollOffsetAtScale(initial_scale_) + .x() == 0; + is_painting_ = true; + if (timer_.IsActive() || base::TimeTicks::Now() - last_evaluated_ < kEvaluationInterval) { return; @@ -75,6 +87,13 @@ timer_.StartOneShot(kEvaluationDelay, FROM_HERE); } +void MobileFriendlinessChecker::NotifyPaintEnd() { + DCHECK(frame_view_->GetFrame().Client()->IsLocalFrameClientImpl()); + DCHECK(frame_view_->GetFrame().IsOutermostMainFrame()); + ignore_beyond_viewport_scope_count_ = 0; + is_painting_ = false; +} + void MobileFriendlinessChecker::WillBeRemovedFromFrame() { timer_.Stop(); } @@ -380,6 +399,24 @@ } // namespace +MobileFriendlinessChecker* MobileFriendlinessChecker::From( + const Document& document) { + DCHECK(document.GetFrame()); + + auto* local_frame = DynamicTo<LocalFrame>(document.GetFrame()->Top()); + if (local_frame == nullptr) + return nullptr; + + MobileFriendlinessChecker* mfc = + local_frame->View()->GetMobileFriendlinessChecker(); + if (!mfc || !mfc->is_painting_) + return nullptr; + + DCHECK_EQ(DocumentLifecycle::kInPaint, document.Lifecycle().GetState()); + DCHECK(!document.IsPrintingOrPaintingPreview()); + return mfc; +} + // Counts and calculate ration of bad tap targets. The process is a surface scan // with region tracking by Fenwick tree. The detail of the algorithm is // go/bad-tap-target-ukm @@ -472,10 +509,12 @@ .viewport_initial_scale_x10 = viewport_initial_scale_x10_, .viewport_hardcoded_width = viewport_hardcoded_width_, .allow_user_zoom = allow_user_zoom_, - .small_text_ratio = text_area_sizes_.SmallTextRatio(), + .small_text_ratio = area_sizes_.SmallTextRatio(), .text_content_outside_viewport_percentage = - ComputeContentOutsideViewport(), + area_sizes_.TextContentsOutsideViewportPercentage( + frame_view_->GetPage()->GetVisualViewport().Size().GetArea()), .bad_tap_targets_ratio = ComputeBadTapTargetsRatio()}); + last_evaluated_ = base::TimeTicks::Now(); } @@ -513,61 +552,68 @@ } } -int MobileFriendlinessChecker::TextAreaWithFontSize::SmallTextRatio() const { +int MobileFriendlinessChecker::AreaSizes::SmallTextRatio() const { if (total_text_area == 0) return 0; return small_font_area * 100 / total_text_area; } -void MobileFriendlinessChecker::NotifyInvalidatePaint( - const LayoutObject& object) { +int MobileFriendlinessChecker::AreaSizes::TextContentsOutsideViewportPercentage( + int viewport_area) const { + return std::ceil(content_beyond_viewport_area * 100 / viewport_area); +} + +void MobileFriendlinessChecker::UpdateTextAreaSizes( + const PhysicalRect& text_rect, + int font_size) { + double actual_font_size = font_size * initial_scale_ / viewport_scalar_; + double area = text_rect.Width() * text_rect.Height(); + if (std::round(actual_font_size) < kSmallFontThresholdInDips) + area_sizes_.small_font_area += area; + + area_sizes_.total_text_area += area; +} + +void MobileFriendlinessChecker::UpdateBeyondViewportAreaSizes( + const PhysicalRect& paint_rect) { + DCHECK(is_painting_); + if (ignore_beyond_viewport_scope_count_ != 0) + return; + + int frame_width = frame_view_->GetPage()->GetVisualViewport().Size().width(); + + // TODO(kumagi): Map paint_rect from the local transform space to the viewport + // space. + PhysicalRect viewport_rect( + LayoutUnit(), LayoutUnit(), + LayoutUnit(frame_width * viewport_scalar_ / initial_scale_), + LayoutUnit(kIntMaxForLayoutUnit)); + int original_size = + ClampTo<int>((paint_rect.Width() * paint_rect.Height()).ToInt()); + viewport_rect.Intersect(paint_rect); + + area_sizes_.content_beyond_viewport_area += + original_size - + ClampTo<int>((viewport_rect.Width() * viewport_rect.Height()).ToInt()); +} + +void MobileFriendlinessChecker::NotifyPaintTextFragment( + const PhysicalRect& paint_rect, + int font_size) { DCHECK(frame_view_->GetFrame().Client()->IsLocalFrameClientImpl()); DCHECK(frame_view_->GetFrame().IsOutermostMainFrame()); - // Compute small text ratio. - if (const auto* text = DynamicTo<LayoutText>(object)) { - const auto& style = text->StyleRef(); - - // Ignore elements that users cannot see. - if (style.Visibility() != EVisibility::kVisible) - return; - - // Ignore elements intended only for screen readers. - if (style.HasOutOfFlowPosition() && style.ClipLeft().IsZero() && - style.ClipRight().IsZero() && style.ClipTop().IsZero() && - style.ClipBottom().IsZero()) - return; - - double actual_font_size = - style.FontSize() * initial_scale_ / viewport_scalar_; - double area = text->PhysicalAreaSize(); - if (std::round(actual_font_size) < kSmallFontThresholdInDips) - text_area_sizes_.small_font_area += area; - - text_area_sizes_.total_text_area += area; - } + UpdateTextAreaSizes(paint_rect, font_size); + UpdateBeyondViewportAreaSizes(paint_rect); } -int MobileFriendlinessChecker::ComputeContentOutsideViewport() { - int frame_width = frame_view_->GetPage()->GetVisualViewport().Size().width(); - if (frame_width == 0) { - return 0; - } +void MobileFriendlinessChecker::NotifyPaintReplaced( + const PhysicalRect& paint_rect) { + DCHECK(frame_view_->GetFrame().Client()->IsLocalFrameClientImpl()); + DCHECK(frame_view_->GetFrame().IsLocalRoot()); - const auto* root_frame_viewport = frame_view_->GetRootFrameViewport(); - if (root_frame_viewport == nullptr) { - return 0; - } - - int content_width = - root_frame_viewport->LayoutViewport().ContentsSize().width() * - initial_scale_; - int max_scroll_offset = content_width - frame_width; - - // We use ceil function here because we want to treat 100.1% as 101 which - // requires a scroll bar. - return std::ceil(max_scroll_offset * 100.0 / frame_width); + UpdateBeyondViewportAreaSizes(paint_rect); } void MobileFriendlinessChecker::Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h index a1a2921..dd03c576 100644 --- a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h +++ b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h
@@ -16,9 +16,8 @@ namespace blink { +class Document; class LocalFrameView; -class LayoutObject; - struct ViewportDescription; // Calculates the mobile usability of current page, especially friendliness on @@ -30,46 +29,79 @@ public: explicit MobileFriendlinessChecker(LocalFrameView& frame_view); virtual ~MobileFriendlinessChecker(); + static MobileFriendlinessChecker* From(const Document&); // LocalFrameView::LifecycleNotificationObserver implementation void DidFinishLifecycleUpdate(const LocalFrameView&) override; void NotifyInitialScaleUpdated(); - void NotifyPaint(); + void NotifyPaintBegin(); + void NotifyPaintEnd(); void WillBeRemovedFromFrame(); void NotifyViewportUpdated(const ViewportDescription&); - void NotifyInvalidatePaint(const LayoutObject& object); + void NotifyPaintTextFragment(const PhysicalRect& paint_rect, int font_size); + void NotifyPaintReplaced(const PhysicalRect& paint_rect); void Trace(Visitor* visitor) const override; - struct TextAreaWithFontSize { + + struct AreaSizes { double small_font_area = 0; double total_text_area = 0; + double content_beyond_viewport_area = 0; + int TextContentsOutsideViewportPercentage(int viewport_area) const; int SmallTextRatio() const; }; + class PaintScope final { + STACK_ALLOCATED(); + + public: + explicit PaintScope(MobileFriendlinessChecker& mfc) : mfc_(mfc) { + mfc_.NotifyPaintBegin(); + } + ~PaintScope() { mfc_.NotifyPaintEnd(); } + + private: + MobileFriendlinessChecker& mfc_; + }; + + class IgnoreBeyondViewportScope final { + STACK_ALLOCATED(); + + public: + explicit IgnoreBeyondViewportScope(MobileFriendlinessChecker& mfc) + : mfc_(mfc) { + mfc_.ignore_beyond_viewport_scope_count_++; + } + ~IgnoreBeyondViewportScope() { mfc_.ignore_beyond_viewport_scope_count_--; } + + private: + MobileFriendlinessChecker& mfc_; + }; + private: void Activate(TimerBase*); - // Returns the percentage of the width of the content that overflows the - // viewport. - // Returns 0 if all content fits in the viewport. - int ComputeContentOutsideViewport(); - // Returns percentage value [0-100] of bad tap targets in the area of the // first page. Returns kTimeBudgetExceeded if the time limit is exceeded. int ComputeBadTapTargetsRatio(); + void UpdateTextAreaSizes(const PhysicalRect& text_rect, int font_size); + void UpdateBeyondViewportAreaSizes(const PhysicalRect& paint_rect); + private: Member<LocalFrameView> frame_view_; HeapTaskRunnerTimer<MobileFriendlinessChecker> timer_; double viewport_scalar_; double initial_scale_ = 1.0; base::TimeTicks last_evaluated_; - TextAreaWithFontSize text_area_sizes_; + AreaSizes area_sizes_; bool viewport_device_width_ = false; bool allow_user_zoom_ = true; int viewport_initial_scale_x10_ = -1; int viewport_hardcoded_width_ = -1; + int ignore_beyond_viewport_scope_count_ = 0; + bool is_painting_ = false; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker_test.cc b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker_test.cc index 35d338d..dd88736 100644 --- a/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker_test.cc +++ b/third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker_test.cc
@@ -110,6 +110,7 @@ .SetShrinksViewportContentToFit(true); helper->GetWebView()->GetPage()->GetSettings().SetViewportStyle( mojom::blink::ViewportStyle::kMobile); + helper->LoadAhem(); return helper; } @@ -396,8 +397,8 @@ </body> </html> )"); - EXPECT_LT(actual_mf.small_text_ratio, 100); - EXPECT_GT(actual_mf.small_text_ratio, 68); + EXPECT_LT(actual_mf.small_text_ratio, 90); + EXPECT_GT(actual_mf.small_text_ratio, 60); } TEST_F(MobileFriendlinessCheckerTest, DontCountInvisibleSmallFontArea) { @@ -547,6 +548,28 @@ )"); // Automatic zoom-out makes text small and image fits in display. EXPECT_EQ(actual_mf.small_text_ratio, 100); + EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 10); +} + +TEST_F(MobileFriendlinessCheckerTest, ZIndex) { + MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( +<html> + <head> + <meta name="viewport" content="width=device-width,initial-scale=1.0"> + </head> + <body style="margin:240px;font-size: 12pt"> + <div style="z-index: 1"> + hello + <div style="z-index: 10"> + foo + <img style="width:5000px; height:380px"> + <p>Normal font text.</p> + </div> + </div> + </body> +</html> +)"); + EXPECT_EQ(actual_mf.small_text_ratio, 0); EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 50); } @@ -557,14 +580,14 @@ <head> <meta name="viewport" content="initial-scale=1.0"> </head> - <body> - <img style="width:3000px; height:50px"> + <body style="margin: 0px"> + <img style="width:3000px; height:240px"> <p style="font-size: 9pt">Normal font text.</p> </body> </html> )"); EXPECT_EQ(actual_mf.small_text_ratio, 0); - EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 100); + EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 50); } TEST_F(MobileFriendlinessCheckerTest, @@ -575,8 +598,8 @@ <head> <meta name="viewport" content="initial-scale=1.0"> </head> - <body> - <img style="width:3000px; height:50px"> + <body style="margin: 0px"> + <img style="width:3000px; height:240px"> <p style="font-size: 6pt">Illegible font text.</p> </body> </html> @@ -645,31 +668,77 @@ R"( <html> <head> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> <meta name="viewport" content="initial-scale=1.0"> </head> <body> - <pre>)" + + <pre style="font: 30px Ahem; line-height: 1">)" + std::string(10000, 'a') + R"(</pre> </body> </html> )"); - EXPECT_NE(actual_mf.text_content_outside_viewport_percentage, 0); + EXPECT_GT(actual_mf.text_content_outside_viewport_percentage, 20); } -TEST_F(MobileFriendlinessCheckerTest, TextTooWideAbsolutePositioning) { +TEST_F(MobileFriendlinessCheckerTest, TextAbsolutePositioning) { MobileFriendliness actual_mf = CalculateMetricsForHTMLString( R"( <html> <head> <meta name="viewport" content="initial-scale=1.0"> </head> - <body> - <pre style="position:absolute; left:2000px">a</pre> + <body style="font-size: 12px"> + <pre style="position:absolute; left:2000px">)" + + std::string(10000, 'a') + + R"(</pre> </body> </html> )"); - EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 317); + EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 15); +} + +TEST_F(MobileFriendlinessCheckerTest, ImageAbsolutePositioning) { + MobileFriendliness actual_mf_full_out = CalculateMetricsForHTMLString( + R"( +<html> + <head> + <meta name="viewport" content="initial-scale=1.0"> + </head> + <body style="margin: 0px"> + <img style="width:480px; height:800px; position:absolute; left:480px"> + </body> +</html> +)"); + EXPECT_EQ(actual_mf_full_out.text_content_outside_viewport_percentage, 100); + + MobileFriendliness actual_mf_half_out = CalculateMetricsForHTMLString( + R"( +<html> + <head> + <meta name="viewport" content="initial-scale=1.0"> + </head> + <body style="margin: 0px"> + <img style="width:480px; height:800px; position:absolute; left:240px"> + </body> +</html> +)"); + EXPECT_EQ(actual_mf_half_out.text_content_outside_viewport_percentage, 50); +} + +TEST_F(MobileFriendlinessCheckerTest, SmallTextOutsideViewportCeiling) { + MobileFriendliness actual_mf = CalculateMetricsForHTMLString( + R"( +<html> + <head> + <meta name="viewport" content="initial-scale=1.0"> + </head> + <body style="font-size: 12px"> + <pre style="position:absolute; left:2000px">x</pre> + </body> +</html> +)"); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 1); } TEST_F(MobileFriendlinessCheckerTest, TextTooWideOverflowXHidden) { @@ -680,7 +749,7 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> - <pre style="overflow-x:hidden">)" + + <pre style="overflow-x:hidden; font-size:12px">)" + std::string(10000, 'a') + R"(</pre> </body> </html> @@ -713,7 +782,7 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> - <div style="overflow:hidden"> + <div style="overflow:hidden; font-size: 12px"> <pre>)" + std::string(10000, 'a') + R"( @@ -729,6 +798,9 @@ MobileFriendliness actual_mf = CalculateMetricsForHTMLString( R"( <html> + <head> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + </head> <body> <div style="overflow:hidden"> <div> @@ -766,7 +838,37 @@ </body> </html> )"); - EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 319); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 20); +} + +TEST_F(MobileFriendlinessCheckerTest, ImageTooWide100) { + MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( +<html> + <head> + <meta name="viewport" content="initial-scale=1.0"> + </head> + <body style="margin:0px;"> + <img style="width:960px; height:800px"> + </body> +</html> +)"); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 100); +} + +TEST_F(MobileFriendlinessCheckerTest, WideImageClipped) { + MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( +<html> + <head> + <meta name="viewport" content="initial-scale=1.0"> + </head> + <body> + <div style="overflow: hidden"> + <img style="width:2000px; height:50px"> + </div> + </body> +</html> +)"); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 0); } TEST_F(MobileFriendlinessCheckerTest, ImageTooWideTwoImages) { @@ -775,13 +877,13 @@ <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> - <body style="width:4000px"> + <body style="width:4036px"> <img style="width:2000px; height:50px"> <img style="width:2000px; height:50px"> </body> </html> )"); - EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 735); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 46); } TEST_F(MobileFriendlinessCheckerTest, ImageTooWideAbsolutePosition) { @@ -795,7 +897,7 @@ </body> </html> )"); - EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 417); + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 100); } TEST_F(MobileFriendlinessCheckerTest, ImageTooWideDisplayNone) { @@ -813,9 +915,10 @@ MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( <html> <head> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> <meta name="viewport" content="minimum-scale=1, initial-scale=3"> </head> - <body style="font-size: 76px; width: 480"> + <body style="font: 76px Ahem; width: 480"> foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo @@ -830,17 +933,20 @@ </html> )"); EXPECT_EQ(actual_mf.viewport_initial_scale_x10, 30); - EXPECT_GE(actual_mf.text_content_outside_viewport_percentage, 100.0); + EXPECT_GT(actual_mf.text_content_outside_viewport_percentage, 90); } TEST_F(MobileFriendlinessCheckerTest, ScrollerOutsideViewport) { MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( <html> <head> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> <style> + body { + margin: 0px; + } div.scrollmenu { background-color: #333; - overflow: auto; white-space: nowrap; } div.scrollmenu a { @@ -849,9 +955,9 @@ padding: 14px; } </style> - <meta name="viewport" content="width=device-width, initial-scale=1.0 minimum-scale=1.0"> + <meta name="viewport" content="width=480px, initial-scale=1.0 minimum-scale=1.0">f </head> - <body style="font-size: 18px"> + <body style="font: 40px/1 Ahem; line-height: 1"> <div class="scrollmenu"> <a href="#1">First text</a> <a href="#2">Second text</a> @@ -863,12 +969,59 @@ <a href="#8">Eighth text</a> <a href="#9">Ninth text</a> <a href="#10">Tenth text</a> + <a href="#11">Eleventh text</a> + <a href="#12">Twelveth text</a> </div> </body> </html> )"); // the viewport - EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 0.0); + EXPECT_GT(actual_mf.text_content_outside_viewport_percentage, 10); +} + +TEST_F(MobileFriendlinessCheckerTest, SubScroller) { + MobileFriendliness actual_mf = CalculateMetricsForHTMLString(R"( +<html> + <head> + <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> + <style> + body { + margin: 0px; + } + div.scrollmenu { + width: 480px; + background-color: #333; + overflow: scroll; + white-space: nowrap; + } + div.scrollmenu a { + display: inline-block; + color: white; + padding: 14px; + } + </style> + <meta name="viewport" content="width=480px, initial-scale=1.0 minimum-scale=1.0"> + </head> + <body style="font: 40px/1 Ahem; line-height: 1"> + <div class="scrollmenu"> + <a href="#1">First text</a> + <a href="#2">Second text</a> + <a href="#3">Third text</a> + <a href="#4">Fourth text</a> + <a href="#5">Fifth text</a> + <a href="#6">Sixth text</a> + <a href="#7">Seventh text</a> + <a href="#8">Eighth text</a> + <a href="#9">Ninth text</a> + <a href="#10">Tenth text</a> + <a href="#11">Eleventh text</a> + <a href="#12">Twelveth text</a> + </div> + </body> +</html> +)"); + // Fits within the viewport by scrollbar. + EXPECT_EQ(actual_mf.text_content_outside_viewport_percentage, 0); } TEST_F(MobileFriendlinessCheckerTest, SingleTapTarget) { @@ -1497,7 +1650,7 @@ EXPECT_EQ(actual_mf.bad_tap_targets_ratio, 100); } -TEST_F(MobileFriendlinessCheckerTest, IFrameTest) { +TEST_F(MobileFriendlinessCheckerTest, IFrame) { url_test_helpers::RegisterMockedURLLoadFromBase( WebString::FromUTF8(kBaseUrl), blink::test::CoreTestDataPath(), WebString::FromUTF8("visible_iframe.html"));
diff --git a/third_party/blink/renderer/core/paint/applied_decoration_painter.cc b/third_party/blink/renderer/core/paint/applied_decoration_painter.cc index bc8ae84..eeced84 100644 --- a/third_party/blink/renderer/core/paint/applied_decoration_painter.cc +++ b/third_party/blink/renderer/core/paint/applied_decoration_painter.cc
@@ -11,19 +11,15 @@ namespace blink { void AppliedDecorationPainter::Paint(const cc::PaintFlags* flags) { - ETextDecorationStyle decoration_style = decoration_info_.DecorationStyle(); - context_.SetStrokeStyle(decoration_info_.StrokeStyle()); context_.SetStrokeColor(decoration_info_.LineColor()); AutoDarkMode auto_dark_mode( PaintAutoDarkMode(decoration_info_.TargetStyle(), DarkModeFilter::ElementRole::kForeground)); - - // TODO(crbug.com/1346281) make other decoration styles work with PaintFlags - switch (decoration_style) { + switch (decoration_info_.DecorationStyle()) { case ETextDecorationStyle::kWavy: - PaintWavyTextDecoration(); + StrokeWavyTextDecoration(flags); break; case ETextDecorationStyle::kDotted: case ETextDecorationStyle::kDashed: @@ -42,7 +38,8 @@ } } -void AppliedDecorationPainter::PaintWavyTextDecoration() { +void AppliedDecorationPainter::StrokeWavyTextDecoration( + const cc::PaintFlags* flags) { // We need this because of the clipping we're doing below, as we paint both // overlines and underlines here. That clip would hide the overlines, when // painting the underlines. @@ -52,21 +49,16 @@ // The wavy line is larger than the line, as we add whole waves before and // after the line in TextDecorationInfo::PrepareWavyStrokePath(). - gfx::PointF origin = decoration_info_.Bounds().origin(); + context_.Clip(decoration_info_.Bounds()); + absl::optional<Path> path = decoration_info_.StrokePath(); AutoDarkMode auto_dark_mode( PaintAutoDarkMode(decoration_info_.TargetStyle(), DarkModeFilter::ElementRole::kForeground)); - cc::PaintFlags flags; - - flags.setAntiAlias(true); - flags.setShader(PaintShader::MakePaintRecord( - decoration_info_.WavyTileRecord(), - gfx::RectFToSkRect(decoration_info_.WavyTileRect()), SkTileMode::kRepeat, - SkTileMode::kDecal, nullptr)); - context_.Translate(origin.x(), origin.y()); - context_.DrawRect(gfx::RectFToSkRect(decoration_info_.WavyPaintRect()), flags, - auto_dark_mode); + if (flags) + context_.DrawPath(path->GetSkPath(), *flags, auto_dark_mode); + else + context_.StrokePath(path.value(), auto_dark_mode); } } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/applied_decoration_painter.h b/third_party/blink/renderer/core/paint/applied_decoration_painter.h index c4b08fc9..e7256e27 100644 --- a/third_party/blink/renderer/core/paint/applied_decoration_painter.h +++ b/third_party/blink/renderer/core/paint/applied_decoration_painter.h
@@ -26,7 +26,7 @@ void Paint(const cc::PaintFlags* flags = nullptr); private: - void PaintWavyTextDecoration(); + void StrokeWavyTextDecoration(const cc::PaintFlags* flags); GraphicsContext& context_; const TextDecorationInfo& decoration_info_;
diff --git a/third_party/blink/renderer/core/paint/inline_text_box_painter.cc b/third_party/blink/renderer/core/paint/inline_text_box_painter.cc index 49260bc..b1086ee 100644 --- a/third_party/blink/renderer/core/paint/inline_text_box_painter.cc +++ b/third_party/blink/renderer/core/paint/inline_text_box_painter.cc
@@ -19,6 +19,7 @@ #include "third_party/blink/renderer/core/layout/layout_theme.h" #include "third_party/blink/renderer/core/layout/line/inline_text_box.h" #include "third_party/blink/renderer/core/layout/text_decoration_offset.h" +#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/paint/applied_decoration_painter.h" #include "third_party/blink/renderer/core/paint/document_marker_painter.h" #include "third_party/blink/renderer/core/paint/highlight_painting_utils.h" @@ -160,6 +161,18 @@ physical_overflow.Move(paint_offset); gfx::Rect visual_rect = ToEnclosingRect(physical_overflow); + if (paint_info.phase == PaintPhase::kForeground) { + if (auto* mf_checker = MobileFriendlinessChecker::From( + inline_text_box_.GetLineLayoutItem().GetDocument())) { + if (const auto* text = DynamicTo<LayoutText>(InlineLayoutObject())) { + PhysicalRect clipped_rect = PhysicalRect(visual_rect); + clipped_rect.Intersect(PhysicalRect(paint_info.GetCullRect().Rect())); + mf_checker->NotifyPaintTextFragment(clipped_rect, + text->StyleRef().FontSize()); + } + } + } + GraphicsContext& context = paint_info.context; PhysicalOffset box_origin = inline_text_box_.PhysicalLocation() + paint_offset;
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc index 5c9eed7..1178a3d 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -218,7 +218,7 @@ // // TODO(kojii): This may become more complicated when we use // |NGBoxFragmentPainter| for all fragments, and we still want this -// oprimization. +// optimization. bool FragmentRequiresLegacyFallback(const NGPhysicalFragment& fragment) { // If |fragment| is |IsFormattingContextRoot|, it may be legacy. // Avoid falling back to |LayoutObject| if |CanTraverse|, because it
diff --git a/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc index 9ae20f2..1c179c60 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h" +#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/paint/document_marker_painter.h" #include "third_party/blink/renderer/core/paint/highlight_painting_utils.h" #include "third_party/blink/renderer/core/paint/inline_text_box_painter.h" @@ -335,6 +336,16 @@ fragment_paint_info, text_painter, decoration_painter, paint_info, cursor_, *cursor_.CurrentItem(), rotation, rotated_box, physical_box.offset, style, text_style, selection, is_printing); + if (paint_info.phase == PaintPhase::kForeground) { + if (auto* mf_checker = MobileFriendlinessChecker::From(document)) { + if (auto* text = DynamicTo<LayoutText>(*layout_object)) { + PhysicalRect clipped_rect = PhysicalRect(visual_rect); + clipped_rect.Intersect(PhysicalRect(paint_info.GetCullRect().Rect())); + mf_checker->NotifyPaintTextFragment(clipped_rect, + text->StyleRef().FontSize()); + } + } + } if (svg_inline_text) { NGTextPainter::SvgTextPaintState& svg_state = text_painter.SetSvgState(
diff --git a/third_party/blink/renderer/core/paint/paint_invalidator.cc b/third_party/blink/renderer/core/paint/paint_invalidator.cc index 7dece503..190ece2 100644 --- a/third_party/blink/renderer/core/paint/paint_invalidator.cc +++ b/third_party/blink/renderer/core/paint/paint_invalidator.cc
@@ -319,15 +319,6 @@ reason == PaintInvalidationReason::kJustCreated)) pending_delayed_paint_invalidations_.push_back(&object); - if (auto* local_frame = DynamicTo<LocalFrame>(object.GetFrame()->Top())) { - if (auto* mf_checker = - local_frame->View()->GetMobileFriendlinessChecker()) { - if (tree_builder_context && - (!pre_paint_info || pre_paint_info->is_last_for_node)) - mf_checker->NotifyInvalidatePaint(object); - } - } - return reason != PaintInvalidationReason::kNone; }
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index f6ad7ee5..5c51b34 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -308,8 +308,23 @@ if (LayoutBox* box = DynamicTo<LayoutBox>(GetLayoutObject()); box && box->AnchorScrollContainer()) { - PaintLayer* scroll_container_layer = box->AnchorScrollContainer()->Layer(); - scroll_container_layer->GetScrollableArea()->AddAnchorPositionedLayer(this); + const PaintLayer* boundary = ContainingScrollContainerLayer(); + DCHECK(boundary); + + bool needs_paint_property_update = false; + for (const PaintLayer* scroller_layer = + box->AnchorScrollContainer()->Layer(); + scroller_layer != ContainingScrollContainerLayer(); + scroller_layer = scroller_layer->ContainingScrollContainerLayer()) { + DCHECK(scroller_layer); + bool is_new_entry = + scroller_layer->GetScrollableArea()->AddAnchorPositionedLayer(this); + if (!is_new_entry) + break; + needs_paint_property_update = true; + } + if (needs_paint_property_update) + box->SetNeedsPaintPropertyUpdate(); } // Display-locked elements always have a PaintLayer, meaning that the
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc index a48c4f6..70453275 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
@@ -2101,10 +2101,9 @@ } } -void PaintLayerScrollableArea::AddAnchorPositionedLayer(PaintLayer* layer) { +bool PaintLayerScrollableArea::AddAnchorPositionedLayer(PaintLayer* layer) { auto add_result = EnsureRareData().anchor_positioned_layers_.insert(layer); - if (add_result.is_new_entry) - layer->GetLayoutObject().SetNeedsPaintPropertyUpdate(); + return add_result.is_new_entry; } void PaintLayerScrollableArea::InvalidateAllAnchorPositionedLayers() {
diff --git a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h index 98f3824..77bfe4b 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h +++ b/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h
@@ -524,7 +524,8 @@ void InvalidateAllStickyConstraints(); void InvalidatePaintForStickyDescendants(); - void AddAnchorPositionedLayer(PaintLayer*); + // Returns true if the layer is not already added. + bool AddAnchorPositionedLayer(PaintLayer*); void InvalidateAllAnchorPositionedLayers(); void InvalidatePaintForAnchorPositionedLayers();
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc index 4c2b6d3..ac731406 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -764,16 +764,18 @@ if (NeedsPaintPropertyUpdate()) { if (NeedsAnchorScrollTranslation(object_)) { const auto& box = To<LayoutBox>(object_); - const PaintLayer* anchor_scroll_container_layer = + const PaintLayer* inner_most_scroll_container_layer = box.AnchorScrollContainer()->Layer(); + gfx::Vector2dF accumulated_scroll_offset(0, 0); + for (const PaintLayer* layer = inner_most_scroll_container_layer; layer; + layer = layer->ContainingScrollContainerLayer()) { + if (layer == box.Layer()->ContainingScrollContainerLayer()) + break; + accumulated_scroll_offset += + layer->GetScrollableArea()->ScrollPosition().OffsetFromOrigin(); + } - // TODO(crbug.com/1309178): We need to accumulate the translation offsets - // of all the scroll containers up to the containing block. - gfx::Vector2dF scroll_offset = - anchor_scroll_container_layer->GetScrollableArea() - ->ScrollPosition() - .OffsetFromOrigin(); - gfx::Vector2dF translation_offset = -scroll_offset; + gfx::Vector2dF translation_offset = -accumulated_scroll_offset; TransformPaintPropertyNode::State state{translation_offset}; // TODO(crbug.com/1309178): Not using GetCompositorElementId() here @@ -787,11 +789,6 @@ state.rendering_context_id = context_.rendering_context_id; state.flags.flattens_inherited_transform = context_.should_flatten_inherited_transform; - state.anchor_scroll_container = - anchor_scroll_container_layer->GetLayoutObject() - .FirstFragment() - .PaintProperties() - ->ScrollTranslation(); OnUpdateTransform(properties_->UpdateAnchorScrollTranslation( *context_.current.transform, std::move(state)));
diff --git a/third_party/blink/renderer/core/paint/paint_timing.cc b/third_party/blink/renderer/core/paint/paint_timing.cc index 7c819a9..d900d127 100644 --- a/third_party/blink/renderer/core/paint/paint_timing.cc +++ b/third_party/blink/renderer/core/paint/paint_timing.cc
@@ -17,7 +17,6 @@ #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/interactive_detector.h" #include "third_party/blink/renderer/core/loader/progress_tracker.h" -#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.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/probe/core_probes.h" @@ -190,10 +189,6 @@ if (image_painted) MarkFirstImagePaint(); fmp_detector_->NotifyPaint(); - if (auto* local_frame = DynamicTo<LocalFrame>(GetFrame()->Top())) { - if (auto* mf_checker = local_frame->View()->GetMobileFriendlinessChecker()) - mf_checker->NotifyPaint(); - } if (is_first_paint) GetFrame()->OnFirstPaint(text_painted, image_painted);
diff --git a/third_party/blink/renderer/core/paint/replaced_painter.cc b/third_party/blink/renderer/core/paint/replaced_painter.cc index 0f1cc456..33c0e0f 100644 --- a/third_party/blink/renderer/core/paint/replaced_painter.cc +++ b/third_party/blink/renderer/core/paint/replaced_painter.cc
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/core/frame/web_feature.h" #include "third_party/blink/renderer/core/layout/layout_replaced.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_root.h" +#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/paint/highlight_painting_utils.h" #include "third_party/blink/renderer/core/paint/object_painter.h" @@ -35,6 +36,10 @@ public: ScopedReplacedContentPaintState(const ScopedPaintState& input, const LayoutReplaced& replaced); + + private: + absl::optional<MobileFriendlinessChecker::IgnoreBeyondViewportScope> + mf_ignore_scope_; }; ScopedReplacedContentPaintState::ScopedReplacedContentPaintState( @@ -70,6 +75,18 @@ new_properties, replaced, input_paint_info_.DisplayItemTypeForClipping()); } + + if (input_paint_info_.phase == PaintPhase::kForeground) { + if (auto* mf_checker = + MobileFriendlinessChecker::From(replaced.GetDocument())) { + PhysicalRect content_rect = replaced.ReplacedContentRect(); + content_rect.Move(paint_offset_); + content_rect.Intersect(PhysicalRect(GetPaintInfo().GetCullRect().Rect())); + mf_checker->NotifyPaintReplaced(content_rect); + + mf_ignore_scope_.emplace(*mf_checker); + } + } } } // anonymous namespace
diff --git a/third_party/blink/renderer/core/paint/scoped_paint_state.cc b/third_party/blink/renderer/core/paint/scoped_paint_state.cc index a6cc50d..8d151d8a 100644 --- a/third_party/blink/renderer/core/paint/scoped_paint_state.cc +++ b/third_party/blink/renderer/core/paint/scoped_paint_state.cc
@@ -141,6 +141,23 @@ box.Layer()->SetPreviousPaintResult(kMayBeClippedByCullRect); } } + + if (input_paint_info_.phase == PaintPhase::kForeground) { + // We treat horizontal-scrollable scrollers like replaced objects. + if (auto* scrollable_area = box.GetScrollableArea()) { + if (scrollable_area->HasHorizontalScrollbar()) { + if (auto* mf_checker = + MobileFriendlinessChecker::From(box.GetDocument())) { + PhysicalRect content_rect = box.LocalVisualRect(); + content_rect.Move(paint_offset_); + content_rect.Intersect( + PhysicalRect(input_paint_info_.GetCullRect().Rect())); + mf_checker->NotifyPaintReplaced(content_rect); + mf_ignore_scope_.emplace(*mf_checker); + } + } + } + } } } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/scoped_paint_state.h b/third_party/blink/renderer/core/paint/scoped_paint_state.h index ac3ebb6b..d3a4df9 100644 --- a/third_party/blink/renderer/core/paint/scoped_paint_state.h +++ b/third_party/blink/renderer/core/paint/scoped_paint_state.h
@@ -8,6 +8,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/layout/layout_box.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h" +#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/paint/paint_info.h" #include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h" @@ -121,6 +122,8 @@ private: void AdjustForBoxContents(const LayoutBox&); + absl::optional<MobileFriendlinessChecker::IgnoreBeyondViewportScope> + mf_ignore_scope_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/text_decoration_info.cc b/third_party/blink/renderer/core/paint/text_decoration_info.cc index 892ff4f1..6eca63e 100644 --- a/third_party/blink/renderer/core/paint/text_decoration_info.cc +++ b/third_party/blink/renderer/core/paint/text_decoration_info.cc
@@ -144,139 +144,6 @@ return stroke_style; } -struct WavyParams { - float resolved_thickness; - bool spelling_grammar; - Color color; -}; - -float WavyDecorationSizing(const WavyParams& params) { - // Minimum unit we use to compute control point distance and step to define - // the path of the Bezier curve. - return std::max<float>(2, params.resolved_thickness); -} - -float WavyControlPointDistance(const WavyParams& params) { - // Distance between decoration's axis and Bezier curve's control points. The - // height of the curve is based on this distance. Increases the curve's height - // as strokeThickness increases to make the curve look better. - if (params.spelling_grammar) - return 5; - - return 3.5 * WavyDecorationSizing(params); -} - -float WavyStep(const WavyParams& params) { - // Increment used to form the diamond shape between start point (p1), control - // points and end point (p2) along the axis of the decoration. Makes the curve - // wider as strokeThickness increases to make the curve look better. - if (params.spelling_grammar) - return 3; - - return 2.5 * WavyDecorationSizing(params); -} - -// Computes the wavy pattern rect, which is where the desired wavy pattern would -// be found when painting the wavy stroke path at the origin, or in other words, -// how far PrepareWavyTileRecord needs to translate in the opposite direction -// when painting to ensure that nothing is painted at y<0. -gfx::RectF ComputeWavyPatternRect(const WavyParams& params, - const Path& stroke_path) { - StrokeData stroke_data; - stroke_data.SetThickness(params.resolved_thickness); - - // Expand the stroke rect to integer y coordinates in both directions, to - // avoid messing with the vertical antialiasing. - gfx::RectF stroke_rect = stroke_path.StrokeBoundingRect(stroke_data); - DCHECK_LT(stroke_rect.y(), 0.f); - float top = -std::ceilf(std::fabsf(stroke_rect.y())); - float bottom = std::ceilf(stroke_rect.bottom()); - return {0.f, top, 2.f * WavyStep(params), bottom - top}; -} - -// Prepares a path for a cubic Bezier curve repeated three times, yielding a -// wavy pattern that we can cut into a tiling shader (PrepareWavyTileRecord). -// -// The result ignores the local origin, line offset, and (wavy) double offset, -// so the midpoints are always at y=0.5, while the phase is shifted for either -// wavy or spelling/grammar decorations so the desired pattern starts at x=0. -// -// The start point, control points (cp1 and cp2), and end point of each curve -// form a diamond shape: -// -// cp2 cp2 cp2 -// --- + + + -// | x=0 -// | control |--- spelling/grammar ---| -// | point . . . . . . -// | distance . . . . . . -// | . . . . . . -// +-- y=0.5 . + . + . + -// . . . . . . -// . . . . . . -// . . . . . . -// |-------- other ---------| -// x=0 -// + + + -// cp1 cp1 cp1 -// |-----------|------------| -// step step -Path PrepareWavyStrokePath(const WavyParams& params) { - float control_point_distance = WavyControlPointDistance(params); - float step = WavyStep(params); - - // We paint the wave before and after the text line (to cover the whole length - // of the line) and then we clip it at - // AppliedDecorationPainter::StrokeWavyTextDecoration(). - // Offset the start point, so the beizer curve starts before the current line, - // that way we can clip it exactly the same way in both ends. - // For spelling and grammar errors we offset by half a step less, to get a - // result closer to Microsoft Word circa 2021. - float phase_shift = (params.spelling_grammar ? -1.5f : -2.f) * step; - - // Midpoints at y=0.5, to reduce vertical antialiasing. - gfx::PointF start{phase_shift, 0.5f}; - gfx::PointF end{start + gfx::Vector2dF(2.f * step, 0.f)}; - gfx::PointF cp1{start + gfx::Vector2dF(step, +control_point_distance)}; - gfx::PointF cp2{start + gfx::Vector2dF(step, -control_point_distance)}; - - Path result{}; - result.MoveTo(start); - - result.AddBezierCurveTo(cp1, cp2, end); - cp1.set_x(cp1.x() + 2.f * step); - cp2.set_x(cp2.x() + 2.f * step); - end.set_x(end.x() + 2.f * step); - result.AddBezierCurveTo(cp1, cp2, end); - cp1.set_x(cp1.x() + 2.f * step); - cp2.set_x(cp2.x() + 2.f * step); - end.set_x(end.x() + 2.f * step); - result.AddBezierCurveTo(cp1, cp2, end); - - return result; -} - -sk_sp<cc::PaintRecord> PrepareWavyTileRecord(const WavyParams& params, - const Path& stroke_path, - const gfx::RectF& pattern_rect) { - cc::PaintFlags flags; - flags.setAntiAlias(true); - flags.setColor(params.color.Rgb()); - flags.setStyle(cc::PaintFlags::kStroke_Style); - flags.setStrokeWidth(params.resolved_thickness); - - // Create a canvas with origin (0,0) and size of the wavy pattern rect. - PaintRecorder recorder; - recorder.beginRecording(pattern_rect.width(), pattern_rect.height()); - - // Translate the wavy pattern so that nothing is painted at y<0. - cc::RecordPaintCanvas* canvas = recorder.getRecordingCanvas(); - canvas->translate(-pattern_rect.x(), -pattern_rect.y()); - canvas->cc::PaintCanvas::drawPath(stroke_path.GetSkPath(), flags); - - return recorder.finishRecordingAsPicture(); -} - } // anonymous namespace TextDecorationInfo::TextDecorationInfo( @@ -435,16 +302,12 @@ case ETextDecorationStyle::kDotted: case ETextDecorationStyle::kDashed: line_data_.stroke_path = PrepareDottedOrDashedStrokePath(); - line_data_.wavy_tile_record.reset(); break; case ETextDecorationStyle::kWavy: - line_data_.stroke_path.reset(); - ComputeWavyLineData(line_data_.wavy_pattern_rect, - line_data_.wavy_tile_record); + line_data_.stroke_path = PrepareWavyStrokePath(); break; default: line_data_.stroke_path.reset(); - line_data_.wavy_tile_record.reset(); } } @@ -618,33 +481,6 @@ return thickness; } -void TextDecorationInfo::ComputeWavyLineData( - gfx::RectF& pattern_rect, - sk_sp<cc::PaintRecord>& tile_record) const { - struct WavyCache { - WavyParams key; - gfx::RectF pattern_rect; - sk_sp<cc::PaintRecord> tile_record; - }; - - DEFINE_STATIC_LOCAL(absl::optional<WavyCache>, wavy_cache, (absl::nullopt)); - - if (wavy_cache && wavy_cache->key.resolved_thickness == ResolvedThickness() && - wavy_cache->key.spelling_grammar == IsSpellingOrGrammarError() && - wavy_cache->key.color == LineColor()) { - pattern_rect = wavy_cache->pattern_rect; - tile_record = wavy_cache->tile_record; - return; - } - - WavyParams params{ResolvedThickness(), IsSpellingOrGrammarError(), - LineColor()}; - Path stroke_path = PrepareWavyStrokePath(params); - pattern_rect = ComputeWavyPatternRect(params, stroke_path); - tile_record = PrepareWavyTileRecord(params, stroke_path, pattern_rect); - wavy_cache = WavyCache{params, pattern_rect, tile_record}; -} - gfx::RectF TextDecorationInfo::Bounds() const { gfx::PointF start_point = StartPoint(); switch (DecorationStyle()) { @@ -677,42 +513,18 @@ return line_data_.stroke_path.value().StrokeBoundingRect(stroke_data); } -// Returns the wavy bounds, which is the same size as the wavy paint rect but -// at the origin needed by the actual decoration, for the global transform. -// -// The origin is the sum of the local origin, line offset, (wavy) double offset, -// and the origin of the wavy pattern rect (around minus half the amplitude). gfx::RectF TextDecorationInfo::BoundsForWavy() const { - gfx::SizeF size = WavyPaintRect().size(); - gfx::PointF origin = line_data_.wavy_pattern_rect.origin(); - origin += StartPoint().OffsetFromOrigin(); - origin += gfx::Vector2dF{0.f, DoubleOffset() * line_data_.wavy_offset_factor}; - return {origin, size}; + StrokeData stroke_data; + stroke_data.SetThickness(ResolvedThickness()); + auto bounding_rect = line_data_.stroke_path->StrokeBoundingRect(stroke_data); + + bounding_rect.set_x(StartPoint().x()); + bounding_rect.set_width(width_); + return bounding_rect; } -// Returns the wavy paint rect, which has the height of the wavy tile rect but -// the width needed by the actual decoration, for the DrawRect operation. -// -// The origin is still (0,0) so that the shader local matrix is independent of -// the origin of the decoration, allowing Skia to cache the tile. To determine -// the origin of the decoration, use Bounds().origin(). -gfx::RectF TextDecorationInfo::WavyPaintRect() const { - gfx::RectF result = WavyTileRect(); - result.set_width(width_); - return result; -} - -// Returns the wavy tile rect, which is the same size as the wavy pattern rect -// but at origin (0,0), for converting the PaintRecord to a PaintShader. -gfx::RectF TextDecorationInfo::WavyTileRect() const { - gfx::RectF result = line_data_.wavy_pattern_rect; - result.set_x(0.f); - result.set_y(0.f); - return result; -} - -sk_sp<cc::PaintRecord> TextDecorationInfo::WavyTileRecord() const { - return line_data_.wavy_tile_record; +absl::optional<Path> TextDecorationInfo::StrokePath() const { + return line_data_.stroke_path; } void TextDecorationInfo::SetHighlightOverrideColor( @@ -720,6 +532,32 @@ highlight_override_ = color; } +float TextDecorationInfo::WavyDecorationSizing() const { + // Minimum unit we use to compute control point distance and step to define + // the path of the Bezier curve. + return std::max<float>(2, ResolvedThickness()); +} + +float TextDecorationInfo::ControlPointDistanceFromResolvedThickness() const { + // Distance between decoration's axis and Bezier curve's control points. The + // height of the curve is based on this distance. Increases the curve's height + // as strokeThickness increases to make the curve look better. + if (IsSpellingOrGrammarError()) + return 5; + + return 3.5 * WavyDecorationSizing(); +} + +float TextDecorationInfo::StepFromResolvedThickness() const { + // Increment used to form the diamond shape between start point (p1), control + // points and end point (p2) along the axis of the decoration. Makes the curve + // wider as strokeThickness increases to make the curve look better. + if (IsSpellingOrGrammarError()) + return 3; + + return 2.5 * WavyDecorationSizing(); +} + Path TextDecorationInfo::PrepareDottedOrDashedStrokePath() const { // These coordinate transforms need to match what's happening in // GraphicsContext's drawLineForText and drawLine. @@ -729,4 +567,118 @@ TextDecorationStyleToStrokeStyle(DecorationStyle())); } +/* + * Prepare a path for a cubic Bezier curve and repeat the same pattern long the + * the decoration's axis. The start point (p1), controlPoint1, controlPoint2 + * and end point (p2) of the Bezier curve form a diamond shape: + * + * step + * |-----------| + * + * controlPoint1 + * + + * + * + * . . + * . . + * . . + * (x1, y1) p1 + . + p2 (x2, y2) - <--- Decoration's axis + * . . | + * . . | + * . . | controlPointDistance + * | + * | + * + - + * controlPoint2 + * + * |-----------| + * step + */ +Path TextDecorationInfo::PrepareWavyStrokePath() const { + float wave_offset = DoubleOffset() * line_data_.wavy_offset_factor; + + float control_point_distance = ControlPointDistanceFromResolvedThickness(); + // For spelling and grammar errors we invert the control_point_distance to get + // a result closer to Microsoft Word circa 2021. + if (IsSpellingOrGrammarError()) + control_point_distance = -control_point_distance; + float step = StepFromResolvedThickness(); + + gfx::PointF start_point = StartPoint(); + // We paint the wave before and after the text line (to cover the whole length + // of the line) and then we clip it at + // AppliedDecorationPainter::StrokeWavyTextDecoration(). + // Offset the start point, so the beizer curve starts before the current line, + // that way we can clip it exactly the same way in both ends. + // For spelling and grammar errors we offset an extra half step, to get a + // result closer to Microsoft Word circa 2021. + float start_offset = (IsSpellingOrGrammarError() ? -2.5 : -2) * step; + gfx::PointF p1(start_point + gfx::Vector2dF(start_offset, wave_offset)); + // Increase the width including the previous offset, plus an extra wave to be + // painted after the line. + float extra_width = (IsSpellingOrGrammarError() ? 4.5 : 4) * step; + gfx::PointF p2(start_point + + gfx::Vector2dF(width_ + extra_width, wave_offset)); + + GraphicsContext::AdjustLineToPixelBoundaries(p1, p2, ResolvedThickness()); + + Path path; + path.MoveTo(p1); + + bool is_vertical_line = (p1.x() == p2.x()); + + if (is_vertical_line) { + DCHECK(p1.x() == p2.x()); + + float x_axis = p1.x(); + float y1; + float y2; + + if (p1.y() < p2.y()) { + y1 = p1.y(); + y2 = p2.y(); + } else { + y1 = p2.y(); + y2 = p1.y(); + } + + gfx::PointF control_point1(x_axis + control_point_distance, 0); + gfx::PointF control_point2(x_axis - control_point_distance, 0); + + for (float y = y1; y + 2 * step <= y2;) { + control_point1.set_y(y + step); + control_point2.set_y(y + step); + y += 2 * step; + path.AddBezierCurveTo(control_point1, control_point2, + gfx::PointF(x_axis, y)); + } + } else { + DCHECK(p1.y() == p2.y()); + + float y_axis = p1.y(); + float x1; + float x2; + + if (p1.x() < p2.x()) { + x1 = p1.x(); + x2 = p2.x(); + } else { + x1 = p2.x(); + x2 = p1.x(); + } + + gfx::PointF control_point1(0, y_axis + control_point_distance); + gfx::PointF control_point2(0, y_axis - control_point_distance); + + for (float x = x1; x + 2 * step <= x2;) { + control_point1.set_x(x + step); + control_point2.set_x(x + step); + x += 2 * step; + path.AddBezierCurveTo(control_point1, control_point2, + gfx::PointF(x, y_axis)); + } + } + return path; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/text_decoration_info.h b/third_party/blink/renderer/core/paint/text_decoration_info.h index 58a3b43c..8f6cff8 100644 --- a/third_party/blink/renderer/core/paint/text_decoration_info.h +++ b/third_party/blink/renderer/core/paint/text_decoration_info.h
@@ -6,7 +6,6 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_DECORATION_INFO_H_ #include "base/types/strong_alias.h" -#include "cc/paint/paint_op_buffer.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/geometry/physical_offset.h" @@ -143,10 +142,8 @@ // Compute bounds for the given line and the current decoration. gfx::RectF Bounds() const; - // Returns tile record and coordinates for wavy decorations. - sk_sp<cc::PaintRecord> WavyTileRecord() const; - gfx::RectF WavyPaintRect() const; - gfx::RectF WavyTileRect() const; + // Return a path for current decoration. + absl::optional<Path> StrokePath() const; // Overrides the line color with the given topmost active highlight ‘color’. void SetHighlightOverrideColor(const absl::optional<Color>&); @@ -157,12 +154,14 @@ float ComputeUnderlineThickness( const TextDecorationThickness& applied_decoration_thickness, const ComputedStyle* decorating_box_style) const; - void ComputeWavyLineData(gfx::RectF& pattern_rect, - sk_sp<cc::PaintRecord>& tile_record) const; gfx::RectF BoundsForDottedOrDashed() const; gfx::RectF BoundsForWavy() const; + float WavyDecorationSizing() const; + float ControlPointDistanceFromResolvedThickness() const; + float StepFromResolvedThickness() const; Path PrepareDottedOrDashedStrokePath() const; + Path PrepareWavyStrokePath() const; bool IsSpellingOrGrammarError() const { return line_data_.line == TextDecorationLine::kSpellingError || line_data_.line == TextDecorationLine::kGrammarError; @@ -229,14 +228,8 @@ TextDecorationLine line; float line_offset; float double_offset; - - // Only used for kDotted and kDashed lines. - absl::optional<Path> stroke_path; - - // Only used for kWavy lines. int wavy_offset_factor; - gfx::RectF wavy_pattern_rect; - sk_sp<cc::PaintRecord> wavy_tile_record; + absl::optional<Path> stroke_path; }; LineData line_data_; absl::optional<Color> highlight_override_;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 542e654..73c240c 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -1264,6 +1264,9 @@ } } + if (accessibility_mode.has_mode(ui::AXMode::kScreenReader)) + SerializeScreenReaderAttributes(node_data); + SerializeUnignoredAttributes(node_data, accessibility_mode); if (accessibility_mode.has_mode(ui::AXMode::kPDF)) { @@ -1602,87 +1605,7 @@ node_data, ax::mojom::blink::StringAttribute::kPlaceholder, placeholder); } -// Helper function that searches in the subtree of |obj| to a max -// depth of |max_depth| for an image. -// -// Returns true on success, or false if it finds more than one image, -// or any node with a name, or anything deeper than |max_depth|. -static AXObject* SearchForExactlyOneInnerImage(AXObject* obj, - AXObject* inner_image, - int max_depth) { - // If it's the first image, set |inner_image|. If we already - // found an image, fail. - if (ui::IsImage(obj->RoleValue())) { - if (inner_image) - return nullptr; - inner_image = obj; - } else { - // If we found something else with a name, fail. - if (!ui::IsPlatformDocument(obj->RoleValue()) && - !ui::IsLink(obj->RoleValue())) { - ax::mojom::blink::NameFrom name_from; - HeapVector<Member<AXObject>> name_objects; - String name = obj->GetName(name_from, &name_objects); - - if (!name.StripWhiteSpace().IsEmpty()) - return nullptr; - } - } - - // Fail if we recursed to |max_depth| and there's more of a subtree. - if (max_depth == 0 && obj->ChildCountIncludingIgnored()) - return nullptr; - - // Don't count ignored nodes toward depth. - int next_depth = obj->AccessibilityIsIgnored() ? max_depth : max_depth - 1; - - // Recurse. - for (int i = 0; i < obj->ChildCountIncludingIgnored(); i++) { - inner_image = SearchForExactlyOneInnerImage(obj->ChildAtIncludingIgnored(i), - inner_image, next_depth); - if (!inner_image) - return nullptr; - } - - return inner_image; -} - -// Return true if the subtree of |obj|, to a max depth of 3, contains -// exactly one image. Return that image in |inner_image|. -static AXObject* FindExactlyOneInnerImageInMaxDepthThree( - AXObject& obj, - AXObject* inner_image) { - return SearchForExactlyOneInnerImage(&obj, inner_image, /* max_depth = */ 3); -} - -String AXObject::KeyboardShortcut() const { - const AtomicString& access_key = AccessKey(); - if (access_key.IsNull()) - return String(); - - DEFINE_STATIC_LOCAL(String, modifier_string, ([] { - unsigned modifiers = - KeyboardEventManager::kAccessKeyModifiers; - // Follow the same order as Mozilla MSAA implementation: - // Ctrl+Alt+Shift+Meta+key. MSDN states that keyboard - // shortcut strings should not be localized and defines - // the separator as "+". - StringBuilder modifier_string_builder; - if (modifiers & WebInputEvent::kControlKey) - modifier_string_builder.Append("Ctrl+"); - if (modifiers & WebInputEvent::kAltKey) - modifier_string_builder.Append("Alt+"); - if (modifiers & WebInputEvent::kShiftKey) - modifier_string_builder.Append("Shift+"); - if (modifiers & WebInputEvent::kMetaKey) - modifier_string_builder.Append("Win+"); - return modifier_string_builder.ToString(); - }())); - - return String(modifier_string + access_key); -} - -void AXObject::SerializeOtherScreenReaderAttributes(ui::AXNodeData* node_data) { +void AXObject::SerializeScreenReaderAttributes(ui::AXNodeData* node_data) { String display_style; Node* node = GetNode(); if (node && !node->IsDocumentNode()) { @@ -1714,21 +1637,6 @@ active_descendant->AXObjectID()); } - if (ui::IsImage(node_data->role)) - AXObjectCache().AddImageAnnotations(this, node_data); - - // If a link or web area isn't otherwise labeled and contains exactly one - // image (searching only to a max depth of 2), and the link doesn't have - // accessible text from an attribute like aria-label, then annotate the - // link/web area with the image's annotation, too. - if ((ui::IsLink(node_data->role) || - ui::IsPlatformDocument(node_data->role)) && - node_data->GetNameFrom() != ax::mojom::blink::NameFrom::kAttribute) { - if (AXObject* inner_image = - FindExactlyOneInnerImageInMaxDepthThree(*this, nullptr)) - AXObjectCache().AddImageAnnotations(inner_image, node_data); - } - if (Node* node = GetNode()) { if (node->IsElementNode()) { Element* element = To<Element>(node); @@ -1741,7 +1649,36 @@ } } } +} +String AXObject::KeyboardShortcut() const { + const AtomicString& access_key = AccessKey(); + if (access_key.IsNull()) + return String(); + + DEFINE_STATIC_LOCAL(String, modifier_string, ()); + if (modifier_string.IsNull()) { + unsigned modifiers = KeyboardEventManager::kAccessKeyModifiers; + // Follow the same order as Mozilla MSAA implementation: + // Ctrl+Alt+Shift+Meta+key. MSDN states that keyboard shortcut strings + // should not be localized and defines the separator as "+". + StringBuilder modifier_string_builder; + if (modifiers & WebInputEvent::kControlKey) + modifier_string_builder.Append("Ctrl+"); + if (modifiers & WebInputEvent::kAltKey) + modifier_string_builder.Append("Alt+"); + if (modifiers & WebInputEvent::kShiftKey) + modifier_string_builder.Append("Shift+"); + if (modifiers & WebInputEvent::kMetaKey) + modifier_string_builder.Append("Win+"); + modifier_string = modifier_string_builder.ToString(); + } + + return String(modifier_string + access_key); +} + +void AXObject::SerializeOtherScreenReaderAttributes( + ui::AXNodeData* node_data) const { DCHECK_NE(node_data->role, ax::mojom::blink::Role::kUnknown); DCHECK_NE(node_data->role, ax::mojom::blink::Role::kNone);
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index 561c6b3..61d1b324 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -1417,7 +1417,7 @@ void SerializeLiveRegionAttributes(ui::AXNodeData* node_data) const; void SerializeNameAndDescriptionAttributes(ui::AXMode accessibility_mode, ui::AXNodeData* node_data) const; - void SerializeOtherScreenReaderAttributes(ui::AXNodeData* node_data); + void SerializeOtherScreenReaderAttributes(ui::AXNodeData* node_data) const; void SerializeScreenReaderAttributes(ui::AXNodeData* node_data); void SerializeScrollAttributes(ui::AXNodeData* node_data); void SerializeSparseAttributes(ui::AXNodeData* node_data);
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 b15b1ee..32939ce 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
@@ -3542,16 +3542,6 @@ MarkAXObjectDirtyWithCleanLayoutHelper(obj, true); } -void AXObjectCacheImpl::AddImageAnnotations(AXObject* obj, - ui::AXNodeData* node_data) { - WebLocalFrameImpl* webframe = WebLocalFrameImpl::FromFrame( - obj->GetDocument()->AXObjectCacheOwner().GetFrame()); - if (webframe && webframe->Client()) { - WebAXObject web_object(obj); - webframe->Client()->AddImageAnnotations(web_object, node_data); - } -} - void AXObjectCacheImpl::MarkAXObjectDirty(AXObject* obj) { if (!obj) return;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h index e9c1a4d..1bc7a50a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
@@ -263,8 +263,6 @@ void MarkAXObjectDirtyWithCleanLayout(AXObject*); void MarkAXSubtreeDirtyWithCleanLayout(AXObject*); - void AddImageAnnotations(AXObject*, ui::AXNodeData*); - // Set the parent of |child|. If no parent is possible, this means the child // can no longer be in the AXTree, so remove the child. AXObject* RestoreParentOrPrune(AXObject* child);
diff --git a/third_party/blink/renderer/modules/locks/lock_manager.cc b/third_party/blink/renderer/modules/locks/lock_manager.cc index 028bdff..1d7f5a6 100644 --- a/third_party/blink/renderer/modules/locks/lock_manager.cc +++ b/third_party/blink/renderer/modules/locks/lock_manager.cc
@@ -43,6 +43,7 @@ namespace { constexpr char kRequestAbortedMessage[] = "The request was aborted."; +constexpr char kSecurityErrorMessage[] = "The request was denied."; LockInfo* ToLockInfo(const mojom::blink::LockInfoPtr& record) { LockInfo* info = LockInfo::Create(); @@ -262,8 +263,7 @@ // 5. If origin is an opaque origin, then reject promise with a // "SecurityError" DOMException. - if (!context->GetSecurityOrigin()->CanAccessLocks() || - !AllowLocks(script_state)) { + if (!context->GetSecurityOrigin()->CanAccessLocks()) { exception_state.ThrowSecurityError( "Access to the Locks API is denied in this context."); return ScriptPromise(); @@ -343,20 +343,35 @@ return ScriptPromise(); } - mojom::blink::LockManager::WaitMode wait = - options->steal() ? mojom::blink::LockManager::WaitMode::PREEMPT - : options->ifAvailable() - ? mojom::blink::LockManager::WaitMode::NO_WAIT - : mojom::blink::LockManager::WaitMode::WAIT; - auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); + CheckStorageAccessAllowed( + context, resolver, + WTF::Bind(&LockManager::RequestImpl, WrapWeakPersistent(this), + WrapPersistent(resolver), WrapPersistent(options), name, + WrapPersistent(callback), mode)); + + // 12. Return promise. + return promise; +} + +void LockManager::RequestImpl(ScriptPromiseResolver* resolver, + const LockOptions* options, + const String& name, + V8LockGrantedCallback* callback, + mojom::blink::LockMode mode) { + mojom::blink::LockManager::WaitMode wait = + options->steal() ? mojom::blink::LockManager::WaitMode::PREEMPT + : options->ifAvailable() ? mojom::blink::LockManager::WaitMode::NO_WAIT + : mojom::blink::LockManager::WaitMode::WAIT; + mojo::PendingRemote<mojom::blink::ObservedFeature> lock_lifetime; observer_->Register(lock_lifetime.InitWithNewPipeAndPassReceiver(), mojom::blink::ObservedFeatureType::kWebLock); mojo::PendingAssociatedRemote<mojom::blink::LockRequest> request_remote; + // 11.1. Let request be the result of running the steps to request a lock with // promise, the current agent, environment’s id, origin, callback, name, // options’ mode dictionary member, options’ ifAvailable dictionary member, @@ -377,24 +392,19 @@ WrapWeakPersistent(request), String(kRequestAbortedMessage))); } - service_->RequestLock(name, mode, wait, std::move(request_remote)); - - // 12. Return promise. - return promise; } ScriptPromise LockManager::query(ScriptState* script_state, ExceptionState& exception_state) { // Observed context may be gone if frame is detached. - if (!GetExecutionContext()) + if (!GetExecutionContext()) { return ScriptPromise(); - + } ExecutionContext* context = ExecutionContext::From(script_state); DCHECK(context->IsContextThread()); - if (!context->GetSecurityOrigin()->CanAccessLocks() || - !AllowLocks(script_state)) { + if (!context->GetSecurityOrigin()->CanAccessLocks()) { exception_state.ThrowSecurityError( "Access to the Locks API is denied in this context."); return ScriptPromise(); @@ -417,6 +427,14 @@ auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); + CheckStorageAccessAllowed( + context, resolver, + WTF::Bind(&LockManager::QueryImpl, WrapWeakPersistent(this), + WrapPersistent(resolver))); + return promise; +} + +void LockManager::QueryImpl(ScriptPromiseResolver* resolver) { service_->QueryState(WTF::Bind( [](ScriptPromiseResolver* resolver, Vector<mojom::blink::LockInfoPtr> pending, @@ -427,8 +445,6 @@ resolver->Resolve(snapshot); }, WrapPersistent(resolver))); - - return promise; } void LockManager::AddPendingRequest(LockRequestImpl* request) { @@ -466,36 +482,64 @@ held_locks_.erase(lock); } -bool LockManager::AllowLocks(ScriptState* script_state) { - if (!cached_allowed_.has_value()) { - ExecutionContext* execution_context = ExecutionContext::From(script_state); - DCHECK(execution_context->IsContextThread()); - SECURITY_DCHECK(execution_context->IsWindow() || - execution_context->IsWorkerGlobalScope()); - if (auto* window = DynamicTo<LocalDOMWindow>(execution_context)) { - LocalFrame* frame = window->GetFrame(); - if (!frame) { - cached_allowed_ = false; - } else if (auto* settings_client = frame->GetContentSettingsClient()) { - // This triggers a sync IPC. - cached_allowed_ = settings_client->AllowStorageAccessSync( - WebContentSettingsClient::StorageType::kWebLocks); - } else { - cached_allowed_ = true; - } - } else { - WebContentSettingsClient* content_settings_client = - To<WorkerGlobalScope>(execution_context)->ContentSettingsClient(); - if (!content_settings_client) { - cached_allowed_ = true; - } else { - // This triggers a sync IPC. - cached_allowed_ = content_settings_client->AllowStorageAccessSync( - WebContentSettingsClient::StorageType::kWebLocks); - } - } +void LockManager::CheckStorageAccessAllowed( + ExecutionContext* context, + ScriptPromiseResolver* resolver, + base::OnceCallback<void()> callback) { + DCHECK(context->IsWindow() || context->IsWorkerGlobalScope()); + + auto wrapped_callback = WTF::Bind( + &LockManager::DidCheckStorageAccessAllowed, WrapWeakPersistent(this), + WrapPersistent(resolver), std::move(callback)); + + if (cached_allowed_.has_value()) { + std::move(wrapped_callback).Run(cached_allowed_.value()); + return; } - return cached_allowed_.value(); + + WebContentSettingsClient* content_settings_client = nullptr; + if (auto* window = DynamicTo<LocalDOMWindow>(context)) { + LocalFrame* frame = window->GetFrame(); + if (!frame) { + std::move(wrapped_callback).Run(false); + return; + } + content_settings_client = frame->GetContentSettingsClient(); + } else { + content_settings_client = + To<WorkerGlobalScope>(context)->ContentSettingsClient(); + } + + if (content_settings_client) { + content_settings_client->AllowStorageAccess( + WebContentSettingsClient::StorageType::kWebLocks, + std::move(wrapped_callback)); + return; + } + std::move(wrapped_callback).Run(true); +} + +void LockManager::DidCheckStorageAccessAllowed( + ScriptPromiseResolver* resolver, + base::OnceCallback<void()> callback, + bool allow_access) { + cached_allowed_ = allow_access; + ScriptState* script_state = resolver->GetScriptState(); + + if (!script_state->ContextIsValid()) { + return; + } + + if (allow_access) { + std::move(callback).Run(); + return; + } + + ScriptState::Scope scope(script_state); + + resolver->Reject(V8ThrowDOMException::CreateOrDie( + script_state->GetIsolate(), DOMExceptionCode::kSecurityError, + kSecurityErrorMessage)); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/locks/lock_manager.h b/third_party/blink/renderer/modules/locks/lock_manager.h index 2b9dc0b..89cd817 100644 --- a/third_party/blink/renderer/modules/locks/lock_manager.h +++ b/third_party/blink/renderer/modules/locks/lock_manager.h
@@ -75,10 +75,22 @@ void RemovePendingRequest(LockRequestImpl*); bool IsPendingRequest(LockRequestImpl*); + void QueryImpl(ScriptPromiseResolver* resolver); + void RequestImpl(ScriptPromiseResolver* resolver, + const LockOptions* options, + const String& name, + V8LockGrantedCallback* callback, + mojom::blink::LockMode mode); + // Query the ContentSettingsClient to ensure access is allowed from - // this context. The first call invokes a synchronous IPC call, but - // the result is cached for subsequent accesses. - bool AllowLocks(ScriptState* script_state); + // this context. This invokes an asynchronous IPC call. + // The result is cached for subsequent accesses. + void CheckStorageAccessAllowed(ExecutionContext* context, + ScriptPromiseResolver* resolver, + base::OnceCallback<void()> callback); + void DidCheckStorageAccessAllowed(ScriptPromiseResolver* resolver, + base::OnceCallback<void()> callback, + bool allow_access); HeapHashSet<Member<LockRequestImpl>> pending_requests_; HeapHashSet<Member<Lock>> held_locks_;
diff --git a/third_party/blink/renderer/modules/ml/ml.idl b/third_party/blink/renderer/modules/ml/ml.idl index 4760542..3948e91d 100644 --- a/third_party/blink/renderer/modules/ml/ml.idl +++ b/third_party/blink/renderer/modules/ml/ml.idl
@@ -9,7 +9,7 @@ // https://github.com/webmachinelearning/webnn/blob/main/explainer.md [ - RuntimeEnabled=MachineLearningModelLoader, + RuntimeEnabled=MachineLearningCommon, Exposed=Window ] interface ML { [CallWith=ScriptState, RaisesException]
diff --git a/third_party/blink/renderer/modules/ml/ml_context.idl b/third_party/blink/renderer/modules/ml/ml_context.idl index 02155809..a70a118 100644 --- a/third_party/blink/renderer/modules/ml/ml_context.idl +++ b/third_party/blink/renderer/modules/ml/ml_context.idl
@@ -13,7 +13,7 @@ // a dictionary may be insufficient. [ - RuntimeEnabled=MachineLearningModelLoader, + RuntimeEnabled=MachineLearningCommon, SecureContext, Exposed=Window ] interface MLContext {
diff --git a/third_party/blink/renderer/modules/ml/navigator_ml.idl b/third_party/blink/renderer/modules/ml/navigator_ml.idl index 9060225..8f3c054 100644 --- a/third_party/blink/renderer/modules/ml/navigator_ml.idl +++ b/third_party/blink/renderer/modules/ml/navigator_ml.idl
@@ -11,7 +11,7 @@ [ SecureContext, ImplementedAs=NavigatorML, - RuntimeEnabled=MachineLearningModelLoader + RuntimeEnabled=MachineLearningCommon ] partial interface Navigator { [SameObject] readonly attribute ML ml; };
diff --git a/third_party/blink/renderer/platform/graphics/compositing/pending_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/pending_layer.cc index b91fbc0..ab922f5 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/pending_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/pending_layer.cc
@@ -20,18 +20,6 @@ namespace { -const ClipPaintPropertyNode* HighestOutputClipBetween( - const EffectPaintPropertyNode& ancestor, - const EffectPaintPropertyNode& descendant) { - const ClipPaintPropertyNode* result = nullptr; - for (const auto* effect = &descendant; effect != &ancestor; - effect = effect->UnaliasedParent()) { - if (const auto* output_clip = effect->OutputClip()) - result = &output_clip->Unalias(); - } - return result; -} - // When possible, provides a clip rect that limits the visibility. absl::optional<gfx::RectF> VisibilityLimit(const PropertyTreeState& state) { if (&state.Clip().LocalTransformSpace() == &state.Transform()) @@ -169,16 +157,6 @@ return os << layer.ToJSON()->ToPrettyJSONString().Utf8(); } -gfx::RectF PendingLayer::VisualRectForOverlapTesting( - const PropertyTreeState& ancestor_state) const { - FloatClipRect visual_rect(bounds_); - GeometryMapper::LocalToAncestorVisualRect( - GetPropertyTreeState(), ancestor_state, visual_rect, - kIgnoreOverlayScrollbarSize, kNonInclusiveIntersect, - kExpandVisualRectForCompositingOverlap); - return visual_rect.Rect(); -} - void PendingLayer::Upcast(const PropertyTreeState& new_state) { DCHECK(!ChunkRequiresOwnLayer()); DCHECK_EQ(&new_state.Effect(), @@ -351,31 +329,9 @@ } bool PendingLayer::MightOverlap(const PendingLayer& other) const { - PropertyTreeState common_ancestor_state( - property_tree_state_.Transform() - .LowestCommonAncestor(other.property_tree_state_.Transform()) - .Unalias(), - property_tree_state_.Clip() - .LowestCommonAncestor(other.property_tree_state_.Clip()) - .Unalias(), - property_tree_state_.Effect() - .LowestCommonAncestor(other.property_tree_state_.Effect()) - .Unalias()); - // Move the common clip up if some effect nodes have OutputClip escaping the - // common clip. - if (const auto* clip_a = HighestOutputClipBetween( - common_ancestor_state.Effect(), property_tree_state_.Effect())) { - common_ancestor_state.SetClip( - clip_a->LowestCommonAncestor(common_ancestor_state.Clip()).Unalias()); - } - if (const auto* clip_b = - HighestOutputClipBetween(common_ancestor_state.Effect(), - other.property_tree_state_.Effect())) { - common_ancestor_state.SetClip( - clip_b->LowestCommonAncestor(common_ancestor_state.Clip()).Unalias()); - } - return VisualRectForOverlapTesting(common_ancestor_state) - .Intersects(other.VisualRectForOverlapTesting(common_ancestor_state)); + return GeometryMapper::MightOverlapForCompositing( + bounds_, property_tree_state_.GetPropertyTreeState(), other.bounds_, + other.property_tree_state_.GetPropertyTreeState()); } // Walk the pending layer list and build up a table of transform nodes that
diff --git a/third_party/blink/renderer/platform/graphics/compositing/pending_layer.h b/third_party/blink/renderer/platform/graphics/compositing/pending_layer.h index f9f8ca3..adace2e 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/pending_layer.h +++ b/third_party/blink/renderer/platform/graphics/compositing/pending_layer.h
@@ -156,8 +156,6 @@ PendingLayer(const PaintChunkSubset&, const PaintChunk& first_chunk, wtf_size_t first_chunk_index_in_paint_artifact); - gfx::RectF VisualRectForOverlapTesting( - const PropertyTreeState& ancestor_state) const; gfx::RectF MapRectKnownToBeOpaque(const PropertyTreeState&) const; bool MergeInternal(const PendingLayer& guest, const PropertyTreeState& guest_state,
diff --git a/third_party/blink/renderer/platform/graphics/compositing/pending_layer_test.cc b/third_party/blink/renderer/platform/graphics/compositing/pending_layer_test.cc index c9d965d..e6c6f40 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/pending_layer_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/pending_layer_test.cc
@@ -26,57 +26,6 @@ return indices; } -TEST(PendingLayerTest, MightOverlap) { - TestPaintArtifact artifact; - artifact.Chunk().Bounds(gfx::Rect(0, 0, 100, 100)); - artifact.Chunk().Bounds(gfx::Rect(0, 0, 100, 100)); - auto t2 = CreateTransform(t0(), TransformationMatrix().Translate(99, 0), - gfx::Point3F(100, 100, 0)); - artifact.Chunk(*t2, c0(), e0()).Bounds(gfx::Rect(0, 0, 100, 100)); - auto t3 = CreateTransform(t0(), TransformationMatrix().Translate(100, 0), - gfx::Point3F(100, 100, 0)); - artifact.Chunk(*t3, c0(), e0()).Bounds(gfx::Rect(0, 0, 100, 100)); - auto t4 = - CreateAnimatingTransform(t0(), TransformationMatrix().Translate(100, 0), - gfx::Point3F(100, 100, 0)); - artifact.Chunk(*t4, c0(), e0()).Bounds(gfx::Rect(0, 0, 100, 100)); - PaintChunkSubset chunks(artifact.Build()); - - PendingLayer pending_layer(chunks, chunks.begin()); - EXPECT_TRUE( - pending_layer.MightOverlap(PendingLayer(chunks, chunks.begin() + 1))); - EXPECT_TRUE( - pending_layer.MightOverlap(PendingLayer(chunks, chunks.begin() + 2))); - EXPECT_FALSE( - pending_layer.MightOverlap(PendingLayer(chunks, chunks.begin() + 3))); - EXPECT_TRUE( - pending_layer.MightOverlap(PendingLayer(chunks, chunks.begin() + 4))); -} - -TEST(PendingLayerTest, MightOverlapCommonClipAncestor) { - auto common_clip = CreateClip(c0(), t0(), FloatRoundedRect(0, 0, 100, 100)); - auto c1 = CreateClip(*common_clip, t0(), FloatRoundedRect(0, 100, 100, 100)); - auto c2 = CreateClip(*common_clip, t0(), FloatRoundedRect(50, 100, 100, 100)); - auto c3 = - CreateClip(*common_clip, t0(), FloatRoundedRect(100, 100, 100, 100)); - - TestPaintArtifact artifact; - artifact.Chunk(t0(), *c1, e0()) - .Bounds(gfx::Rect(0, 100, 200, 100)) - .Chunk(t0(), *c2, e0()) - .Bounds(gfx::Rect(0, 100, 200, 100)) - .Chunk(t0(), *c3, e0()) - .Bounds(gfx::Rect(0, 100, 200, 100)); - PaintChunkSubset chunks(artifact.Build()); - - PendingLayer pending_layer1(chunks, chunks.begin()); - PendingLayer pending_layer2(chunks, chunks.begin() + 1); - PendingLayer pending_layer3(chunks, chunks.begin() + 2); - EXPECT_FALSE(pending_layer1.MightOverlap(pending_layer3)); - EXPECT_TRUE(pending_layer1.MightOverlap(pending_layer2)); - EXPECT_TRUE(pending_layer2.MightOverlap(pending_layer3)); -} - TEST(PendingLayerTest, Merge) { TestPaintArtifact artifact; artifact.Chunk()
diff --git a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc index 0965def..cb99b75c 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc
@@ -579,7 +579,7 @@ // Populate the output mailbox and callback. { - bool is_overlay_candidate = !!color_buffer_for_mailbox->gpu_memory_buffer; + bool is_overlay_candidate = color_buffer_for_mailbox->has_usage_scanout; *out_resource = viz::TransferableResource::MakeGL( color_buffer_for_mailbox->mailbox, GL_LINEAR, texture_target_, color_buffer_for_mailbox->produce_sync_token, size_, @@ -826,6 +826,7 @@ const gfx::ColorSpace& color_space, viz::ResourceFormat format, GLuint texture_id, + bool has_usage_scanout, std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer, gpu::Mailbox mailbox) : owning_thread_ref(base::PlatformThread::CurrentRef()), @@ -834,6 +835,7 @@ color_space(color_space), format(format), texture_id(texture_id), + has_usage_scanout(has_usage_scanout), gpu_memory_buffer(std::move(gpu_memory_buffer)), mailbox(mailbox) {} @@ -1828,6 +1830,7 @@ uint32_t usage = gpu::SHARED_IMAGE_USAGE_GLES2 | gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT | gpu::SHARED_IMAGE_USAGE_DISPLAY; + bool has_usage_scanout = false; GrSurfaceOrigin origin = opengl_flip_y_extension_ ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin; @@ -1848,39 +1851,51 @@ front_buffer_mailbox = mailboxes.front_buffer; } else { if (ShouldUseChromiumImage()) { - gfx::BufferFormat buffer_format; - if (allocate_alpha_channel_) { - buffer_format = use_half_float_storage_ ? gfx::BufferFormat::RGBA_F16 - : gfx::BufferFormat::RGBA_8888; - } else { - DCHECK(!use_half_float_storage_); - buffer_format = gfx::BufferFormat::RGBX_8888; + // TODO(https://crbug.com/911176): RGB emulation is only implemented by + // the path that explicitly allocates a GpuMemoryBuffer. It can be removed + // once the validating command decoder is removed (for the passthrough + // command decoder, its implementation is pushed into ANGLE). + // TODO(https://crbug.com/1346737): Low latency canvas on ChromeOS is + // broken in the SharedImage path. + const bool allocate_gmb_explicitly = + (!allocate_alpha_channel_ && have_alpha_channel_) || + low_latency_enabled(); + if (allocate_gmb_explicitly) { + gfx::BufferFormat buffer_format = gfx::BufferFormat::RGBX_8888; if (gpu::IsImageFromGpuMemoryBufferFormatSupported( gfx::BufferFormat::BGRX_8888, ContextProvider()->GetCapabilities())) { buffer_format = gfx::BufferFormat::BGRX_8888; } - } - // TODO(crbug.com/911176): When RGB emulation is not needed, we should use - // the non-GMB CreateSharedImage with gpu::SHARED_IMAGE_USAGE_SCANOUT in - // order to allocate the GMB service-side and avoid a synchronous - // round-trip to the browser process here. - gfx::BufferUsage buffer_usage = gfx::BufferUsage::SCANOUT; - uint32_t additional_usage_flags = gpu::SHARED_IMAGE_USAGE_SCANOUT; - if (low_latency_enabled()) { - buffer_usage = gfx::BufferUsage::SCANOUT_FRONT_RENDERING; - additional_usage_flags = gpu::SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE; - } - - if (gpu::IsImageFromGpuMemoryBufferFormatSupported( - buffer_format, ContextProvider()->GetCapabilities())) { - gpu_memory_buffer = gpu_memory_buffer_manager->CreateGpuMemoryBuffer( - size, buffer_format, buffer_usage, gpu::kNullSurfaceHandle, - nullptr); - if (gpu_memory_buffer) { - back_buffer_mailbox = sii->CreateSharedImage( - gpu_memory_buffer.get(), gpu_memory_buffer_manager, color_space_, - origin, kPremul_SkAlphaType, usage | additional_usage_flags); + gfx::BufferUsage buffer_usage = gfx::BufferUsage::SCANOUT; + uint32_t additional_usage_flags = gpu::SHARED_IMAGE_USAGE_SCANOUT; + if (low_latency_enabled()) { + buffer_usage = gfx::BufferUsage::SCANOUT_FRONT_RENDERING; + additional_usage_flags = + gpu::SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE; + } + if (gpu::IsImageFromGpuMemoryBufferFormatSupported( + buffer_format, ContextProvider()->GetCapabilities())) { + gpu_memory_buffer = gpu_memory_buffer_manager->CreateGpuMemoryBuffer( + size, buffer_format, buffer_usage, gpu::kNullSurfaceHandle, + nullptr); + if (gpu_memory_buffer) { + has_usage_scanout = true; + back_buffer_mailbox = sii->CreateSharedImage( + gpu_memory_buffer.get(), gpu_memory_buffer_manager, + color_space_, origin, kPremul_SkAlphaType, + usage | additional_usage_flags); + } + } + } else { + if (gpu::IsImageFromGpuMemoryBufferFormatSupported( + viz::BufferFormat(format), + ContextProvider()->GetCapabilities())) { + usage |= gpu::SHARED_IMAGE_USAGE_SCANOUT; + has_usage_scanout = true; + if (low_latency_enabled()) { + usage |= gpu::SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE; + } } } } @@ -1911,7 +1926,7 @@ front_buffer_mailbox.name); front_color_buffer_ = base::MakeRefCounted<ColorBuffer>( weak_factory_.GetWeakPtr(), size, color_space_, format, texture_id, - nullptr, front_buffer_mailbox); + /*has_usage_scanout=*/false, nullptr, front_buffer_mailbox); } // Import the backbuffer of swap chain or allocated SharedImage into GL. texture_id = @@ -1940,7 +1955,7 @@ return base::MakeRefCounted<ColorBuffer>( weak_factory_.GetWeakPtr(), size, color_space_, format, texture_id, - std::move(gpu_memory_buffer), back_buffer_mailbox); + has_usage_scanout, std::move(gpu_memory_buffer), back_buffer_mailbox); } void DrawingBuffer::AttachColorBufferToReadFramebuffer() {
diff --git a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h index f4e6c8d..890b0f10 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h +++ b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.h
@@ -414,6 +414,7 @@ const gfx::ColorSpace& color_space, viz::ResourceFormat, GLuint texture_id, + bool has_usage_scanout, std::unique_ptr<gfx::GpuMemoryBuffer>, gpu::Mailbox mailbox); ColorBuffer(const ColorBuffer&) = delete; @@ -432,6 +433,7 @@ const gfx::ColorSpace color_space; const viz::ResourceFormat format; const GLuint texture_id = 0; + const bool has_usage_scanout; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer; // If we're emulating an RGB back buffer using an RGBA Chromium
diff --git a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc index 300a7a6..c154bc84 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc
@@ -510,71 +510,6 @@ EXPECT_EQ(0u, sii->shared_image_count()); } -TEST_F(DrawingBufferImageChromiumTest, AllocationFailure) { - GLES2InterfaceForTests* gl_ = drawing_buffer_->ContextGLForTests(); - viz::TestGpuMemoryBufferManager* gmb_manager = - static_cast<viz::TestGpuMemoryBufferManager*>( - Platform::Current()->GetGpuMemoryBufferManager()); - viz::TestSharedImageInterface* sii = - drawing_buffer_->SharedImageInterfaceForTests(); - - viz::TransferableResource resource1; - viz::ReleaseCallback release_callback1; - viz::TransferableResource resource2; - viz::ReleaseCallback release_callback2; - viz::TransferableResource resource3; - viz::ReleaseCallback release_callback3; - - // Request a resource. A SharedImage should already be created. Everything - // works as expected. - EXPECT_CALL(*gl_, CreateAndTexStorage2DSharedImageCHROMIUMMock(_)).Times(1); - EXPECT_FALSE(drawing_buffer_->MarkContentsChanged()); - EXPECT_TRUE(drawing_buffer_->PrepareTransferableResource(nullptr, &resource1, - &release_callback1)); - EXPECT_TRUE(resource1.is_overlay_candidate); - gpu::Mailbox mailbox1; - mailbox1.SetName(gl_->last_imported_shared_image()->name); - EXPECT_TRUE(sii->CheckSharedImageExists(mailbox1)); - testing::Mock::VerifyAndClearExpectations(gl_); - VerifyStateWasRestored(); - - // Force GpuMemoryBuffer creation failure. Request another resource. It should - // still be provided, but this time with allowOverlay = false. - EXPECT_CALL(*gl_, CreateAndTexStorage2DSharedImageCHROMIUMMock(_)).Times(1); - gmb_manager->SetFailOnCreate(true); - EXPECT_TRUE(drawing_buffer_->MarkContentsChanged()); - EXPECT_TRUE(drawing_buffer_->PrepareTransferableResource(nullptr, &resource2, - &release_callback2)); - EXPECT_FALSE(resource2.is_overlay_candidate); - gpu::Mailbox mailbox2; - mailbox2.SetName(gl_->last_imported_shared_image()->name); - EXPECT_TRUE(sii->CheckSharedImageExists(mailbox2)); - VerifyStateWasRestored(); - - // Check that if GpuMemoryBuffer allocation starts working again, resources - // are correctly created with allowOverlay = true. - EXPECT_CALL(*gl_, CreateAndTexStorage2DSharedImageCHROMIUMMock(_)).Times(1); - gmb_manager->SetFailOnCreate(false); - EXPECT_TRUE(drawing_buffer_->MarkContentsChanged()); - EXPECT_TRUE(drawing_buffer_->PrepareTransferableResource(nullptr, &resource3, - &release_callback3)); - EXPECT_TRUE(resource3.is_overlay_candidate); - gpu::Mailbox mailbox3; - mailbox3.SetName(gl_->last_imported_shared_image()->name); - EXPECT_TRUE(sii->CheckSharedImageExists(mailbox3)); - testing::Mock::VerifyAndClearExpectations(gl_); - VerifyStateWasRestored(); - - std::move(release_callback1).Run(gpu::SyncToken(), false /* lostResource */); - std::move(release_callback2).Run(gpu::SyncToken(), false /* lostResource */); - std::move(release_callback3).Run(gpu::SyncToken(), false /* lostResource */); - - drawing_buffer_->BeginDestruction(); - EXPECT_FALSE(sii->CheckSharedImageExists(mailbox1)); - EXPECT_FALSE(sii->CheckSharedImageExists(mailbox2)); - EXPECT_FALSE(sii->CheckSharedImageExists(mailbox3)); -} - class DepthStencilTrackingGLES2Interface : public gpu::gles2::GLES2InterfaceStub { public:
diff --git a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc index 520f9ba7..4f5983d8 100644 --- a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc +++ b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc
@@ -194,23 +194,22 @@ const PropertyTreeState& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior clip_behavior, - InclusiveIntersectOrNot inclusive_behavior, - ExpandVisualRectForCompositingOverlapOrNot expand) { + InclusiveIntersectOrNot inclusive_behavior) { bool success = false; - bool result = LocalToAncestorVisualRectInternal( + bool result = LocalToAncestorVisualRectInternal<ForCompositingOverlap::kNo>( local_state, ancestor_state, mapping_rect, clip_behavior, - inclusive_behavior, expand, success); + inclusive_behavior, success); DCHECK(success); return result; } +template <GeometryMapper::ForCompositingOverlap for_compositing_overlap> bool GeometryMapper::LocalToAncestorVisualRectInternal( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state, FloatClipRect& rect_to_map, OverlayScrollbarClipBehavior clip_behavior, InclusiveIntersectOrNot inclusive_behavior, - ExpandVisualRectForCompositingOverlapOrNot expand, bool& success) { if (local_state == ancestor_state) { success = true; @@ -218,9 +217,9 @@ } if (&local_state.Effect() != &ancestor_state.Effect()) { - return SlowLocalToAncestorVisualRectWithEffects( + return SlowLocalToAncestorVisualRectWithEffects<for_compositing_overlap>( local_state, ancestor_state, rect_to_map, clip_behavior, - inclusive_behavior, expand, success); + inclusive_behavior, success); } ExtraProjectionResult extra_result; @@ -244,8 +243,8 @@ return false; } - if ((extra_result.has_animation || extra_result.has_sticky) && - expand == kExpandVisualRectForCompositingOverlap) { + if (for_compositing_overlap == ForCompositingOverlap::kYes && + (extra_result.has_animation || extra_result.has_sticky)) { // Assume during the animation or the sticky translation can map // |rect_to_map| to anywhere during animation or composited scroll. // Ancestor clips will still apply. @@ -254,8 +253,8 @@ rect_to_map = InfiniteLooseFloatClipRect(); } else { translation_2d_or_matrix.MapFloatClipRect(rect_to_map); - if (extra_result.has_fixed && - expand == kExpandVisualRectForCompositingOverlap) { + if (for_compositing_overlap == ForCompositingOverlap::kYes && + extra_result.has_fixed) { ExpandFixedBoundsInScroller(&local_state.Transform(), &ancestor_state.Transform(), rect_to_map); // This early return skips the clipping below because the expansion for @@ -265,9 +264,10 @@ } } - FloatClipRect clip_rect = LocalToAncestorClipRectInternal( - local_state.Clip(), ancestor_state.Clip(), ancestor_state.Transform(), - clip_behavior, inclusive_behavior, expand, success); + FloatClipRect clip_rect = + LocalToAncestorClipRectInternal<for_compositing_overlap>( + local_state.Clip(), ancestor_state.Clip(), ancestor_state.Transform(), + clip_behavior, inclusive_behavior, success); if (success) { // This is where we propagate the roundedness and tightness of |clip_rect| // to |rect_to_map|. @@ -287,13 +287,13 @@ return !rect_to_map.Rect().IsEmpty(); } +template <GeometryMapper::ForCompositingOverlap for_compositing_overlap> bool GeometryMapper::SlowLocalToAncestorVisualRectWithEffects( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior clip_behavior, InclusiveIntersectOrNot inclusive_behavior, - ExpandVisualRectForCompositingOverlapOrNot expand, bool& success) { PropertyTreeState last_transform_and_clip_state( local_state.Transform(), local_state.Clip(), @@ -303,8 +303,8 @@ for (const auto* effect = &local_state.Effect(); effect && effect != &ancestor_effect; effect = effect->UnaliasedParent()) { - if (effect->HasActiveFilterAnimation() && - expand == kExpandVisualRectForCompositingOverlap) { + if (for_compositing_overlap == ForCompositingOverlap::kYes && + effect->HasActiveFilterAnimation()) { // Assume during the animation the filter can map |rect_to_map| to // anywhere. Ancestor clips will still apply. // TODO(crbug.com/1026653): Use animation bounds instead of infinite rect. @@ -321,9 +321,10 @@ PropertyTreeState transform_and_clip_state( effect->LocalTransformSpace().Unalias(), effect->OutputClip()->Unalias(), EffectPaintPropertyNode::Root()); - bool intersects = LocalToAncestorVisualRectInternal( - last_transform_and_clip_state, transform_and_clip_state, mapping_rect, - clip_behavior, inclusive_behavior, expand, success); + bool intersects = + LocalToAncestorVisualRectInternal<for_compositing_overlap>( + last_transform_and_clip_state, transform_and_clip_state, + mapping_rect, clip_behavior, inclusive_behavior, success); if (!success || !intersects) { success = true; mapping_rect = FloatClipRect(gfx::RectF()); @@ -337,9 +338,9 @@ PropertyTreeState final_transform_and_clip_state( ancestor_state.Transform(), ancestor_state.Clip(), EffectPaintPropertyNode::Root()); - bool intersects = LocalToAncestorVisualRectInternal( + bool intersects = LocalToAncestorVisualRectInternal<for_compositing_overlap>( last_transform_and_clip_state, final_transform_and_clip_state, - mapping_rect, clip_behavior, inclusive_behavior, expand, success); + mapping_rect, clip_behavior, inclusive_behavior, success); // Many effects (e.g. filters, clip-paths) can make a clip rect not tight. mapping_rect.ClearIsTight(); @@ -356,10 +357,9 @@ return FloatClipRect(); bool success = false; - auto result = LocalToAncestorClipRectInternal( + auto result = LocalToAncestorClipRectInternal<ForCompositingOverlap::kNo>( local_clip, ancestor_clip, ancestor_state.Transform(), clip_behavior, - kNonInclusiveIntersect, kDontExpandVisualRectForCompositingOverlap, - success); + kNonInclusiveIntersect, success); DCHECK(success); // Many effects (e.g. filters, clip-paths) can make a clip rect not tight. @@ -382,13 +382,13 @@ return clip_rect; } +template <GeometryMapper::ForCompositingOverlap for_compositing_overlap> FloatClipRect GeometryMapper::LocalToAncestorClipRectInternal( const ClipPaintPropertyNode& descendant_clip, const ClipPaintPropertyNode& ancestor_clip, const TransformPaintPropertyNode& ancestor_transform, OverlayScrollbarClipBehavior clip_behavior, InclusiveIntersectOrNot inclusive_behavior, - ExpandVisualRectForCompositingOverlapOrNot expand, bool& success) { if (&descendant_clip == &ancestor_clip) { success = true; @@ -414,10 +414,9 @@ if (inclusive_behavior != kInclusiveIntersect) cached_clip = clip_node->GetClipCache().GetCachedClip(clip_and_transform); - if (cached_clip && + if (for_compositing_overlap == ForCompositingOverlap::kYes && cached_clip && (cached_clip->has_transform_animation || - cached_clip->has_sticky_transform) && - expand == kExpandVisualRectForCompositingOverlap) { + cached_clip->has_sticky_transform)) { // Don't use cached clip if it's transformed by any animating transform // or sticky translation. cached_clip = nullptr; @@ -454,8 +453,8 @@ return FloatClipRect(gfx::RectF()); } - if ((extra_result.has_animation || extra_result.has_sticky) && - expand == kExpandVisualRectForCompositingOverlap) + if (for_compositing_overlap == ForCompositingOverlap::kYes && + (extra_result.has_animation || extra_result.has_sticky)) continue; // This is where we generate the roundedness and tightness of clip rect @@ -476,7 +475,7 @@ // Clips that are inclusive intersected or expanded for animation are not // cached at present. DCHECK(inclusive_behavior == kInclusiveIntersect || - expand == kExpandVisualRectForCompositingOverlap || + for_compositing_overlap == ForCompositingOverlap::kYes || descendant_clip.GetClipCache() .GetCachedClip(clip_and_transform) ->clip_rect == clip); @@ -484,6 +483,81 @@ return clip; } +bool GeometryMapper::MightOverlapForCompositing( + const gfx::RectF& rect1, + const PropertyTreeState& state1, + const gfx::RectF& rect2, + const PropertyTreeState& state2) { + PropertyTreeState common_ancestor( + state1.Transform().LowestCommonAncestor(state2.Transform()).Unalias(), + state1.Clip().LowestCommonAncestor(state2.Clip()).Unalias(), + state1.Effect().LowestCommonAncestor(state2.Effect()).Unalias()); + // Move the common clip up if some effect nodes have OutputClip escaping the + // common clip. + if (const auto* clip_a = + HighestOutputClipBetween(common_ancestor.Effect(), state1.Effect())) { + common_ancestor.SetClip( + clip_a->LowestCommonAncestor(common_ancestor.Clip()).Unalias()); + } + if (const auto* clip_b = + HighestOutputClipBetween(common_ancestor.Effect(), state2.Effect())) { + common_ancestor.SetClip( + clip_b->LowestCommonAncestor(common_ancestor.Clip()).Unalias()); + } + return VisualRectForCompositingOverlap(rect1, state1, common_ancestor) + .Intersects( + VisualRectForCompositingOverlap(rect2, state2, common_ancestor)); +} + +const ClipPaintPropertyNode* GeometryMapper::HighestOutputClipBetween( + const EffectPaintPropertyNode& ancestor, + const EffectPaintPropertyNode& descendant) { + const ClipPaintPropertyNode* result = nullptr; + for (const auto* effect = &descendant; effect != &ancestor; + effect = effect->UnaliasedParent()) { + if (const auto* output_clip = effect->OutputClip()) + result = &output_clip->Unalias(); + } + return result; +} + +gfx::RectF GeometryMapper::VisualRectForCompositingOverlap( + const gfx::RectF& local_rect, + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state) { + FloatClipRect visual_rect(local_rect); + bool success = false; + GeometryMapper::LocalToAncestorVisualRectInternal< + ForCompositingOverlap::kYes>(local_state, ancestor_state, visual_rect, + kIgnoreOverlayScrollbarSize, + kNonInclusiveIntersect, success); + DCHECK(success); + return visual_rect.Rect(); +} + +bool GeometryMapper::LocalToAncestorVisualRectInternalForTesting( + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state, + FloatClipRect& mapping_rect, + bool& success) { + return GeometryMapper::LocalToAncestorVisualRectInternal< + ForCompositingOverlap::kNo>(local_state, ancestor_state, mapping_rect, + kIgnoreOverlayScrollbarSize, + kNonInclusiveIntersect, success); +} + +bool GeometryMapper:: + LocalToAncestorVisualRectInternalForCompositingOverlapForTesting( + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state, + FloatClipRect& mapping_rect, + bool& success) { + return GeometryMapper::LocalToAncestorVisualRectInternal< + ForCompositingOverlap::kYes>(local_state, ancestor_state, mapping_rect, + kIgnoreOverlayScrollbarSize, + kNonInclusiveIntersect, success); +} + void GeometryMapper::ClearCache() { GeometryMapperTransformCache::ClearCache(); GeometryMapperClipCache::ClearCache();
diff --git a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h index ef2a8ec..6150b69 100644 --- a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h +++ b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h
@@ -22,29 +22,6 @@ // Clips can use gfx::RectF::Intersect or gfx::RectF::InclusiveIntersect. enum InclusiveIntersectOrNot { kNonInclusiveIntersect, kInclusiveIntersect }; -// When performing overlap testing during compositing, we may need to expand the -// visual rect in two cases when mapping from descendant state to ancestor -// state: mapping through a fixed transform node to the viewport it is attached -// to, and mapping through an animating transform or filter. -// -// This allows for a more conservative overlap test that assumes potentially -// more overlap than we'd encounter otherwise, in order to reduce the need to -// re-run overlap testing in response to things like scrolling. -// -// The expansion for fixed covers all coordinates where the fixed content may -// end up when the scroller is at the end of the extents. -// -// For animation, the visual or clip rect is expanded to infinity when we meet -// any animating transform or filter when walking from a descendant state to an -// ancestor state, when mapping a visual rect or getting the accumulated clip -// rect. After we expanded the rect, we will still apply ancestor clips when -// continuing walking up the tree. TODO(crbug.com/1026653): Consider animation -// bounds instead of using infinite rect. -enum ExpandVisualRectForCompositingOverlapOrNot { - kDontExpandVisualRectForCompositingOverlap, - kExpandVisualRectForCompositingOverlap, -}; - // GeometryMapper is a helper class for fast computations of transformed and // visual rects in different PropertyTreeStates. The design document has a // number of details on use cases, algorithmic definitions, and running times. @@ -251,21 +228,22 @@ const PropertyTreeStateOrAlias& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior clip = kIgnoreOverlayScrollbarSize, - InclusiveIntersectOrNot intersect = kNonInclusiveIntersect, - ExpandVisualRectForCompositingOverlapOrNot expand = - kDontExpandVisualRectForCompositingOverlap) { + InclusiveIntersectOrNot intersect = kNonInclusiveIntersect) { return LocalToAncestorVisualRect(local_state.Unalias(), ancestor_state.Unalias(), mapping_rect, - clip, intersect, expand); + clip, intersect); } static bool LocalToAncestorVisualRect( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior = kIgnoreOverlayScrollbarSize, - InclusiveIntersectOrNot = kNonInclusiveIntersect, - ExpandVisualRectForCompositingOverlapOrNot = - kDontExpandVisualRectForCompositingOverlap); + InclusiveIntersectOrNot = kNonInclusiveIntersect); + + static bool MightOverlapForCompositing(const gfx::RectF& rect1, + const PropertyTreeState& state1, + const gfx::RectF& rect2, + const PropertyTreeState& state2); static void ClearCache(); @@ -287,37 +265,48 @@ ExtraProjectionResult&, bool& success); + enum class ForCompositingOverlap { kNo, kYes }; + + template <ForCompositingOverlap> static FloatClipRect LocalToAncestorClipRectInternal( const ClipPaintPropertyNode& descendant, const ClipPaintPropertyNode& ancestor_clip, const TransformPaintPropertyNode& ancestor_transform, OverlayScrollbarClipBehavior, InclusiveIntersectOrNot, - ExpandVisualRectForCompositingOverlapOrNot, bool& success); // The return value has the same meaning as that for // LocalToAncestorVisualRect. + template <ForCompositingOverlap> static bool LocalToAncestorVisualRectInternal( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior, InclusiveIntersectOrNot, - ExpandVisualRectForCompositingOverlapOrNot, bool& success); // The return value has the same meaning as that for // LocalToAncestorVisualRect. + template <ForCompositingOverlap> static bool SlowLocalToAncestorVisualRectWithEffects( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state, FloatClipRect& mapping_rect, OverlayScrollbarClipBehavior, InclusiveIntersectOrNot, - ExpandVisualRectForCompositingOverlapOrNot, bool& success); + static const ClipPaintPropertyNode* HighestOutputClipBetween( + const EffectPaintPropertyNode& ancestor, + const EffectPaintPropertyNode& descendant); + + static gfx::RectF VisualRectForCompositingOverlap( + const gfx::RectF& local_rect, + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state); + static void MoveRect(gfx::RectF& rect, const gfx::Vector2dF& delta) { rect.Offset(delta.x(), delta.y()); } @@ -333,7 +322,16 @@ } friend class GeometryMapperTest; - friend class PaintLayerClipperTest; + static bool LocalToAncestorVisualRectInternalForTesting( + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state, + FloatClipRect& mapping_rect, + bool& success); + static bool LocalToAncestorVisualRectInternalForCompositingOverlapForTesting( + const PropertyTreeState& local_state, + const PropertyTreeState& ancestor_state, + FloatClipRect& mapping_rect, + bool& success); }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc index 20b066b..6a790b43 100644 --- a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc +++ b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc
@@ -29,14 +29,23 @@ } void LocalToAncestorVisualRectInternal( - const PropertyTreeState& internal_local_state, - const PropertyTreeState& internal_ancestor_state, + const PropertyTreeStateOrAlias& local_state, + const PropertyTreeStateOrAlias& ancestor_state, FloatClipRect& mapping_rect, bool& success) { - GeometryMapper::LocalToAncestorVisualRectInternal( - internal_local_state, internal_ancestor_state, mapping_rect, - kIgnoreOverlayScrollbarSize, kNonInclusiveIntersect, - kDontExpandVisualRectForCompositingOverlap, success); + GeometryMapper::LocalToAncestorVisualRectInternalForTesting( + local_state.Unalias(), ancestor_state.Unalias(), mapping_rect, success); + } + + void LocalToAncestorVisualRectForCompositingOverlap( + const PropertyTreeStateOrAlias& local_state, + const PropertyTreeStateOrAlias& ancestor_state, + FloatClipRect& mapping_rect, + bool& success) { + GeometryMapper:: + LocalToAncestorVisualRectInternalForCompositingOverlapForTesting( + local_state.Unalias(), ancestor_state.Unalias(), mapping_rect, + success); } void CheckMappings(); @@ -75,15 +84,17 @@ void GeometryMapperTest::CheckLocalToAncestorVisualRect() { FloatClipRect actual_visual_rect(input_rect); - GeometryMapper::LocalToAncestorVisualRect(local_state, ancestor_state, - actual_visual_rect); + bool success = false; + LocalToAncestorVisualRectInternal(local_state, ancestor_state, + actual_visual_rect, success); + DCHECK(success); EXPECT_CLIP_RECT_EQ(expected_visual_rect, actual_visual_rect); actual_visual_rect = FloatClipRect(input_rect); - GeometryMapper::LocalToAncestorVisualRect( - local_state, ancestor_state, actual_visual_rect, - kIgnoreOverlayScrollbarSize, kNonInclusiveIntersect, - kExpandVisualRectForCompositingOverlap); + success = false; + LocalToAncestorVisualRectForCompositingOverlap(local_state, ancestor_state, + actual_visual_rect, success); + DCHECK(success); EXPECT_CLIP_RECT_EQ(expected_visual_rect_expanded_for_compositing ? *expected_visual_rect_expanded_for_compositing : expected_visual_rect, @@ -1034,4 +1045,47 @@ GeometryMapper::SourceToDestinationProjection(*t2, *t3).IsIdentity()); } +TEST(GeometryMapperTest, VisualRectsMightOverlap) { + auto t2 = Create2DTranslation(t0(), 99, 0); + auto t3 = Create2DTranslation(t0(), 100, 0); + auto t4 = + CreateAnimatingTransform(t0(), TransformationMatrix().Translate(100, 0)); + + gfx::RectF r(0, 0, 100, 100); + PropertyTreeState s1 = PropertyTreeState::Root(); + PropertyTreeState s2(*t2, c0(), e0()); + PropertyTreeState s3(*t3, c0(), e0()); + PropertyTreeState s4(*t4, c0(), e0()); + + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s1)); + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s2)); + EXPECT_FALSE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s3)); + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s4)); + + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s2, r, s1)); + EXPECT_FALSE(GeometryMapper::MightOverlapForCompositing(r, s3, r, s1)); + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s4, r, s1)); +} + +TEST(GeometryMapperTest, VisualRectsMightOverlapCommonClipAncestor) { + auto common_clip = CreateClip(c0(), t0(), FloatRoundedRect(0, 0, 1, 1)); + auto c1 = CreateClip(*common_clip, t0(), FloatRoundedRect(0, 100, 100, 100)); + auto c2 = CreateClip(*common_clip, t0(), FloatRoundedRect(50, 100, 100, 100)); + auto c3 = + CreateClip(*common_clip, t0(), FloatRoundedRect(100, 100, 100, 100)); + + gfx::RectF r(0, 100, 200, 100); + PropertyTreeState s1(t0(), *c1, e0()); + PropertyTreeState s2(t0(), *c2, e0()); + PropertyTreeState s3(t0(), *c3, e0()); + + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s2)); + EXPECT_FALSE(GeometryMapper::MightOverlapForCompositing(r, s1, r, s3)); + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s2, r, s3)); + + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s2, r, s1)); + EXPECT_FALSE(GeometryMapper::MightOverlapForCompositing(r, s3, r, s1)); + EXPECT_TRUE(GeometryMapper::MightOverlapForCompositing(r, s3, r, s2)); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.cc b/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.cc index a2d0a4d..40741cf 100644 --- a/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.cc +++ b/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.cc
@@ -33,7 +33,6 @@ scroll != other.scroll || scroll_translation_for_fixed != other.scroll_translation_for_fixed || !base::ValuesEquivalent(sticky_constraint, other.sticky_constraint) || - anchor_scroll_container != other.anchor_scroll_container || visible_frame_element_id != other.visible_frame_element_id) { return PaintPropertyChangeType::kChangedOnlyValues; }
diff --git a/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h b/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h index 24079a8..328b1c59 100644 --- a/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h +++ b/third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h
@@ -181,10 +181,6 @@ CompositingReasons direct_compositing_reasons = CompositingReason::kNone; CompositorElementId compositor_element_id; std::unique_ptr<CompositorStickyConstraint> sticky_constraint; - // Scroll container of the element specified by the 'anchor-scroll' - // property, if this element uses anchor positioning and is not in the same - // scroll container. - scoped_refptr<const TransformPaintPropertyNode> anchor_scroll_container; // If a visible frame is rooted at this node, this represents the element // ID of the containing document. CompositorElementId visible_frame_element_id; @@ -272,10 +268,6 @@ return state_.sticky_constraint.get(); } - const TransformPaintPropertyNode* GetAnchorScrollContainer() const { - return state_.anchor_scroll_container.get(); - } - // If this is a scroll offset translation (i.e., has an associated scroll // node), returns this. Otherwise, returns the transform node that this node // scrolls with respect to.
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 8694f59d..f50deea 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1115,7 +1115,7 @@ }, { name: "ForcedColorsPreserveParentColor", - depends_on: ["ForcedColors"], + status: "stable", }, { // This is used in tests to perform memory measurement without @@ -1357,6 +1357,11 @@ // Enabled by features::kLegacyWindowsDWriteFontFallback; }, { + name: "MachineLearningCommon", + implied_by: ["MachineLearningModelLoader", "MachineLearningNeuralNetwork"], + status: "experimental", + }, + { name: "MachineLearningModelLoader", status: "experimental", },
diff --git a/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.cc b/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.cc index d816db6..dc53ac38 100644 --- a/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.cc +++ b/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.cc
@@ -254,9 +254,12 @@ #endif } -void WidgetInputHandlerManager::DidFirstVisuallyNonEmptyPaint() { +void WidgetInputHandlerManager::DidFirstVisuallyNonEmptyPaint( + const base::TimeTicks& first_paint_time) { suppressing_input_events_state_ &= ~static_cast<uint16_t>(SuppressingInputEventsBits::kHasNotPainted); + + RecordMetricsForDroppedEventsBeforePaint(first_paint_time); } void WidgetInputHandlerManager::InitInputHandler() { @@ -473,15 +476,33 @@ if (suppressing_input_events_state_ & (unsigned)SuppressingInputEventsBits::kDeferCommits) { lifecycle_state = InitialInputTiming::kBeforeCommit; + } else if (suppressing_input_events_state_ & + (unsigned)SuppressingInputEventsBits::kHasNotPainted) { + lifecycle_state = InitialInputTiming::kBeforeFirstPaint; } else { - lifecycle_state = InitialInputTiming::kAfterCommit; + lifecycle_state = InitialInputTiming::kAfterFirstPaint; } } - UMA_HISTOGRAM_ENUMERATION("PaintHolding.InputTiming2", lifecycle_state); + UMA_HISTOGRAM_ENUMERATION("PaintHolding.InputTiming3", lifecycle_state); have_emitted_uma_ = true; } } +void WidgetInputHandlerManager::RecordMetricsForDroppedEventsBeforePaint( + const base::TimeTicks& first_paint_time) { + // Initialize to 0 timestamp and log 0 if there was no suppressed event or the + // most recent suppressed event was before the first_paint_time + auto diff = base::TimeDelta(); + if (most_recent_suppressed_event_time_ > first_paint_time) { + diff = most_recent_suppressed_event_time_ - first_paint_time; + } + UMA_HISTOGRAM_TIMES("PageLoad.Internal.SuppressedEventsTimingBeforePaint", + diff); + + UMA_HISTOGRAM_COUNTS("PageLoad.Internal.SuppressedEventsCountBeforePaint", + suppressed_events_count_); +} + void WidgetInputHandlerManager::DispatchScrollGestureToCompositor( std::unique_ptr<WebGestureEvent> event) { DCHECK(base::FeatureList::IsEnabled(::features::kScrollUnification)); @@ -518,9 +539,18 @@ bool event_is_move = event->Event().GetType() == WebInputEvent::Type::kMouseMove || event->Event().GetType() == WebInputEvent::Type::kPointerMove; - if (!event_is_move) + if (!event_is_move) { LogInputTimingUMA(); + // We only count it if the only reason we are suppressing is because we + // haven't painted yet. + if (suppressing_input_events_state_ == + static_cast<uint16_t>(SuppressingInputEventsBits::kHasNotPainted)) { + most_recent_suppressed_event_time_ = base::TimeTicks::Now(); + suppressed_events_count_ += 1; + } + } + // Drop input if we are deferring a rendering pipeline phase, unless it's a // move event, or we are waiting for first visually non empty paint. // We don't want users interacting with stuff they can't see, so we drop it. @@ -690,6 +720,8 @@ suppressing_input_events_state_ = static_cast<uint16_t>(SuppressingInputEventsBits::kHasNotPainted); have_emitted_uma_ = false; + most_recent_suppressed_event_time_ = base::TimeTicks(); + suppressed_events_count_ = 0; } void WidgetInputHandlerManager::OnDeferMainFrameUpdatesChanged(bool status) {
diff --git a/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h b/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h index 4c41d2e..fb05d1c 100644 --- a/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h +++ b/third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h
@@ -55,9 +55,11 @@ kBeforeLifecycle = 0, // Input is before commit kBeforeCommit = 1, - // Input comes only after commit - kAfterCommit = 2, - kMaxValue = kAfterCommit + // Input comes before first paint + kBeforeFirstPaint = 2, + // Input comes only after first paint + kAfterFirstPaint = 3, + kMaxValue = kAfterFirstPaint }; // For use in bitfields to keep track of why we should keep suppressing input @@ -102,7 +104,7 @@ void InputEventsDispatched(bool raf_aligned) override; void SetNeedsMainFrame() override; - void DidFirstVisuallyNonEmptyPaint(); + void DidFirstVisuallyNonEmptyPaint(const base::TimeTicks& first_paint_time); // InputHandlerProxyClient overrides. void WillShutdown() override; @@ -283,6 +285,8 @@ void LogInputTimingUMA(); + void RecordMetricsForDroppedEventsBeforePaint(const base::TimeTicks&); + // Only valid to be called on the main thread. base::WeakPtr<WidgetBase> widget_; base::WeakPtr<mojom::blink::FrameWidgetInputHandler> @@ -335,6 +339,18 @@ // status of deferrals changes, so it needs to be thread safe. std::atomic<uint16_t> suppressing_input_events_state_; + // Saves most recent input event time that would be dropped by the + // DropInputEventsBeforeFirstPaint feature (i.e. before receiving the first + // presentation of content). If this is after the first paint timestamp, + // we log the difference to track the worst dropped event experienced. + base::TimeTicks most_recent_suppressed_event_time_; + + // Saves the number of events that would be dropped by the + // DropInputEventsBeforeFirstPaint feature (i.e. before receiving the first + // presentation of content). This is important because it shows how many times + // user tried to interact with page but the event was dropped. + int suppressed_events_count_ = 0; + // Allow input suppression to be disabled for tests and non-browser uses // of chromium that do not wait for the first commit, or that may never // commit. Over time, tests should be fixed so they provide additional
diff --git a/third_party/blink/renderer/platform/widget/widget_base.cc b/third_party/blink/renderer/platform/widget/widget_base.cc index 335eeec..b949616a 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.cc +++ b/third_party/blink/renderer/platform/widget/widget_base.cc
@@ -255,9 +255,12 @@ initialized_ = true; } -void WidgetBase::DidFirstVisuallyNonEmptyPaint() { - if (widget_input_handler_manager_) - widget_input_handler_manager_->DidFirstVisuallyNonEmptyPaint(); +void WidgetBase::DidFirstVisuallyNonEmptyPaint( + base::TimeTicks& first_paint_time) { + if (widget_input_handler_manager_) { + widget_input_handler_manager_->DidFirstVisuallyNonEmptyPaint( + first_paint_time); + } } void WidgetBase::Shutdown() {
diff --git a/third_party/blink/renderer/platform/widget/widget_base.h b/third_party/blink/renderer/platform/widget/widget_base.h index 4b50471..51186bd7b 100644 --- a/third_party/blink/renderer/platform/widget/widget_base.h +++ b/third_party/blink/renderer/platform/widget/widget_base.h
@@ -109,7 +109,7 @@ // Shutdown the compositor. void Shutdown(); - void DidFirstVisuallyNonEmptyPaint(); + void DidFirstVisuallyNonEmptyPaint(base::TimeTicks&); // Set the compositor as visible. If |visible| is true, then the compositor // will request a new layer frame sink, begin producing frames from the
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 a984a10..b5acecc 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
@@ -673,8 +673,6 @@ 'ui::IsDialog', 'ui::IsHeading', 'ui::IsLandmark', - 'ui::IsLink', - 'ui::IsImage', 'ui::IsPlatformDocument', 'ui::IsPresentational', 'ui::IsSelectRequiredOrImplicit',
diff --git a/third_party/blink/tools/print_web_test_ordering.py b/third_party/blink/tools/print_web_test_ordering.py index e6dd1b5..0da9f9c 100755 --- a/third_party/blink/tools/print_web_test_ordering.py +++ b/third_party/blink/tools/print_web_test_ordering.py
@@ -1,4 +1,4 @@ -#!/usr/bin/env vpython +#!/usr/bin/env vpython3 # Copyright (C) 2012 Google Inc. All rights reserved. # @@ -63,10 +63,10 @@ }) for worker in sorted(stats_by_worker.keys()): - print worker + ':' + print(worker + ':') for test in sorted( stats_by_worker[worker], key=lambda test: test["number"]): - print test["name"] + print(test["name"]) print @@ -74,7 +74,7 @@ # Cloned from blinkpy.web_tests.layout_package.json_results_generator # so that this code can stand alone. result = {} - for name, data in trie.iteritems(): + for name, data in trie.items(): if prefix: name = prefix + "/" + name if "results" in data:
diff --git a/third_party/blink/tools/web_tests_history.py b/third_party/blink/tools/web_tests_history.py index 6ee642d..78d85109 100755 --- a/third_party/blink/tools/web_tests_history.py +++ b/third_party/blink/tools/web_tests_history.py
@@ -1,4 +1,4 @@ -#!/usr/bin/env vpython +#!/usr/bin/env vpython3 # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file.
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index c92e3cf3b..cece273 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1728,7 +1728,6 @@ crbug.com/1078927 external/wpt/css/css-break/iframe-in-repeated-table-header-crash.html [ Crash Failure ] crbug.com/1295905 [ Mac11-arm64 ] external/wpt/css/css-break/table/sections-and-captions-mixed-order.html [ Failure ] crbug.com/1078927 external/wpt/css/css-multicol/table/balance-table-with-border-spacing.html [ Failure ] -crbug.com/1078927 fast/multicol/balance-repeating-table-headers.html [ Failure ] crbug.com/1078927 fast/multicol/table-row-height-increase.html [ Failure ] crbug.com/1078927 fragmentation/border-spacing-break-before-unbreakable-row.html [ Failure ] crbug.com/1078927 fragmentation/fragmented-rowspan-alignment.html [ Failure ] @@ -2590,10 +2589,6 @@ crbug.com/450619 external/wpt/css/css-fonts/font-feature-resolution-001.html [ Failure ] crbug.com/450619 external/wpt/css/css-fonts/font-feature-resolution-002.html [ Failure ] -# CSS Forced Color Adjust preserve-parent-color is not implemented yet -crbug.com/1242706 external/wpt/css/css-forced-color-adjust/parsing/forced-color-adjust-computed.html [ Failure ] -crbug.com/1242706 external/wpt/css/css-forced-color-adjust/parsing/forced-color-adjust-valid.html [ Failure ] - # Disabled briefly until test runner support lands. crbug.com/479533 accessibility/show-context-menu.html [ Skip ] crbug.com/479533 accessibility/show-context-menu-shadowdom.html [ Skip ] @@ -5143,6 +5138,9 @@ crbug.com/1204176 virtual/compositor-threaded-percent-based-scrolling/fast/scrolling/events/overscroll-event-fired-to-scrolled-element.html [ Failure Timeout ] crbug.com/1204176 virtual/compositor-threaded-percent-based-scrolling/fast/scrolling/events/overscroll-event-fired-to-window.html [ Failure Timeout ] +#fast/scroll-behavior/ +crbug.com/1345498 [ Mac10.14 ] virtual/scroll-unification-prefer_compositing_to_lcd_text/fast/scroll-behavior/smooth-scroll/mousewheel-scroll.html [ Failure Timeout Pass ] + ### END PERCENT BASED SCROLLING TEST FAILURES # Sheriff 2020-02-28
diff --git a/third_party/blink/web_tests/external/Version b/third_party/blink/web_tests/external/Version index 77db290..7943692 100644 --- a/third_party/blink/web_tests/external/Version +++ b/third_party/blink/web_tests/external/Version
@@ -1 +1 @@ -Version: 757400b74c36b839062534188440fb4e096541eb +Version: 6808a6b42652b5f4786a6057a8e7f6778987fb67
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 40620b3..6d7dbe62 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -915,6 +915,13 @@ {} ] ], + "chrome-remove-insert-evaluator-crash.html": [ + "986f6b0bf69f69b49f35b356483b683b256e08bc", + [ + null, + {} + ] + ], "columns-in-table-001-crash.html": [ "fe421500dade86b6fedbbf6289a668dcc5174f45", [ @@ -389927,7 +389934,7 @@ ] ], "contain-intrinsic-size-028.html": [ - "b65716142058a0b8aa2cd1139cb06cab2fcaa01a", + "a25d19687d518f2293b191a118bba5d3c3ee4dd9", [ null, {} @@ -521247,7 +521254,7 @@ {} ] ], - "worklet-rt-entries.html": [ + "worklet-rt-entries.https.html": [ "8ed280be1706b60ff2f8942a503ab7e79e08bd15", [ null,
diff --git a/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028.html b/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028.html index b657161..a25d1968 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028.html +++ b/third_party/blink/web_tests/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028.html
@@ -60,40 +60,40 @@ <hr> <img class="test cis-none" src="/css/support/60x60-green.png" - data-expected-client-width="60" data-expected-client-height="60"> + data-expected-client-width="0" data-expected-client-height="60"> <img class="test cis-height" src="/css/support/60x60-green.png" - data-expected-client-width="60" data-expected-client-height="60"> + data-expected-client-width="0" data-expected-client-height="60"> <img class="test cis-width" src="/css/support/60x60-green.png" data-expected-client-width="100" data-expected-client-height="60"> <img class="test cis-both" src="/css/support/60x60-green.png" data-expected-client-width="100" data-expected-client-height="60"> <img class="test cis-none vertical" src="/css/support/60x60-green.png" - data-expected-client-width="60" data-expected-client-height="60"> + data-expected-client-width="60" data-expected-client-height="0"> <img class="test cis-height vertical" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="50"> <img class="test cis-width vertical" src="/css/support/60x60-green.png" - data-expected-client-width="60" data-expected-client-height="60"> + data-expected-client-width="60" data-expected-client-height="0"> <img class="test cis-both vertical" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="50"> <hr> <svg class="test cis-none" - data-expected-client-width="300" data-expected-client-height="150"></svg> + data-expected-client-width="0" data-expected-client-height="150"></svg> <svg class="test cis-height" - data-expected-client-width="300" data-expected-client-height="150"></svg> + data-expected-client-width="0" data-expected-client-height="150"></svg> <svg class="test cis-width" data-expected-client-width="100" data-expected-client-height="150"></svg> <svg class="test cis-both" data-expected-client-width="100" data-expected-client-height="150"></svg> <svg class="test cis-none vertical" - data-expected-client-width="300" data-expected-client-height="150"></svg> + data-expected-client-width="300" data-expected-client-height="0"></svg> <svg class="test cis-height vertical" data-expected-client-width="300" data-expected-client-height="50"></svg> <svg class="test cis-width vertical" - data-expected-client-width="300" data-expected-client-height="150"></svg> + data-expected-client-width="300" data-expected-client-height="0"></svg> <svg class="test cis-both vertical" data-expected-client-width="300" data-expected-client-height="50"></svg> </body>
diff --git a/third_party/blink/web_tests/fast/multicol/balance-repeating-table-headers.html b/third_party/blink/web_tests/fast/multicol/balance-repeating-table-headers.html index a1335b2..ad7e973 100644 --- a/third_party/blink/web_tests/fast/multicol/balance-repeating-table-headers.html +++ b/third_party/blink/web_tests/fast/multicol/balance-repeating-table-headers.html
@@ -1,42 +1,40 @@ <!DOCTYPE html> <p>There should be a yellow/hotpink square 2x2 chessboard below.</p> <div style="columns:3; column-gap:0; width:60px; line-height:20px; orphans:1; widows:1;"> - <div style="overflow: hidden;"> - <div style="background:yellow;"><br></div> - <table cellspacing="0" cellpadding="0" style="width:40px;"> - <!-- The thead should be repeated at the top of each column - that the table breaks into. --> - <thead style="break-inside:avoid;"> - <tr> - <td style="background:hotpink;"><br></td> - </tr> - </thead> - <tbody> - <tr> - <td><br></td> - </tr> - <tr> - <td><br></td> - </tr> - <tr> - <td><br></td> - </tr> - <tr> - <td style="background:yellow;"><br></td> - </tr> - <tr> - <td><br></td> - </tr> - <tr> - <td><br></td> - </tr> - <tr> - <td><br></td> - </tr> - </tbody> - </table> - <br> - <br> - <br> - </div> + <div style="background:yellow;"><br></div> + <table cellspacing="0" cellpadding="0" style="width:20px;"> + <!-- The thead should be repeated at the top of each column + that the table breaks into. --> + <thead style="break-inside:avoid;"> + <tr> + <td style="background:hotpink;"><br></td> + </tr> + </thead> + <tbody> + <tr> + <td><br></td> + </tr> + <tr> + <td><br></td> + </tr> + <tr> + <td><br></td> + </tr> + <tr> + <td style="background:yellow;"><br></td> + </tr> + <tr> + <td><br></td> + </tr> + <tr> + <td><br></td> + </tr> + <tr> + <td><br></td> + </tr> + </tbody> + </table> + <br> + <br> + <br> </div>
diff --git a/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt b/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt new file mode 100644 index 0000000..68880385 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/highdpi/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt
@@ -0,0 +1,27 @@ +This is a testharness.js-based test. +PASS .test 1 +PASS .test 2 +PASS .test 3 +PASS .test 4 +PASS .test 5 +PASS .test 6 +PASS .test 7 +PASS .test 8 +PASS .test 9 +PASS .test 10 +PASS .test 11 +PASS .test 12 +PASS .test 13 +PASS .test 14 +PASS .test 15 +PASS .test 16 +PASS .test 17 +PASS .test 18 +PASS .test 19 +PASS .test 20 +PASS .test 21 +PASS .test 22 +PASS .test 23 +PASS .test 24 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header.js b/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header.js new file mode 100644 index 0000000..32624e6 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header.js
@@ -0,0 +1,20 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function(testRunner) { + const {page, dp} = await testRunner.startBlank( + `Test that an attributionsrc response with an invalid Attribution-Reporting-Register-Trigger header triggers an issue.`); + + await dp.Audits.enable(); + await page.navigate( + 'https://devtools.test:8443/inspector-protocol/attribution-reporting/resources/impression.html'); + + await page.loadHTML( + `<img attributionsrc="https://devtools.test:8443/inspector-protocol/attribution-reporting/resources/register-invalid-trigger.php">`); + + const issuePromise = dp.Audits.onceIssueAdded(); + const issue = await issuePromise; + testRunner.log(issue.params.issue, 'Issue reported: ', ['frame', 'request']); + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/resources/register-invalid-trigger.php b/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/resources/register-invalid-trigger.php new file mode 100644 index 0000000..23a2c31 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/attribution-reporting/resources/register-invalid-trigger.php
@@ -0,0 +1,3 @@ +<?php +header('Attribution-Reporting-Register-Trigger: !'); +?>
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt deleted file mode 100644 index 3c641a6..0000000 --- a/third_party/blink/web_tests/platform/generic/external/wpt/css/css-sizing/contain-intrinsic-size/contain-intrinsic-size-028-expected.txt +++ /dev/null
@@ -1,43 +0,0 @@ -This is a testharness.js-based test. -PASS .test 1 -PASS .test 2 -PASS .test 3 -PASS .test 4 -PASS .test 5 -PASS .test 6 -PASS .test 7 -PASS .test 8 -FAIL .test 9 assert_equals: -<img class="test cis-none" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="60"> -clientWidth expected 60 but got 0 -FAIL .test 10 assert_equals: -<img class="test cis-height" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="60"> -clientWidth expected 60 but got 0 -PASS .test 11 -PASS .test 12 -FAIL .test 13 assert_equals: -<img class="test cis-none vertical" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="60"> -clientHeight expected 60 but got 0 -PASS .test 14 -FAIL .test 15 assert_equals: -<img class="test cis-width vertical" src="/css/support/60x60-green.png" data-expected-client-width="60" data-expected-client-height="60"> -clientHeight expected 60 but got 0 -PASS .test 16 -FAIL .test 17 assert_equals: -<svg class="test cis-none" data-expected-client-width="300" data-expected-client-height="150"></svg> -clientWidth expected 300 but got 0 -FAIL .test 18 assert_equals: -<svg class="test cis-height" data-expected-client-width="300" data-expected-client-height="150"></svg> -clientWidth expected 300 but got 0 -PASS .test 19 -PASS .test 20 -FAIL .test 21 assert_equals: -<svg class="test cis-none vertical" data-expected-client-width="300" data-expected-client-height="150"></svg> -clientHeight expected 150 but got 0 -PASS .test 22 -FAIL .test 23 assert_equals: -<svg class="test cis-width vertical" data-expected-client-width="300" data-expected-client-height="150"></svg> -clientHeight expected 150 but got 0 -PASS .test 24 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt similarity index 100% rename from third_party/blink/web_tests/platform/linux/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt rename to third_party/blink/web_tests/platform/generic/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt similarity index 100% rename from third_party/blink/web_tests/platform/linux/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt rename to third_party/blink/web_tests/platform/generic/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt similarity index 100% rename from third_party/blink/web_tests/platform/linux/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt rename to third_party/blink/web_tests/platform/generic/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt similarity index 100% rename from third_party/blink/web_tests/platform/linux/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt rename to third_party/blink/web_tests/platform/generic/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt
diff --git a/third_party/blink/web_tests/platform/generic/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header-expected.txt b/third_party/blink/web_tests/platform/generic/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header-expected.txt new file mode 100644 index 0000000..df126352 --- /dev/null +++ b/third_party/blink/web_tests/platform/generic/http/tests/inspector-protocol/attribution-reporting/invalid-trigger-header-expected.txt
@@ -0,0 +1,12 @@ +Test that an attributionsrc response with an invalid Attribution-Reporting-Register-Trigger header triggers an issue. +Issue reported: { + code : AttributionReportingIssue + details : { + attributionReportingIssueDetails : { + invalidParameter : ! + request : <object> + violationType : InvalidRegisterTriggerHeader + } + } +} +
diff --git a/third_party/blink/web_tests/platform/generic/virtual/document-transition/inspector-protocol/css/css-get-styles-for-document-transition-expected.txt b/third_party/blink/web_tests/platform/generic/virtual/document-transition/inspector-protocol/css/css-get-styles-for-document-transition-expected.txt index 25e32a1..35dfc53 100644 --- a/third_party/blink/web_tests/platform/generic/virtual/document-transition/inspector-protocol/css/css-get-styles-for-document-transition-expected.txt +++ b/third_party/blink/web_tests/platform/generic/virtual/document-transition/inspector-protocol/css/css-get-styles-for-document-transition-expected.txt
@@ -112,6 +112,10 @@ name : left value : 0px } + [5] : { + name : pointer-events + value : none + } ] shorthandEntries : [ [0] : { @@ -173,6 +177,10 @@ name : transform-origin value : left top } + [5] : { + name : pointer-events + value : auto + } ] shorthandEntries : [ ] @@ -271,6 +279,10 @@ name : transform-origin value : left top } + [5] : { + name : pointer-events + value : auto + } ] shorthandEntries : [ ] @@ -1599,6 +1611,10 @@ name : left value : 0px } + [5] : { + name : pointer-events + value : none + } ] shorthandEntries : [ [0] : { @@ -1663,6 +1679,10 @@ name : transform-origin value : left top } + [5] : { + name : pointer-events + value : auto + } ] shorthandEntries : [ ] @@ -2309,6 +2329,10 @@ name : transform-origin value : left top } + [5] : { + name : pointer-events + value : auto + } ] shorthandEntries : [ ]
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png index 705559a..800944c 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png index ce7545ad..b9346e2 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png index d8fc1c9..72ea3435 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png index 70a80bad..0610a1b1 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png index 708e9e8b..12ef2ff7 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png index 7295bb3..a4546b7c 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png index 42b00ad9..492c7748 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png index 841e639..4cf54316 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index 2d7844c..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.13/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.14/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac10.14/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index 2d7844c..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.14/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/external/wpt/css/css-color-adjust/inheritance-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.15/external/wpt/css/css-color-adjust/inheritance-expected.txt index 1686f10..bf66e73 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.15/external/wpt/css/css-color-adjust/inheritance-expected.txt +++ b/third_party/blink/web_tests/platform/mac-mac10.15/external/wpt/css/css-color-adjust/inheritance-expected.txt
@@ -4,7 +4,7 @@ FAIL Property color-adjust has initial value economy assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property color-adjust inherits assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false PASS Property forced-color-adjust has initial value auto -FAIL Property forced-color-adjust inherits assert_equals: expected "preserve-parent-color" but got "auto" +PASS Property forced-color-adjust inherits FAIL Property print-color-adjust has initial value economy assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property print-color-adjust inherits assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index 94016c7e..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index d82feba..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 9d94d95..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index f9cd12f4..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index 2d7844c..0000000 --- a/third_party/blink/web_tests/platform/mac-mac10.15/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt b/third_party/blink/web_tests/platform/mac-mac11-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt index 1686f10..bf66e73 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt
@@ -4,7 +4,7 @@ FAIL Property color-adjust has initial value economy assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property color-adjust inherits assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false PASS Property forced-color-adjust has initial value auto -FAIL Property forced-color-adjust inherits assert_equals: expected "preserve-parent-color" but got "auto" +PASS Property forced-color-adjust inherits FAIL Property print-color-adjust has initial value economy assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property print-color-adjust inherits assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index 94016c7e..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index 551ffe9..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 9d94d95..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index f9cd12f4..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index f38ebae5..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index 94016c7e..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index d82feba..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 9d94d95..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index f9cd12f4..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index 2d7844c..0000000 --- a/third_party/blink/web_tests/platform/mac-mac11/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt b/third_party/blink/web_tests/platform/mac-mac12-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt index 1686f10..bf66e73 100644 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/external/wpt/css/css-color-adjust/inheritance-expected.txt
@@ -4,7 +4,7 @@ FAIL Property color-adjust has initial value economy assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property color-adjust inherits assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false PASS Property forced-color-adjust has initial value auto -FAIL Property forced-color-adjust inherits assert_equals: expected "preserve-parent-color" but got "auto" +PASS Property forced-color-adjust inherits FAIL Property print-color-adjust has initial value economy assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property print-color-adjust inherits assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index 94016c7e..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index 551ffe9..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 9d94d95..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index f9cd12f4..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index f38ebae5..0000000 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/css/css-color-adjust/inheritance-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/css/css-color-adjust/inheritance-expected.txt index 1686f10..bf66e73 100644 --- a/third_party/blink/web_tests/platform/mac/external/wpt/css/css-color-adjust/inheritance-expected.txt +++ b/third_party/blink/web_tests/platform/mac/external/wpt/css/css-color-adjust/inheritance-expected.txt
@@ -4,7 +4,7 @@ FAIL Property color-adjust has initial value economy assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property color-adjust inherits assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false PASS Property forced-color-adjust has initial value auto -FAIL Property forced-color-adjust inherits assert_equals: expected "preserve-parent-color" but got "auto" +PASS Property forced-color-adjust inherits FAIL Property print-color-adjust has initial value economy assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property print-color-adjust inherits assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt deleted file mode 100644 index fb21d62..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt +++ /dev/null
@@ -1,20 +0,0 @@ -This is a testharness.js-based test. -FAIL forwarddelete in <div> elements in <head> should join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <meta> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <title> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <style> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <script> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <link> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <base> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <template> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <script> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <style> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <title> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <script> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <style> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <title> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <script> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <style> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <title> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt deleted file mode 100644 index ec4c7c8..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt +++ /dev/null
@@ -1,15 +0,0 @@ -This is a testharness.js-based test. -FAIL delete in <div> elements after <body> should join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the <div> in the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the empty <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the <div> in the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the empty <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following invisible <head> element shouldn't delete the <head> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> around invisible <head> element should not delete the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <head> element should be merged with the <div> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <head> element should be merged with the visible <style> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <script> element should be merged with the visible <script> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt deleted file mode 100644 index 8b3c576e..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt +++ /dev/null
@@ -1,12 +0,0 @@ -This is a testharness.js-based test. -FAIL insertParagraph in empty <title style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <title style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <style style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <style style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <script style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <script style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre"> in the <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre"> (containing only a <br>) in the <head> should split the <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre"> (containing text) in the <head> should split the <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt deleted file mode 100644 index 606258a..0000000 --- a/third_party/blink/web_tests/platform/mac/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt +++ /dev/null
@@ -1,12 +0,0 @@ -This is a testharness.js-based test. -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> after <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) after <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) after <body> should not create another <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png index 94016c7e..f58d14c 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png index d82feba..26b563f 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png index 9d94d95..8173aa9 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png index f9cd12f4..18fbcb2 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png index 2d7844c..ac9a5a4 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/external/wpt/css/css-color-adjust/inheritance-expected.txt b/third_party/blink/web_tests/platform/win/external/wpt/css/css-color-adjust/inheritance-expected.txt index 1686f10..bf66e73 100644 --- a/third_party/blink/web_tests/platform/win/external/wpt/css/css-color-adjust/inheritance-expected.txt +++ b/third_party/blink/web_tests/platform/win/external/wpt/css/css-color-adjust/inheritance-expected.txt
@@ -4,7 +4,7 @@ FAIL Property color-adjust has initial value economy assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property color-adjust inherits assert_true: color-adjust doesn't seem to be supported in the computed style expected true got false PASS Property forced-color-adjust has initial value auto -FAIL Property forced-color-adjust inherits assert_equals: expected "preserve-parent-color" but got "auto" +PASS Property forced-color-adjust inherits FAIL Property print-color-adjust has initial value economy assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false FAIL Property print-color-adjust inherits assert_true: print-color-adjust doesn't seem to be supported in the computed style expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/win/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt b/third_party/blink/web_tests/platform/win/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt index b945cda..0474795 100644 --- a/third_party/blink/web_tests/platform/win/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt +++ b/third_party/blink/web_tests/platform/win/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt
@@ -30,6 +30,6 @@ FAIL Rec2020-222000000, Context display-p3, ImageData srgb, cropSource=false assert_true: Actual pixel value 134,1,3,255 is approximately equal to 186,0,0,255. expected true got false FAIL Rec2020-222000000, Context display-p3, ImageData srgb, cropSource=true assert_true: Actual pixel value 134,1,3,255 is approximately equal to 186,0,0,255. expected true got false FAIL Rec2020-222000000, Context display-p3, ImageData display-p3, cropSource=false assert_true: Actual pixel value 122,22,15,255 is approximately equal to 169,0,3,255. expected true got false -FAIL Rec2020-222000000, Context display-p3, ImageData display-p3, cropSource=true promise_test: Unhandled rejection with value: object "InvalidStateError: Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data." +FAIL Rec2020-222000000, Context display-p3, ImageData display-p3, cropSource=true assert_true: Actual pixel value 122,22,15,255 is approximately equal to 169,0,3,255. expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png index 9da068a7..6069802 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png index f0bf0c21..59e24c6 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png index e985d8f9..7de056c9 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png index 9da9cee..59a35be 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png index 54641f83..28825b5 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png index b34df05..ad5618ea 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png index 5f8f72c..8639f69 100644 --- a/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt deleted file mode 100644 index fb21d62..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-head.tentative_designMode=on_method=forwarddelete-expected.txt +++ /dev/null
@@ -1,20 +0,0 @@ -This is a testharness.js-based test. -FAIL forwarddelete in <div> elements in <head> should join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <meta> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <title> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <style> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <script> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <link> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <base> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete around invisible <template> should not delete it at joining paragraphs promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <script> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <style> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete in visible <title> elements in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <script> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <style> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <title> and <div> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <script> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <style> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL forwarddelete at boundary of <div> and <title> in <head> should not join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt deleted file mode 100644 index ec4c7c8..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/delete-in-child-of-html.tentative_designMode=off_method=backspace-expected.txt +++ /dev/null
@@ -1,15 +0,0 @@ -This is a testharness.js-based test. -FAIL delete in <div> elements after <body> should join them promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the <div> in the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> after <body> into the empty <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the <div> in the <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete should merge <div> before <body> into the empty <body> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following invisible <head> element shouldn't delete the <head> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> around invisible <head> element should not delete the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <head> element should be merged with the <div> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <head> element should be merged with the visible <style> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL delete from <div> following visible <script> element should be merged with the visible <script> in the <head> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt deleted file mode 100644 index 8b3c576e..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-head.tentative_designMode=on_white-space=pre-expected.txt +++ /dev/null
@@ -1,12 +0,0 @@ -This is a testharness.js-based test. -FAIL insertParagraph in empty <title style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <title style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <style style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <style style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <script style="display:block;white-space:pre"> should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <script style="display:block;white-space:pre"> containing text should not split it promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre"> in the <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre"> (containing only a <br>) in the <head> should split the <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre"> (containing text) in the <head> should split the <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt deleted file mode 100644 index 606258a..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/editing/other/insertparagraph-in-child-of-html.tentative_designMode=on_white-space=pre-wrap-expected.txt +++ /dev/null
@@ -1,12 +0,0 @@ -This is a testharness.js-based test. -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> after <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) after <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) after <body> should not create another <div> element promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) before <body> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in empty <div style="white-space:pre-wrap"> before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing only a <br>) before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -FAIL insertParagraph in <div style="white-space:pre-wrap"> (containing text) before <head> should split the <div> promise_test: Unhandled rejection with value: object "Error: can only send actions in top-level window" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt b/third_party/blink/web_tests/platform/win10/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt deleted file mode 100644 index 0474795..0000000 --- a/third_party/blink/web_tests/platform/win10/external/wpt/html/canvas/element/manual/wide-gamut-canvas/canvas-display-p3-drawImage-ImageBitmap-video-expected.txt +++ /dev/null
@@ -1,35 +0,0 @@ -This is a testharness.js-based test. -PASS sRGB-FF0100, Context srgb, ImageData srgb, cropSource=false -PASS sRGB-FF0100, Context srgb, ImageData srgb, cropSource=true -PASS sRGB-FF0100, Context srgb, ImageData display-p3, cropSource=false -PASS sRGB-FF0100, Context srgb, ImageData display-p3, cropSource=true -PASS sRGB-FF0100, Context display-p3, ImageData srgb, cropSource=false -PASS sRGB-FF0100, Context display-p3, ImageData srgb, cropSource=true -PASS sRGB-FF0100, Context display-p3, ImageData display-p3, cropSource=false -PASS sRGB-FF0100, Context display-p3, ImageData display-p3, cropSource=true -PASS sRGB-BB0000, Context srgb, ImageData srgb, cropSource=false -PASS sRGB-BB0000, Context srgb, ImageData srgb, cropSource=true -PASS sRGB-BB0000, Context srgb, ImageData display-p3, cropSource=false -PASS sRGB-BB0000, Context srgb, ImageData display-p3, cropSource=true -PASS sRGB-BB0000, Context display-p3, ImageData srgb, cropSource=false -PASS sRGB-BB0000, Context display-p3, ImageData srgb, cropSource=true -PASS sRGB-BB0000, Context display-p3, ImageData display-p3, cropSource=false -PASS sRGB-BB0000, Context display-p3, ImageData display-p3, cropSource=true -PASS Rec2020-3FF000000, Context srgb, ImageData srgb, cropSource=false -PASS Rec2020-3FF000000, Context srgb, ImageData srgb, cropSource=true -PASS Rec2020-3FF000000, Context srgb, ImageData display-p3, cropSource=false -PASS Rec2020-3FF000000, Context srgb, ImageData display-p3, cropSource=true -PASS Rec2020-3FF000000, Context display-p3, ImageData srgb, cropSource=false -PASS Rec2020-3FF000000, Context display-p3, ImageData srgb, cropSource=true -FAIL Rec2020-3FF000000, Context display-p3, ImageData display-p3, cropSource=false assert_true: Actual pixel value 233,51,36,255 is approximately equal to 255,0,9,255. expected true got false -FAIL Rec2020-3FF000000, Context display-p3, ImageData display-p3, cropSource=true assert_true: Actual pixel value 233,51,36,255 is approximately equal to 255,0,9,255. expected true got false -FAIL Rec2020-222000000, Context srgb, ImageData srgb, cropSource=false assert_true: Actual pixel value 134,0,2,255 is approximately equal to 186,0,0,255. expected true got false -FAIL Rec2020-222000000, Context srgb, ImageData srgb, cropSource=true assert_true: Actual pixel value 134,0,2,255 is approximately equal to 186,0,0,255. expected true got false -FAIL Rec2020-222000000, Context srgb, ImageData display-p3, cropSource=false assert_true: Actual pixel value 122,22,15,255 is approximately equal to 170,34,23,255. expected true got false -FAIL Rec2020-222000000, Context srgb, ImageData display-p3, cropSource=true assert_true: Actual pixel value 122,22,15,255 is approximately equal to 170,34,23,255. expected true got false -FAIL Rec2020-222000000, Context display-p3, ImageData srgb, cropSource=false assert_true: Actual pixel value 134,1,3,255 is approximately equal to 186,0,0,255. expected true got false -FAIL Rec2020-222000000, Context display-p3, ImageData srgb, cropSource=true assert_true: Actual pixel value 134,1,3,255 is approximately equal to 186,0,0,255. expected true got false -FAIL Rec2020-222000000, Context display-p3, ImageData display-p3, cropSource=false assert_true: Actual pixel value 122,22,15,255 is approximately equal to 169,0,3,255. expected true got false -FAIL Rec2020-222000000, Context display-p3, ImageData display-p3, cropSource=true assert_true: Actual pixel value 122,22,15,255 is approximately equal to 169,0,3,255. expected true got false -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png deleted file mode 100644 index 9da068a7..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-grammar-error-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png deleted file mode 100644 index f0bf0c21..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-line-spelling-error-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png deleted file mode 100644 index 3d489455..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-skip-ink-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index 0f5cb1bd..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index e985d8f9..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index 9da9cee..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 54641f83..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index b34df05..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png b/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png deleted file mode 100644 index 5f8f72c..0000000 --- a/third_party/blink/web_tests/platform/win10/fast/css3-text/css3-text-decoration/text-decoration-style-wavy-font-size-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/anchor-scroll-nested.html b/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/anchor-scroll-nested.html new file mode 100644 index 0000000..709148cb --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/anchor-scroll-nested.html
@@ -0,0 +1,90 @@ +<!DOCTYPE html> +<html class="reftest-wait"> +<title>Tests anchor-scroll with nested scroll containers</title> +<link rel="author" href="mailto:xiaochengh@chromium.org"> +<link rel="help" href="https://tabatkins.github.io/specs/css-anchor-position/"> +<link rel="match" href="reference/anchor-scroll-nested-ref.html"> +<style> +body { + margin: 0; + width: 1500px; + height: 1500px; + position: relative; +} + +#outer-scroller { + margin: 500px; + width: 350px; + height: 350px; + outline: 1px solid black; + overflow: scroll; +} + +#inner-scroller { + margin: 100px; + width: 250px; + height: 250px; + outline: 1px solid black; + overflow: scroll; +} + +#anchor { + margin: 200px; + width: 50px; + height: 50px; + background-color: green; + anchor-name: --anchor; +} + +.anchored { + position: absolute; + width: 50px; + height: 50px; + left: anchor(--anchor left); + anchor-scroll: --anchor; +} + +.above { + bottom: anchor(--anchor top); + background-color: red; +} + +.below { + top: anchor(--anchor bottom); + background-color: yellow; +} +</style> + +<div id="outer-scroller"> + <div id="inner-scroller"> + <div id="anchor"></div> + <div class="anchored above"></div> + </div> +</div> + +<div class="anchored below"></div> + +<script> +function raf() { + return new Promise(resolve => requestAnimationFrame(resolve)); +} + +async function runTest() { + await raf(); + await raf(); + + document.documentElement.scrollTop = 400; + document.documentElement.scrollLeft = 400; + + let outerScroller = document.getElementById('outer-scroller'); + outerScroller.scrollTop = 50; + outerScroller.scrollLeft = 50; + + let innerScroller = document.getElementById('inner-scroller'); + innerScroller.scrollTop = 100; + innerScroller.scrollLeft = 100; + + document.documentElement.classList.remove('reftest-wait'); +} +runTest(); +</script>
diff --git a/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/reference/anchor-scroll-nested-ref.html b/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/reference/anchor-scroll-nested-ref.html new file mode 100644 index 0000000..124ef66 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/css/css-anchor-position/reference/anchor-scroll-nested-ref.html
@@ -0,0 +1,74 @@ +<!DOCTYPE html> +<title>Tests anchor-scroll with nested scroll containers</title> +<link rel="author" href="mailto:xiaochengh@chromium.org"> +<link rel="help" href="https://tabatkins.github.io/specs/css-anchor-position/"> +<style> +body { + margin: 0; + width: 1500px; + height: 1500px; + position: relative; +} + +#outer-scroller { + margin: 500px; + width: 350px; + height: 350px; + outline: 1px solid black; + overflow: scroll; +} + +#inner-scroller { + margin: 100px; + width: 250px; + height: 250px; + outline: 1px solid black; + overflow: scroll; +} + +#anchor { + margin: 200px; + width: 50px; + height: 50px; + background-color: green; +} + +.anchored { + position: fixed; + width: 50px; + height: 50px; + left: 250px; +} + +.above { + top: 200px; + background-color: red; +} + +.below { + top: 300px; + background-color: yellow; +} +</style> + +<div id="outer-scroller"> + <div id="inner-scroller"> + <div id="anchor"></div> + <div class="anchored above"></div> + </div> +</div> + +<div class="anchored below"></div> + +<script> +document.documentElement.scrollTop = 400; +document.documentElement.scrollLeft = 400; + +let outerScroller = document.getElementById('outer-scroller'); +outerScroller.scrollTop = 50; +outerScroller.scrollLeft = 50; + +let innerScroller = document.getElementById('inner-scroller'); +innerScroller.scrollTop = 100; +innerScroller.scrollLeft = 100; +</script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order-ref.html b/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order-ref.html index c293709f..23d3c90f 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order-ref.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order-ref.html
@@ -6,7 +6,7 @@ <script src="/common/reftest-wait.js"></script> <style> div { - contain: paint; + contain: layout; position: absolute; top: 50px; width: 100px;
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order.html b/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order.html index ddba9f0..7f4998d6 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/css-tags-paint-order.html
@@ -7,7 +7,7 @@ <script src="/common/reftest-wait.js"></script> <style> -div { contain: paint; } +div { contain: layout; } #one { background: green; width: 100px;
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element-ref.html b/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element-ref.html new file mode 100644 index 0000000..5dbb61e --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element-ref.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<title>Shared transitions: hit test shared element at the real dom location (ref)</title> +<link rel="help" href="https://github.com/WICG/shared-element-transitions"> +<link rel="author" href="mailto:vmpstr@chromium.org"> + +<style> +#target { + width: 100px; + height: 100px; + contain: paint; + background: blue; + position: relative; + left: 200px; +} +#unrelated { + width: 100px; + height: 100px; + background: green; + position: relative; + top: 200px; + left: 200px; +} + +</style> + +<div id=target></div> +<div id=unrelated></div>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element.html b/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element.html new file mode 100644 index 0000000..3a8f99732 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/document-transition/hit-test-unrelated-element.html
@@ -0,0 +1,71 @@ +<!DOCTYPE html> +<html class=reftest-wait> +<title>Shared transitions: hit test shared element at the real dom location</title> +<link rel="help" href="https://github.com/WICG/shared-element-transitions"> +<link rel="author" href="mailto:vmpstr@chromium.org"> +<link rel="match" href="hit-test-unrelated-element-ref.html"> + +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-actions.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="/common/reftest-wait.js"></script> + +<style> +html { page-transition-tag: none } +#target { + width: 100px; + height: 100px; + contain: paint; + background: blue; + page-transition-tag: shared; +} +#target.before { + position: relative; + left: 200px; +} + +#unrelated { + width: 100px; + height: 100px; + background: red; + position: relative; + top: 200px; + left: 200px; +} +#unrelated:hover { + background: green; +} + +html::page-transition-container(shared) { + animation-delay: 300s; +} +html::page-transition-outgoing-image(shared) { + animation: unset; + opacity: 0; +} +html::page-transition-incoming-image(shared) { + animation: unset; + opacity: 1; +} +</style> + +<div id=target class=before></div> +<div id=unrelated></div> + +<script> +function mouseMoveToTarget(x, y) { + return new test_driver.Actions().pointerMove(x, y).send(); +} + +async function runTest() { + document.createDocumentTransition().start(() => { + target.classList.toggle("before"); + requestAnimationFrame(async () => { + await mouseMoveToTarget(210, 310); + requestAnimationFrame(takeScreenshot); + }); + }); +} + +onload = () => requestAnimationFrame(() => requestAnimationFrame(runTest)); +</script>
diff --git a/third_party/libavif/README.chromium b/third_party/libavif/README.chromium index cfe4f91..464a06a 100644 --- a/third_party/libavif/README.chromium +++ b/third_party/libavif/README.chromium
@@ -1,7 +1,7 @@ Name: libavif - Library for encoding and decoding .avif files Short Name: libavif URL: https://github.com/AOMediaCodec/libavif -Version: v0.10.1 +Version: 0 Revision: DEPS controlled License: 2-Clause BSD License File: LICENSE
diff --git a/tools/android/avd/proto/creation/generic_android28.textpb b/tools/android/avd/proto/creation/generic_android28.textpb index cc122a5..40f9280 100644 --- a/tools/android/avd/proto/creation/generic_android28.textpb +++ b/tools/android/avd/proto/creation/generic_android28.textpb
@@ -34,3 +34,18 @@ value: "on" } } + +min_sdk: 28 +install_privileged_apk_partition: "/system" + +privileged_apk { + package_name: "chrome_internal/third_party/google3/apks/gmscore/x86" + version: "0h92P9pOxl5e5D8ImqTtJydx6qu6qxOhsZxzeKerjCwC" + dest_path: "generic_android28/gmscore_apks" +} + +privileged_apk { + package_name: "chrome_internal/third_party/google3/apks/phonesky/x86" + version: "bzwRpftuEvDQnEXNuAGZyWUcNJGwd7NNc6Qq6YklXdsC" + dest_path: "generic_android28/phonesky_apks" +}
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index b400b413..fb29e8a 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -35,8 +35,8 @@ # https://chromium.googlesource.com/chromium/src/+/main/docs/updating_clang.md # Reverting problematic clang rolls is safe, though. # This is the output of `git describe` and is usable as a commit-ish. -CLANG_REVISION = 'llvmorg-15-init-15652-g89a99ec9' -CLANG_SUB_REVISION = 5 +CLANG_REVISION = 'llvmorg-15-init-17529-ga210f404' +CLANG_SUB_REVISION = 1 PACKAGE_VERSION = '%s-%s' % (CLANG_REVISION, CLANG_SUB_REVISION) RELEASE_VERSION = '15.0.0'
diff --git a/tools/gritsettings/resource_ids.spec b/tools/gritsettings/resource_ids.spec index 70c5134c..69f23c86 100644 --- a/tools/gritsettings/resource_ids.spec +++ b/tools/gritsettings/resource_ids.spec
@@ -124,6 +124,10 @@ "META": {"sizes": {"includes": [80]}}, "includes": [1340], }, + "<(SHARED_INTERMEDIATE_DIR)/chrome/browser/resources/chromeos/cloud_upload/resources.grd": { + "META": {"sizes": {"includes": [5]}}, + "includes": [1345], + }, "<(SHARED_INTERMEDIATE_DIR)/chrome/browser/resources/chromeos/gaia_action_buttons/resources.grd": { "META": {"sizes": {"includes": [10],}}, "includes": [1350],
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 38b71ee..c1af458 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -657,6 +657,7 @@ 'mac-arm-builder-perf-pgo': 'official_goma_mac_arm_perf_pgo', 'mac-builder-perf': 'official_goma_mac_perf', 'mac-builder-perf-pgo': 'official_goma_mac_perf_pgo', + 'mac-builder-perf-pinpoint': 'official_goma_mac_perf_pinpoint', 'win64-builder-perf': 'official_goma_perf', 'win64-builder-perf-pgo': 'official_goma_perf_pgo', }, @@ -1259,6 +1260,7 @@ 'Linux Builder Perf PGO': 'official_goma_linux_perf_pgo', 'Mac Builder Perf': 'official_goma_mac_perf', 'Mac Builder Perf PGO': 'official_goma_mac_perf_pgo', + 'Mac Builder Perf Pinpoint': 'official_goma_mac_perf_pinpoint', 'Mac arm Builder Perf': 'official_goma_mac_arm_perf', 'Mac arm Builder Perf PGO': 'official_goma_mac_arm_perf_pgo', 'Win x64 Builder Perf': 'official_goma_perf', @@ -3207,6 +3209,10 @@ 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'full_symbols', ], + 'official_goma_mac_perf_pinpoint': [ + 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'no_symbols', 'pgo_phase_0', + ], + 'official_goma_mac_pgo': [ 'official', 'goma', 'no_keystone_registration_framework', 'no_widevine_cdm_host_verification', 'disable_widevine_signing', 'static', 'no_symbols', 'pgo_phase_1' ],
diff --git a/tools/mb/mb_config_expectations/chromium.perf.json b/tools/mb/mb_config_expectations/chromium.perf.json index 9eaa4398..6d06531 100644 --- a/tools/mb/mb_config_expectations/chromium.perf.json +++ b/tools/mb/mb_config_expectations/chromium.perf.json
@@ -201,6 +201,18 @@ "use_goma": true } }, + "mac-builder-perf-pinpoint": { + "gn_args": { + "chrome_pgo_phase": 0, + "enable_keystone_registration_framework": false, + "ignore_missing_widevine_signing_cert": true, + "is_chrome_branded": true, + "is_official_build": true, + "strip_absolute_paths_from_debug_symbols": true, + "symbol_level": 0, + "use_goma": true + } + }, "win64-builder-perf": { "gn_args": { "chrome_pgo_phase": 0,
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json index e7a8896..32d77f0e 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.perf.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.perf.json
@@ -144,6 +144,18 @@ "use_goma": true } }, + "Mac Builder Perf Pinpoint": { + "gn_args": { + "chrome_pgo_phase": 0, + "enable_keystone_registration_framework": false, + "ignore_missing_widevine_signing_cert": true, + "is_chrome_branded": true, + "is_official_build": true, + "strip_absolute_paths_from_debug_symbols": true, + "symbol_level": 0, + "use_goma": true + } + }, "Mac arm Builder Perf": { "gn_args": { "chrome_pgo_phase": 0,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index af000819..8dbde950 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -57573,6 +57573,7 @@ <int value="-810684526" label="AutofillToolkitViewsCreditCardDialogsMac:disabled"/> <int value="-810110236" label="EditPasswordsInSettings:enabled"/> + <int value="-809640965" label="ShelfAutoHideSeparation:enabled"/> <int value="-809456392" label="WebViewVulkanIntermediateBuffer:enabled"/> <int value="-808486493" label="NewWallpaperPicker:disabled"/> <int value="-806549905" @@ -60450,6 +60451,7 @@ <int value="1053743655" label="NewOverviewAnimations:enabled"/> <int value="1054910800" label="enable-timezone-tracking-option"/> <int value="1055116004" label="AllowTouchpadHapticClickSettings:enabled"/> + <int value="1055907260" label="ReleaseTrackUi:disabled"/> <int value="1057014709" label="EnforceTLS13Downgrade:enabled"/> <int value="1057709415" label="DeprecateAltBasedSixPack:disabled"/> <int value="1057887829" label="AutofillScanThemeDialog:disabled"/> @@ -60691,6 +60693,7 @@ <int value="1205929554" label="SendTabToSelfOmniboxSendingAnimation:enabled"/> <int value="1206140820" label="RelatedSearchesInBar:disabled"/> <int value="1206486242" label="UseDnsHttpsSvcbAlpn:enabled"/> + <int value="1210118915" label="ShelfAutoHideSeparation:disabled"/> <int value="1210298193" label="FontAccessPersistent:enabled"/> <int value="1210343926" label="enable-drop-sync-credential"/> <int value="1211284676" label="V8NoTurbo:enabled"/> @@ -61977,6 +61980,7 @@ <int value="2043321329" label="OfflinePagesPrefetchingUI:disabled"/> <int value="2043794900" label="CommercePriceTracking:enabled"/> <int value="2044623453" label="DeferredShaping:disabled"/> + <int value="2046329062" label="ReleaseTrackUi:enabled"/> <int value="2047503404" label="FilesSWA:enabled"/> <int value="2047695652" label="DelegateOverscrollSwipes:enabled"/> <int value="2049432745" label="VaapiWebPImageDecodeAcceleration:enabled"/> @@ -74165,7 +74169,8 @@ <enum name="PaintHoldingInputTiming"> <int value="0" label="Before Lifecycle"/> <int value="1" label="Before Commit"/> - <int value="2" label="After Commit"/> + <int value="2" label="Before First Paint"/> + <int value="3" label="After First Paint"/> </enum> <enum name="PaintOpDeserializationError"> @@ -101501,6 +101506,133 @@ <int value="2" label="Not allowlisted"/> </enum> +<enum name="WebUIOSSettingsPathHashes"> + <int value="-2019732586" label="/printing"/> + <int value="-1950073287" label="/crostini/details"/> + <int value="-1924511305" label="/help"/> + <int value="-1820397898" label="/manageAccessibility"/> + <int value="-1795544471" label="/languages/inputMethods"/> + <int value="-1589300908" label="/app-management/pluginVm/sharedPaths"/> + <int value="-1569772500" label="/manageAccessibility/tts"/> + <int value="-1484929503" label="/manageAccessibility/switchAccess"/> + <int value="-1312744606" label="/knownNetworks"/> + <int value="-1279337432" label="/power"/> + <int value="-1206523744" label="/app-management/detail"/> + <int value="-1204780990" label="/dateTime/timeZone"/> + <int value="-1119639824" label="/display"/> + <int value="-1068416040" label="/multidevice/features/smartLock"/> + <int value="-1058065329" label="/languages"/> + <int value="-1048015830" label="/"/> + <int value="-988053194" label="/lockScreen"/> + <int value="-972517930" label="/googleAssistant"/> + <int value="-916174295" label="/internet"/> + <int value="-898481268" label="/multidevice/features"/> + <int value="-842548379" label="/apps"/> + <int value="-710357049" label="/bluetooth"/> + <int value="-570956986" label="/personalization"/> + <int value="-512116630" label="/search"/> + <int value="-442978022" label="/networks"/> + <int value="-378866134" label="/networkDetail"/> + <int value="-319293467" label="/multidevice"/> + <int value="-295702530" label="/smbShares"/> + <int value="-237154443" label="/manageAccessibility/tts/googleTtsEngine"/> + <int value="-230959653" label="/syncSetup"/> + <int value="-189314307" label="/crostini/exportImport"/> + <int value="-59332819" label="/accountManager"/> + <int value="-44267040" label="/bluetoothDevices"/> + <int value="-14666765" label="/accounts"/> + <int value="8030578" label="/crostini/sharedUsbDevices"/> + <int value="8530592" label="/syncSetup/advanced"/> + <int value="16287984" label="/languages/details"/> + <int value="48634426" label="/osReset"/> + <int value="149495749" label="/osLanguages"/> + <int value="223791833" label="/help/about"/> + <int value="282161661" label="/osPeople"/> + <int value="297583680" label="/device"/> + <int value="309061570" label="/osPrivacy/accounts"/> + <int value="334469894" label="/people"/> + <int value="383306038" label="/ambientMode"/> + <int value="473528525" label="/audio"/> + <int value="527386438" label="/osLanguages/languages"/> + <int value="683177973" label="/cupsPrinters"/> + <int value="754547746" label="/help/details"/> + <int value="863669423" label="/textToSpeech"/> + <int value="868952532" label="/pointer-overlay"/> + <int value="996514470" label="/osSyncSetup"/> + <int value="1071171447" label="/osPrinting"/> + <int value="1114615837" label="/accessibility"/> + <int value="1163194731" label="/osAccessibility"/> + <int value="1189329372" label="/kerberos/kerberosAccounts"/> + <int value="1258785570" label="/crostini/sharedPaths"/> + <int value="1289925226" label="/osPrivacy/privacyHub"/> + <int value="1300569861" label="/keyboard-overlay"/> + <int value="1384165448" label="/stylus"/> + <int value="1429807312" label="/displayAndMagnification"/> + <int value="1433770724" label="/osSearch"/> + <int value="1462185522" label="/dateTime"/> + <int value="1466297319" label="/bluetoothSavedDevices"/> + <int value="1602314362" label="/storage"/> + <int value="1611548266" label="/crostini/extraContainers"/> + <int value="1661964813" label="/reset"/> + <int value="1693191706" label="/osPrivacy/lockScreen/fingerprint"/> + <int value="1810385625" label="/crostini"/> + <int value="1831829553" label="/multidevice/nearbyshare"/> + <int value="1847987129" label="/bruschetta/sharedUsbDevices"/> + <int value="1853516270" label="/lockScreen/fingerprint"/> + <int value="1880662603" label="/osLanguages/input"/> + <int value="1952830804" label="/osLanguages/inputMethodOptions"/> + <int value="1956464558" label="/changePicture"/> + <int value="2014923527" label="/storage/externalStoragePreferences"/> + <int value="2030415176" label="/files"/> + <int value="2121014241" label="/audioAndCaptions"/> + <int value="2136345292" label="/privacy"/> + <int value="2236117233" label="/cursorAndTouchpad"/> + <int value="2292642563" label="/androidAppsDetails"/> + <int value="2344894009" label="/crostini/details"/> + <int value="2370455991" label="/help"/> + <int value="2474569398" label="/manageAccessibility"/> + <int value="2583527907" label="/manageAccessibility/captions"/> + <int value="2584045321" label="/app-notifications"/> + <int value="2705666388" label="/app-management/pluginVm/sharedPaths"/> + <int value="2725194796" label="/manageAccessibility/tts"/> + <int value="2810037793" label="/manageAccessibility/switchAccess"/> + <int value="2827754479" label="/osPrivacy/lockScreen"/> + <int value="2831082225" label="/bluetoothDeviceDetail"/> + <int value="2982222690" label="/knownNetworks"/> + <int value="3015629864" label="/power"/> + <int value="3088443552" label="/app-management/detail"/> + <int value="3090186306" label="/dateTime/timeZone"/> + <int value="3174617532" label="/osLanguages/smartInputs"/> + <int value="3175327472" label="/display"/> + <int value="3226551256" label="/multidevice/features/smartLock"/> + <int value="3246951466" label="/"/> + <int value="3322449366" label="/googleAssistant"/> + <int value="3378793001" label="/internet"/> + <int value="3396486028" label="/multidevice/features"/> + <int value="3447116306" label="/osSearch/search"/> + <int value="3452400691" label="/kerberos"/> + <int value="3452418917" label="/apps"/> + <int value="3453079661" label="/osSync"/> + <int value="3514732098" label="/keyboardAndTextInput"/> + <int value="3531919210" label="/osLanguages/editDictionary"/> + <int value="3561556862" label="/app-management/pluginVm/sharedUsbDevices"/> + <int value="3584610247" label="/bluetooth"/> + <int value="3585870839" label="/crostini/androidAdb"/> + <int value="3724010310" label="/personalization"/> + <int value="3869947881" label="/crostini/portForwarding"/> + <int value="3916101162" label="/networkDetail"/> + <int value="3958116773" label="/osPrivacy/smartPrivacy"/> + <int value="3975673829" label="/multidevice"/> + <int value="3999264766" label="/smbShares"/> + <int value="4060403967" label="/osPrivacy"/> + <int value="4083684424" label="/bruschetta/details"/> + <int value="4105652989" label="/crostini/exportImport"/> + <int value="4171209718" label="/app-management"/> + <int value="4174275430" label="/androidAppsDetails/sharedUsbDevices"/> + <int value="4235634477" label="/accountManager"/> + <int value="4250700256" label="/bluetoothDevices"/> +</enum> + <enum name="WebUISettingsPathHashes"> <int value="-2088016711" label="/startupPages"/> <int value="-2082028555" label="/androidApps/details"/>
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index c463041..dfcc7cda 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -4649,6 +4649,16 @@ </summary> </histogram> +<histogram name="Android.WebView.VariationsHeaderLength" units="bytes" + expires_after="2023-07-22"> + <owner>cduvall@chromium.org</owner> + <owner>src/android_webview/OWNERS</owner> + <summary> + Records the length of the WebView variations header. Recorded every time + WebViewCompat.getVariationsHeader() is called. + </summary> +</histogram> + <histogram name="Android.WebView.Visibility.Global" enum="WebViewVisibility" expires_after="2023-04-19"> <owner>idries@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/chromeos_settings/histograms.xml b/tools/metrics/histograms/metadata/chromeos_settings/histograms.xml index 3d96607a..79ccb796 100644 --- a/tools/metrics/histograms/metadata/chromeos_settings/histograms.xml +++ b/tools/metrics/histograms/metadata/chromeos_settings/histograms.xml
@@ -237,8 +237,8 @@ </summary> </histogram> -<histogram name="ChromeOS.Settings.PathVisited" enum="WebUISettingsPathHashes" - expires_after="2023-04-17"> +<histogram name="ChromeOS.Settings.PathVisited" + enum="WebUIOSSettingsPathHashes" expires_after="2023-04-17"> <owner>xiaohuic@chromium.org</owner> <owner>cros-settings@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/compositing/histograms.xml b/tools/metrics/histograms/metadata/compositing/histograms.xml index 24e387e..76de164b 100644 --- a/tools/metrics/histograms/metadata/compositing/histograms.xml +++ b/tools/metrics/histograms/metadata/compositing/histograms.xml
@@ -863,8 +863,8 @@ </histogram> <histogram name="CompositorLatency{ReportType}{InteractionType}.{StageType}" - units="microseconds" expires_after="2022-07-24"> - <owner>sadrul@chromium.org</owner> + units="microseconds" expires_after="2023-07-24"> + <owner>jonross@chromium.org</owner> <owner>graphics-dev@chromium.org</owner> <summary> Tracks the duration of various stages in the pipeline as a single frame goes
diff --git a/tools/metrics/histograms/metadata/cookie/histograms.xml b/tools/metrics/histograms/metadata/cookie/histograms.xml index c69c4fbe..fb4e7a5 100644 --- a/tools/metrics/histograms/metadata/cookie/histograms.xml +++ b/tools/metrics/histograms/metadata/cookie/histograms.xml
@@ -44,7 +44,7 @@ </histogram> <histogram name="Cookie.ClockSkew.{SkewDirection}" units="minutes" - expires_after="2022-11-01"> + expires_after="2023-04-01"> <owner>kyraseevers@chromium.org</owner> <owner>bingler@chromium.org</owner> <summary> @@ -55,13 +55,28 @@ </summary> <token key="SkewDirection"> <variant name="AddMinutes" + summary="The raw clock skew value was positive or zero, so these + cookies were adjusted to expire later."/> + <variant name="AddMinutes12To24Hours" summary="The raw clock skew value was positive, so these cookies were - adjusted to expire later."/> + adjusted to expire later. The range of bucket values for + this metric is 720 to 1440 minutes (12 to 24 hours)."/> <variant name="SubtractMinutes" summary="The raw clock skew value was negative, so these cookies were adjusted to expire quicker. This histogram can only record positive values, so all counts are adjusted to their positive counterparts."/> + <variant name="SubtractMinutes12To24Hours" + summary="The raw clock skew value was negative, so these cookies were + adjusted to expire quicker. This histogram can only record + positive values, so all counts are adjusted to their + positive counterparts.The range of bucket values for this + metric is 720 to 1440 minutes (12 to 24 hours)."/> + <variant name="WithoutAddMinutesExpires" + summary="The raw clock skew value was positive AND the addition of + these minutes caused the cookie to delay expiring until + later. If this cookie was not adjusted for clock skew, it + would have expired immediately."/> </token> </histogram>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index bc486c6..7c9fdf90 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -9442,12 +9442,12 @@ </summary> </histogram> -<histogram name="PaintHolding.InputTiming2" enum="PaintHoldingInputTiming" +<histogram name="PaintHolding.InputTiming3" enum="PaintHoldingInputTiming" expires_after="2023-01-01"> <owner>schenney@chromium.org</owner> <owner>paint-dev@chromium.org</owner> <summary> - Records whether or not input arrived before the first commit. + Records whether or not input arrived before the first paint. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/page/histograms.xml b/tools/metrics/histograms/metadata/page/histograms.xml index 5b17481..00013a8 100644 --- a/tools/metrics/histograms/metadata/page/histograms.xml +++ b/tools/metrics/histograms/metadata/page/histograms.xml
@@ -2317,6 +2317,44 @@ </summary> </histogram> +<histogram name="PageLoad.Internal.SuppressedEventsCountBeforePaint" + units="count" expires_after="2023-01-01"> + <owner>mehdika@chromium.org</owner> + <owner>blink-interactions-team@google.com</owner> + <summary> + Measures the number of events observed before the first paint. This metric + is emitted for every committed page load, immediately after the first paint + is complete. When the DropInputEventsBeforeFirstPaint feature is enabled + these events will be dropped as the user may not have seen the content they + are interacting with yet. Since there is a delay from the first paint + presentation to when the notification about it is received the user may have + actually seen the first paint for some of these events. If many events are + being dropped we may need to revisit this experiment or improve the + measurement to only those after the first paint. + </summary> +</histogram> + +<histogram name="PageLoad.Internal.SuppressedEventsTimingBeforePaint" + units="ms" expires_after="2023-01-01"> + <owner>mehdika@chromium.org</owner> + <owner>blink-interactions-team@google.com</owner> + <summary> + Measures time difference between first paint and last event dropped by + DropInputEventsBeforeFirstPaint feature. This metric is emitted for every + committed page load, immediately after the first paint is complete. When the + DropInputEventsBeforeFirstPaint feature is enabled events observed before + the first paint will be dropped as the user may not have seen the content + they are interacting with yet. Since there is a delay from the first paint + presentation to when the notification about it is received the user may have + actually seen the first paint for some of these events. If this time + difference is long enough to affect user experience we may need to revisit + this experiment. We are logging 0 timestamp if there is no suppressed event + or the most recent suppressed event is before the first paint time so that + we have a count of the number of times the behavior was good to compare the + size of the bad cases to. + </summary> +</histogram> + <histogram name="PageLoad.LayoutInstability.CumulativeShiftScore" units="scorex10" expires_after="2023-07-13"> <owner>bmcquade@chromium.org</owner> @@ -2594,7 +2632,7 @@ </histogram> <histogram name="PageLoad.PaintTiming.NavigationToFirstImagePaint" units="ms" - expires_after="2022-08-21"> + expires_after="2023-07-21"> <owner>sullivan@chromium.org</owner> <owner>speed-metrics-dev@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/privacy/histograms.xml b/tools/metrics/histograms/metadata/privacy/histograms.xml index dac2a20e..9e2bdf7 100644 --- a/tools/metrics/histograms/metadata/privacy/histograms.xml +++ b/tools/metrics/histograms/metadata/privacy/histograms.xml
@@ -292,7 +292,7 @@ <histogram name="PrivacySandbox.AggregationService.KeyFetcher.HttpResponseOrNetErrorCode" - enum="NetErrorCodes" expires_after="2022-08-23"> + enum="NetErrorCodes" expires_after="2023-02-23"> <owner>alexmt@chromium.org</owner> <owner>linnan@chromium.org</owner> <summary> @@ -339,7 +339,7 @@ <histogram name="PrivacySandbox.AggregationService.ReportSender.HttpResponseOrNetErrorCode" - enum="CombinedHttpResponseAndNetErrorCode" expires_after="2022-08-23"> + enum="CombinedHttpResponseAndNetErrorCode" expires_after="2023-02-23"> <owner>alexmt@chromium.org</owner> <owner>linnan@chromium.org</owner> <summary> @@ -351,7 +351,7 @@ <histogram name="PrivacySandbox.AggregationService.ReportSender.Status" enum="PrivacySandboxAggregationServiceReportSenderStatus" - expires_after="2022-08-23"> + expires_after="2023-02-23"> <owner>alexmt@chromium.org</owner> <owner>linnan@chromium.org</owner> <summary> @@ -384,7 +384,7 @@ </histogram> <histogram name="PrivacySandbox.AggregationService.Storage.Sql.CreationTime" - units="ms" expires_after="2022-08-23"> + units="ms" expires_after="2023-02-23"> <owner>alexmt@chromium.org</owner> <owner>linnan@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/subresource/histograms.xml b/tools/metrics/histograms/metadata/subresource/histograms.xml index 227bbef..061b96f3 100644 --- a/tools/metrics/histograms/metadata/subresource/histograms.xml +++ b/tools/metrics/histograms/metadata/subresource/histograms.xml
@@ -243,7 +243,7 @@ </histogram> <histogram name="SubresourceFilter.DocumentLoad.SubframeFilteringDelay.Allowed" - units="microseconds" expires_after="2022-08-09"> + units="microseconds" expires_after="2023-08-09"> <owner>alexmt@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> <summary> @@ -287,7 +287,7 @@ </histogram> <histogram name="SubresourceFilter.Experimental.ReadyToCommitResultsInCommit2" - enum="Boolean" expires_after="2022-08-14"> + enum="Boolean" expires_after="2023-08-14"> <owner>alexmt@chromium.org</owner> <owner>johnidel@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> @@ -304,7 +304,7 @@ <histogram name="SubresourceFilter.Experimental.ReadyToCommitResultsInCommit2.RestrictedAdFrameNavigation" - enum="Boolean" expires_after="2022-08-28"> + enum="Boolean" expires_after="2023-08-28"> <owner>alexmt@chromium.org</owner> <owner>johnidel@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> @@ -390,7 +390,7 @@ <histogram name="SubresourceFilter.MainFrameLoad.RulesetIsAvailableAnyActivationLevel" - enum="BooleanAvailable" expires_after="2022-08-09"> + enum="BooleanAvailable" expires_after="2023-08-09"> <owner>alexmt@chromium.org</owner> <owner>jkarlin@chromium.org</owner> <summary> @@ -502,7 +502,7 @@ </histogram> <histogram name="SubresourceFilter.PageLoad.SafeBrowsingDelay" units="ms" - expires_after="2022-07-31"> + expires_after="2023-07-31"> <owner>alexmt@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> <summary> @@ -592,7 +592,7 @@ </histogram> <histogram name="SubresourceFilter.SubresourceLoad.Evaluation.CPUDuration" - units="microseconds" expires_after="2022-06-19"> + units="microseconds" expires_after="2023-07-25"> <owner>alexmt@chromium.org</owner> <owner>chrome-ads-histograms@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/webapps/histograms.xml b/tools/metrics/histograms/metadata/webapps/histograms.xml index a73376603..2d8723a 100644 --- a/tools/metrics/histograms/metadata/webapps/histograms.xml +++ b/tools/metrics/histograms/metadata/webapps/histograms.xml
@@ -828,7 +828,7 @@ used to trigger a Perfetto trace to provide more debugging information. See crbug.com/1201820 for more details. - Warning: this histogram was expired from 2021-09-01 to 2022-12-31, data may + Warning: this histogram was expired from 2021-09-01 through M105, data may be missing. </summary> </histogram>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index fac1e289f..4413e64 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,24 +5,24 @@ "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "ab72fde28b8d84c12e2de2ebd2eee9177ff4d45d", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/049a4290ea53cc6797f5b1c433bbc5a21985ad77/trace_processor_shell.exe" + "hash": "2248c20cf6d98c436292ae961f87060d7099a4cb", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/e4d93e430c4751cda91e9fb5603154a6d44314fd/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "51434125005f7f2ea81241f2a2045870e0e01afa", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/049a4290ea53cc6797f5b1c433bbc5a21985ad77/trace_processor_shell" + "hash": "7d5b49130f6e3ec1627783ab5c2908adcf70def8", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/e4d93e430c4751cda91e9fb5603154a6d44314fd/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6", "full_remote_path": "perfetto-luci-artifacts/v25.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "e5fb41a71c96e4800a9c0dc7d8647b9dc56629fe", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/624891936a38ebb943bd53afc7610cebb8bba946/trace_processor_shell" + "hash": "6618ebd430cb56e06fdd328970e63dab9b06dfdd", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/e19e4f253f28cfb21c5a2c2587c98b77b978bb98/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/aura/client/capture_client.h b/ui/aura/client/capture_client.h index c787426..cd17c05 100644 --- a/ui/aura/client/capture_client.h +++ b/ui/aura/client/capture_client.h
@@ -15,6 +15,14 @@ class CaptureClientObserver; // An interface implemented by an object that manages input capture. +// +// The intended semantics of window-capture are that: +// * At most one window on the system can register as "capturing" input. +// * If a window is capturing input, then all input events will get routed to +// this window. +// * The window may choose to release capture while processing an event. The +// resulting behavior is platform dependent (e.g. whether the event is +// redispatched to the window server). class AURA_EXPORT CaptureClient { public: // Does a capture on the |window|.
diff --git a/ui/chromeos/file_manager_strings.grdp b/ui/chromeos/file_manager_strings.grdp index b423fc6..ee3353c 100644 --- a/ui/chromeos/file_manager_strings.grdp +++ b/ui/chromeos/file_manager_strings.grdp
@@ -425,13 +425,6 @@ An error occured during installation of your Linux application. </message> - <message name="IDS_FILE_BROWSER_AUDIO_ERROR" desc="In the Audio Player, message informing that the file could not be played."> - This file could not be played. - </message> - <message name="IDS_FILE_BROWSER_AUDIO_OFFLINE" desc="In the Audio Player, message informing that the audio file could not be played in the offline mode."> - This file is not available offline. - </message> - <message name="IDS_FILE_BROWSER_RECOVERED_FILES_FROM_GOOGLE_DRIVE_DIRECTORY_NAME" desc="The name of the direcotry which stores files recovered from Google Drive directory when the locally stored Google Drive data is found to be broken."> Recovered files from Google Drive </message> @@ -1404,12 +1397,6 @@ <message name="IDS_FILE_BROWSER_ERROR_UNRESOLVABLE_FILE" desc="Error message when the file attempted to open from Downloads panel was not found under paths managed by file manager."> This file has wandered off somewhere. Please check your download location setting and try again. </message> - <message name="IDS_FILE_BROWSER_AUDIO_PLAYER_TITLE" desc="Title of the Audio Player window."> - Audio Player - </message> - <message name="IDS_FILE_BROWSER_AUDIO_PLAYER_DEFAULT_ARTIST" desc="In the Audio Player window, default artist name used when artist name is unknown."> - Unknown Artist - </message> <message name="IDS_FILE_BROWSER_FILE_ERROR_GENERIC" desc="In the File Manager, the error message when the file operation failed."> An error occurred. @@ -1554,20 +1541,6 @@ Volume slider </message> -<!-- Audio Player --> - <message name="IDS_AUDIO_PLAYER_SHUFFLE_BUTTON_LABEL" desc="Label for the Shuffle button of audio player."> - Shuffle - </message> - <message name="IDS_AUDIO_PLAYER_REPEAT_BUTTON_LABEL" desc="Label for the Repeat button of audio player"> - Repeat - </message> - <message name="IDS_AUDIO_PLAYER_OPEN_PLAY_LIST_BUTTON_LABEL" desc="Label for a button which is used to open play list in audio player."> - Open play list - </message> - <message name="IDS_AUDIO_PLAYER_ARTWORK_EXPAND_BUTTON_LABEL" desc="Label for an expand button which is used to show/hide artwork."> - Artwork - </message> - <!-- Data Leak Prevention --> <message name="IDS_FILE_BROWSER_DLP_BLOCK_COPY_TOAST" desc="A toast informing the user that copying files is blocked by the administrator."> Pasting this file is blocked by your administrator
diff --git a/ui/display/mac/test/virtual_display_mac_util.mm b/ui/display/mac/test/virtual_display_mac_util.mm index 99147bd4..c40a7db 100644 --- a/ui/display/mac/test/virtual_display_mac_util.mm +++ b/ui/display/mac/test/virtual_display_mac_util.mm
@@ -13,7 +13,6 @@ #include "base/check.h" #include "base/check_op.h" #include "base/mac/scoped_nsobject.h" -#include "build/build_config.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/size.h" @@ -391,14 +390,6 @@ // static bool VirtualDisplayMacUtil::IsAPIAvailable() { - bool is_arch_cpu_arm_family = false; -#if defined(ARCH_CPU_ARM_FAMILY) - is_arch_cpu_arm_family = true; -#endif // defined(ARCH_CPU_ARM_FAMILY) - if (is_arch_cpu_arm_family) { - return false; - } - bool is_api_available = false; if (@available(macos 12.0, *)) { is_api_available = true;
diff --git a/ui/display/mac/test/virtual_display_mac_util_interactive_uitest.mm b/ui/display/mac/test/virtual_display_mac_util_interactive_uitest.mm index 04b24fe..a838d81 100644 --- a/ui/display/mac/test/virtual_display_mac_util_interactive_uitest.mm +++ b/ui/display/mac/test/virtual_display_mac_util_interactive_uitest.mm
@@ -19,7 +19,7 @@ void SetUp() override { if (!display::test::VirtualDisplayMacUtil::IsAPIAvailable()) { - GTEST_SKIP() << "Skipping test for MacOS 11.0 and older or Arm Macs."; + GTEST_SKIP() << "Skipping test for MacOS 11.0 and older."; } testing::Test::SetUp();
diff --git a/ui/events/ozone/evdev/event_converter_evdev_impl.cc b/ui/events/ozone/evdev/event_converter_evdev_impl.cc index 60835c6..0613ae6 100644 --- a/ui/events/ozone/evdev/event_converter_evdev_impl.cc +++ b/ui/events/ozone/evdev/event_converter_evdev_impl.cc
@@ -67,7 +67,7 @@ #endif // Converts unsigned long to uint64_t. const auto key_bits = devinfo.GetKeyBits(); - key_bits_.resize(key_bits.size()); + key_bits_.resize(EVDEV_BITS_TO_INT64(KEY_CNT)); for (int i = 0; i < KEY_CNT; i++) { if (EvdevBitIsSet(key_bits.data(), i)) { EvdevSetUint64Bit(key_bits_.data(), i);
diff --git a/ui/events/ozone/evdev/gamepad_event_converter_evdev.cc b/ui/events/ozone/evdev/gamepad_event_converter_evdev.cc index fec1d4fa..56029fba 100644 --- a/ui/events/ozone/evdev/gamepad_event_converter_evdev.cc +++ b/ui/events/ozone/evdev/gamepad_event_converter_evdev.cc
@@ -60,7 +60,7 @@ supports_rumble_ = devinfo.SupportsRumble(); // Converts unsigned long to uint64_t. const auto key_bits = devinfo.GetKeyBits(); - key_bits_.resize(key_bits.size()); + key_bits_.resize(EVDEV_BITS_TO_INT64(KEY_CNT)); for (int i = 0; i < KEY_CNT; i++) { if (EvdevBitIsSet(key_bits.data(), i)) { EvdevSetUint64Bit(key_bits_.data(), i);
diff --git a/ui/file_manager/BUILD.gn b/ui/file_manager/BUILD.gn index ec59114..23ad76b 100644 --- a/ui/file_manager/BUILD.gn +++ b/ui/file_manager/BUILD.gn
@@ -39,8 +39,6 @@ testonly = true deps = [ - "audio_player/elements:closure_compile", - "audio_player/js:closure_compile", "file_manager/background/js:closure_compile", "file_manager/common/js:closure_compile", "file_manager/foreground/elements:closure_compile", @@ -96,10 +94,9 @@ out_folder = preprocess_folder out_manifest = "$target_gen_dir/manifest_preprocess_static_image_loader.json" - in_files = audio_static_js_files + image_loader_static_js_files + in_files = image_loader_static_js_files deps = [ - "//ui/file_manager/audio_player/js:js_modules", "//ui/file_manager/image_loader:background", "//ui/file_manager/image_loader:js_modules", ] @@ -129,12 +126,9 @@ out_manifest = "$target_gen_dir/manifest_preprocess_generated_image_loader.json" - in_files = audio_generated_js_files + image_loader_generated_js_files + in_files = image_loader_generated_js_files - deps = [ - "//ui/file_manager/audio_player/elements:web_components", - "//ui/file_manager/image_loader:copy_from_filesapp", - ] + deps = [ "//ui/file_manager/image_loader:copy_from_filesapp" ] } ts_library("build_ts") { @@ -177,30 +171,17 @@ generate_grd("build_grd") { out_grd = generated_grd - grdp_files = [ - "$target_gen_dir/audio_player/static_resources.grdp", - "$target_gen_dir/file_manager/static_resources.grdp", - ] + grdp_files = [ "$target_gen_dir/file_manager/static_resources.grdp" ] deps = [ ":build_ts", - "audio_player:build_static_grdp", "file_manager:build_static_grdp", - "//ui/file_manager/audio_player/js:build", - "//ui/file_manager/audio_player/js:build_background", - "//ui/file_manager/audio_player/js:build_worker", "//ui/file_manager/file_manager:fix_broken_images", "//ui/file_manager/image_loader:build", ] input_files_base_dir = rebase_path(target_gen_dir, root_build_dir) input_files = [ - "audio_player/js/main.rollup.js", - "audio_player/js/main_background.rollup.js", - "audio_player/js/metadata_worker.rollup.js", - "audio_player/js/shared.rollup.js", - "audio_player/js/runtime_loaded_test_util.rollup.js", - # Fix broken images: "file_manager/images/files/ui/arrow_right.svg", "file_manager/images/files/ui/state_banner_icon.svg", @@ -210,13 +191,8 @@ "image_loader/background.rollup.js", ] - resource_path_rewrites = [ - "audio_player/js/main.rollup.js|audio_player/js/main.js", - "audio_player/js/main_background.rollup.js|audio_player/js/main_background.js", - "audio_player/js/metadata_worker.rollup.js|audio_player/js/metadata_worker.js", - "audio_player/js/runtime_loaded_test_util.rollup.js|audio_player/js/runtime_loaded_test_util.js", - "image_loader/background.rollup.js|image_loader/background.js", - ] + resource_path_rewrites = + [ "image_loader/background.rollup.js|image_loader/background.js" ] if (optimize_webui) { input_files += [
diff --git a/ui/file_manager/audio_player/BUILD.gn b/ui/file_manager/audio_player/BUILD.gn deleted file mode 100644 index 7f7a2ad..0000000 --- a/ui/file_manager/audio_player/BUILD.gn +++ /dev/null
@@ -1,50 +0,0 @@ -# Copyright 2020 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//ui/webui/resources/tools/generate_grd.gni") - -generated_static_grdp = "$target_gen_dir/static_resources.grdp" - -generate_grd("build_static_grdp") { - out_grd = generated_static_grdp - grd_prefix = "audio_player" - - resource_path_prefix = "audio_player" - - input_files_base_dir = rebase_path(".", "//") - - input_files = [ - # Images: - "assets/100/player_button_next.png", - "assets/100/player_button_pause.png", - "assets/100/player_button_playlist.png", - "assets/100/player_button_play.png", - "assets/100/player_button_previous.png", - "assets/100/player_button_repeat_one.png", - "assets/100/player_button_repeat.png", - "assets/100/player_button_shuffle.png", - "assets/100/player_button_volume_muted.png", - "assets/100/player_button_volume.png", - "assets/100/player_cover_close.png", - "assets/100/player_cover_open.png", - "assets/100/player_no_artwork.png", - "assets/100/playlist_now_playing.png", - "assets/100/playlist_play.png", - "assets/200/player_button_next.png", - "assets/200/player_button_pause.png", - "assets/200/player_button_playlist.png", - "assets/200/player_button_play.png", - "assets/200/player_button_previous.png", - "assets/200/player_button_repeat_one.png", - "assets/200/player_button_repeat.png", - "assets/200/player_button_shuffle.png", - "assets/200/player_button_volume_muted.png", - "assets/200/player_button_volume.png", - "assets/200/player_cover_close.png", - "assets/200/player_cover_open.png", - "assets/200/player_no_artwork.png", - "assets/200/playlist_now_playing.png", - "assets/200/playlist_play.png", - ] -}
diff --git a/ui/file_manager/audio_player/OWNERS b/ui/file_manager/audio_player/OWNERS deleted file mode 100644 index 13c6f49f..0000000 --- a/ui/file_manager/audio_player/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -tapted@chromium.org
diff --git a/ui/file_manager/audio_player/assets/100/player_button_next.png b/ui/file_manager/audio_player/assets/100/player_button_next.png deleted file mode 100644 index 0dd7709bb..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_next.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_pause.png b/ui/file_manager/audio_player/assets/100/player_button_pause.png deleted file mode 100644 index c070a25..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_pause.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_play.png b/ui/file_manager/audio_player/assets/100/player_button_play.png deleted file mode 100644 index 6f05107..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_playlist.png b/ui/file_manager/audio_player/assets/100/player_button_playlist.png deleted file mode 100644 index 4c8370d..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_playlist.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_previous.png b/ui/file_manager/audio_player/assets/100/player_button_previous.png deleted file mode 100644 index 46bf7e1..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_previous.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_repeat.png b/ui/file_manager/audio_player/assets/100/player_button_repeat.png deleted file mode 100644 index 63f60d7..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_repeat.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_repeat_one.png b/ui/file_manager/audio_player/assets/100/player_button_repeat_one.png deleted file mode 100644 index 6372eb0c..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_repeat_one.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_shuffle.png b/ui/file_manager/audio_player/assets/100/player_button_shuffle.png deleted file mode 100644 index f1d54f4..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_shuffle.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_volume.png b/ui/file_manager/audio_player/assets/100/player_button_volume.png deleted file mode 100644 index ce60e626..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_volume.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_button_volume_muted.png b/ui/file_manager/audio_player/assets/100/player_button_volume_muted.png deleted file mode 100644 index c9fd787..0000000 --- a/ui/file_manager/audio_player/assets/100/player_button_volume_muted.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_cover_close.png b/ui/file_manager/audio_player/assets/100/player_cover_close.png deleted file mode 100644 index 00042f2..0000000 --- a/ui/file_manager/audio_player/assets/100/player_cover_close.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_cover_open.png b/ui/file_manager/audio_player/assets/100/player_cover_open.png deleted file mode 100644 index 8524c1e..0000000 --- a/ui/file_manager/audio_player/assets/100/player_cover_open.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/player_no_artwork.png b/ui/file_manager/audio_player/assets/100/player_no_artwork.png deleted file mode 100644 index aa01ae68..0000000 --- a/ui/file_manager/audio_player/assets/100/player_no_artwork.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/playlist_now_playing.png b/ui/file_manager/audio_player/assets/100/playlist_now_playing.png deleted file mode 100644 index 9082e99..0000000 --- a/ui/file_manager/audio_player/assets/100/playlist_now_playing.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/100/playlist_play.png b/ui/file_manager/audio_player/assets/100/playlist_play.png deleted file mode 100644 index 0df434c0..0000000 --- a/ui/file_manager/audio_player/assets/100/playlist_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_next.png b/ui/file_manager/audio_player/assets/200/player_button_next.png deleted file mode 100644 index 9c1129c..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_next.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_pause.png b/ui/file_manager/audio_player/assets/200/player_button_pause.png deleted file mode 100644 index 5e71f9ac..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_pause.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_play.png b/ui/file_manager/audio_player/assets/200/player_button_play.png deleted file mode 100644 index b848dc9..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_playlist.png b/ui/file_manager/audio_player/assets/200/player_button_playlist.png deleted file mode 100644 index f6bb0bd..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_playlist.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_previous.png b/ui/file_manager/audio_player/assets/200/player_button_previous.png deleted file mode 100644 index 621c1f6a..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_previous.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_repeat.png b/ui/file_manager/audio_player/assets/200/player_button_repeat.png deleted file mode 100644 index 468d5ed..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_repeat.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_repeat_one.png b/ui/file_manager/audio_player/assets/200/player_button_repeat_one.png deleted file mode 100644 index 306ffe8..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_repeat_one.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_shuffle.png b/ui/file_manager/audio_player/assets/200/player_button_shuffle.png deleted file mode 100644 index 8a25deb..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_shuffle.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_volume.png b/ui/file_manager/audio_player/assets/200/player_button_volume.png deleted file mode 100644 index 5b837b5..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_volume.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_button_volume_muted.png b/ui/file_manager/audio_player/assets/200/player_button_volume_muted.png deleted file mode 100644 index e0a5326a..0000000 --- a/ui/file_manager/audio_player/assets/200/player_button_volume_muted.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_cover_close.png b/ui/file_manager/audio_player/assets/200/player_cover_close.png deleted file mode 100644 index 794064d..0000000 --- a/ui/file_manager/audio_player/assets/200/player_cover_close.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_cover_open.png b/ui/file_manager/audio_player/assets/200/player_cover_open.png deleted file mode 100644 index 404e3b27..0000000 --- a/ui/file_manager/audio_player/assets/200/player_cover_open.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/player_no_artwork.png b/ui/file_manager/audio_player/assets/200/player_no_artwork.png deleted file mode 100644 index 17fe370..0000000 --- a/ui/file_manager/audio_player/assets/200/player_no_artwork.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/playlist_now_playing.png b/ui/file_manager/audio_player/assets/200/playlist_now_playing.png deleted file mode 100644 index 079bab8e..0000000 --- a/ui/file_manager/audio_player/assets/200/playlist_now_playing.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/assets/200/playlist_play.png b/ui/file_manager/audio_player/assets/200/playlist_play.png deleted file mode 100644 index 7249181..0000000 --- a/ui/file_manager/audio_player/assets/200/playlist_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/audio_player.html b/ui/file_manager/audio_player/audio_player.html deleted file mode 100644 index 29e5d90b..0000000 --- a/ui/file_manager/audio_player/audio_player.html +++ /dev/null
@@ -1,32 +0,0 @@ -<!-- - -- Copyright 2020 The Chromium Authors. All rights reserved. - -- Use of this source code is governed by a BSD-style license that can be - -- found in the LICENSE file. - --> -<!DOCTYPE HTML> -<html> -<head> - <title></title> - <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> - <link rel="stylesheet" type="text/css" href="css/audio_player.css"> - - <script type="module" src="js/main.js"></script> -</head> -<body> - <custom-style> - <style> - html { - /* Customize control-panel buttons. */ - --files-ripple-bg-color: black; - --files-toggle-ripple-bg-color: black; - --files-toggle-ripple-activated-bg-color: black; - --files-toggle-ripple-activated-opacity: 0.1; - } - </style> - </custom-style> - <div class="audio-player"> - <!-- Place the audio player. --> - <audio-player></audio-player> - </div> -</body> -</html>
diff --git a/ui/file_manager/audio_player/background.html b/ui/file_manager/audio_player/background.html deleted file mode 100644 index e6edd25..0000000 --- a/ui/file_manager/audio_player/background.html +++ /dev/null
@@ -1,4 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> - -<script type="module" src="js/main_background.js"></script>
diff --git a/ui/file_manager/audio_player/css/audio_player.css b/ui/file_manager/audio_player/css/audio_player.css deleted file mode 100644 index 07ccd70b..0000000 --- a/ui/file_manager/audio_player/css/audio_player.css +++ /dev/null
@@ -1,81 +0,0 @@ -/* Copyright 2013 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -html { - height: 100%; - /* crbug.com/812035 Remove 300ms delay for 'click' event, when using - touch interface. */ - touch-action: manipulation; -} - -body { - display: flex; - flex-direction: column; - height: 100%; - margin: 0; - overflow: hidden; - padding: 0; - user-select: none; -} - -.header { - background: #fff; - border-bottom: 1px solid #ddd; - height: 32px; -} - -div.audio-player { - border-top: 4px solid white; - box-sizing: border-box; - color: #3d3d3d; - cursor: default; - flex: 1 1 auto; - font-size: 10pt; - height: 100%; - position: relative; -} - -.audio-player:not(.collapsed):not(.single-track) > .title-button { - background-color: #1f1f1f; -} - -/* Customized scrollbar for the playlist. */ - -::-webkit-scrollbar { - height: 11px; - width: 11px; -} - -::-webkit-scrollbar-button { - height: 0; - width: 0; -} - -::-webkit-scrollbar-thumb { - background-clip: padding-box; - background-color: rgba(0, 0, 0, 0.2); - min-height: 28px; -} - -::-webkit-scrollbar-thumb:hover { - background-color: rgba(0, 0, 0, 0.3); -} - -::-webkit-scrollbar-thumb:active { - background-color: rgba(0, 0, 0, 0.4); -} - -::-webkit-scrollbar-thumb:vertical { - border-bottom: 0 solid transparent; - border-left: 5px solid transparent; - border-right: 0 solid transparent; - border-top: 0 solid transparent; -} - -::-webkit-scrollbar-track:vertical { - background-clip: padding-box; - background-color: rgba(255, 255, 255, 0.5); - border-left: 5px solid transparent; - border-right: 0 solid transparent; -}
diff --git a/ui/file_manager/audio_player/elements/BUILD.gn b/ui/file_manager/audio_player/elements/BUILD.gn deleted file mode 100644 index 9e8d7d970..0000000 --- a/ui/file_manager/audio_player/elements/BUILD.gn +++ /dev/null
@@ -1,71 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//third_party/closure_compiler/compile_js.gni") -import("//tools/polymer/html_to_js.gni") - -html_to_js("web_components") { - js_files = [ - "audio_player.js", - "control_panel.js", - "track_info_panel.js", - "track_list.js", - "repeat_button.js", - ] -} - -js_library("audio_player") { - deps = [ - ":control_panel", - ":track_info_panel", - ":track_list", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - -js_library("control_panel") { - deps = [ - ":repeat_button", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - "//ui/file_manager/file_manager/foreground/elements:files_icon_button", - "//ui/webui/resources/js:assert.m", - ] - externs_list = - [ "//ui/webui/resources/cr_elements/cr_slider/cr_slider_externs.js" ] -} - -js_library("track_info_panel") { - deps = [ - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - "//ui/webui/resources/cr_elements/cr_button:cr_button.m", - ] -} - -js_library("track_list") { - deps = [ - "//third_party/polymer/v3_0/components-chromium/paper-ripple:paper-ripple", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - ] -} - -js_library("repeat_button") { - deps = [ - "//third_party/polymer/v3_0/components-chromium/iron-behaviors:iron-button-state", - "//third_party/polymer/v3_0/components-chromium/iron-behaviors:iron-control-state", - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - "//ui/file_manager/file_manager/foreground/elements:files_toggle_ripple", - ] -} - -js_type_check("closure_compile") { - is_polymer3 = true - closure_flags = default_closure_args + [ "browser_resolver_prefix_replacements=\"chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/=../../ui/file_manager/file_manager/\"" ] - deps = [ - ":audio_player", - ":control_panel", - ":repeat_button", - ":track_info_panel", - ":track_list", - ] -}
diff --git a/ui/file_manager/audio_player/elements/audio_player.html b/ui/file_manager/audio_player/elements/audio_player.html deleted file mode 100644 index 439f7141..0000000 --- a/ui/file_manager/audio_player/elements/audio_player.html +++ /dev/null
@@ -1,52 +0,0 @@ -<!-- - -- Copyright 2015 The Chromium Authors. All rights reserved. - -- Use of this source code is governed by a BSD-style license that can be - -- found in the LICENSE file. - --> -<style> - :host { - display: flex; - flex-direction: column; - height: 100%; - justify-content: space-between; - } - - track-info-panel { - flex-grow: 0; - flex-shrink: 0; - } - - track-list { - flex-grow: 1; - flex-shrink: 1; - overflow-x: hidden; - overflow-y: scroll; - } - - control-panel { - height: 96px; - flex-shrink: 0; - } -</style> -<track-info-panel id="trackInfo" expanded="{{trackInfoExpanded}}" - aria-expand-artwork-label="[[ariaExpandArtworkLabel]]"> -</track-info-panel> -<track-list id="trackList" - expanded$="[[playlistExpanded]]" - shuffle="[[shuffle]]" - current-track-index="{{currentTrackIndex}}" - on-replay="onReplayCurrentTrack" - on-play="onPlayCurrentTrack"></track-list> -<control-panel id="audioController" - playing="{{playing}}" - time="[[time]]" - duration="[[duration]]" - shuffle="{{shuffle}}" - repeat-mode="{{repeatMode}}" - volume="{{volume}}" - playlist-expanded="{{playlistExpanded}}" - aria-labels="[[ariaLabels]]" - on-update-time="onUpdateTime_" - on-next-clicked="onControllerNextClicked" - on-previous-clicked="onControllerPreviousClicked"></control-panel> -<audio id="audio" volume="[[computeAudioVolume_(volume)]]"></audio>
diff --git a/ui/file_manager/audio_player/elements/audio_player.js b/ui/file_manager/audio_player/elements/audio_player.js deleted file mode 100644 index 7f1e2dd9..0000000 --- a/ui/file_manager/audio_player/elements/audio_player.js +++ /dev/null
@@ -1,518 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import './track_info_panel.js'; - -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -import {AriaLabels} from './control_panel.js'; -import {TrackInfo} from './track_list.js'; - -Polymer({ - _template: html`{__html_template__}`, - - is: 'audio-player', - - listeners: { - 'toggle-pause-event': 'onTogglePauseEvent_', - 'next-track-event': 'onNextTrackEvent_', - 'previous-track-event': 'onPreviousTrackEvent_', - 'small-forward-skip-event': 'onSmallForwardSkipEvent_', - 'small-backword-skip-event': 'onSmallBackwordSkipEvent_', - 'big-forward-skip-event': 'onBigForwardSkipEvent_', - 'big-backword-skip-event': 'onBigBackwordSkipEvent_', - }, - - properties: { - /** - * Flag whether the audio is playing or paused. True if playing, or false - * paused. - */ - playing: { - type: Boolean, - observer: 'playingChanged', - reflectToAttribute: true, - notify: true, - }, - - /** - * Current elapsed time in the current music in millisecond. - */ - time: Number, - - /** - * Whether the shuffle button is ON. - */ - shuffle: { - type: Boolean, - notify: true, - }, - - /** - * What mode the repeat button idicates. - * |repeatMode| can be "no-repeat", "repeat-all", or "repeat-one". - */ - repeatMode: { - type: String, - notify: true, - }, - - /** - * The audio volume. 0 is silent, and 100 is maximum loud. - */ - volume: { - type: Number, - notify: true, - }, - - /** - * Whether the playlist is expanded or not. - */ - playlistExpanded: { - type: Boolean, - notify: true, - }, - /** - * Whether the artwork is expanded or not. - */ - trackInfoExpanded: { - type: Boolean, - notify: true, - }, - - /** - * Track index of the current track. - */ - currentTrackIndex: { - type: Number, - observer: 'currentTrackIndexChanged', - }, - - /** - * URL of the current track. (exposed publicly for tests) - */ - currenttrackurl: { - type: String, - value: '', - reflectToAttribute: true, - }, - - /** - * The number of played tracks. (exposed publicly for tests) - */ - playcount: { - type: Number, - value: 0, - reflectToAttribute: true, - }, - - /** @type {AriaLabels} */ - ariaLabels: Object, - - ariaExpandArtworkLabel: String, - }, - - /** - * The last playing state when user starts dragging the seek bar. - * @private {boolean} - */ - wasPlayingOnDragStart_: false, - - /** - * Initializes an element. This method is called automatically when the - * element is ready. - */ - ready: function() { - this.$.audioController.addEventListener( - 'seeking-changed', this.onSeekingChanged_.bind(this)); - - this.$.audio.addEventListener('ended', this.onAudioEnded.bind(this)); - this.$.audio.addEventListener('error', this.onAudioError.bind(this)); - - const onAudioStatusUpdatedBound = this.onAudioStatusUpdate_.bind(this); - this.$.audio.addEventListener('timeupdate', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('ended', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('play', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('pause', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('suspend', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('abort', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('error', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('emptied', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('stalled', onAudioStatusUpdatedBound); - this.$.audio.addEventListener('loadedmetadata', onAudioStatusUpdatedBound); - }, - - /** - * Starts playing in inner audio element. - */ - play: function() { - this.$.audio.play(); - }, - - /** - * Invoked when trackList.currentTrackIndex is changed. - * @param {number} newValue new value. - * @param {number} oldValue old value. - */ - currentTrackIndexChanged: function(newValue, oldValue) { - let currentTrackUrl = ''; - - if (oldValue != newValue) { - const currentTrack = this.$.trackList.getCurrentTrack(); - if(currentTrack && currentTrack != this.$.trackInfo.track){ - this.$.trackInfo.track = currentTrack; - this.$.trackInfo.artworkAvailable = !!currentTrack.artworkUrl; - } - if (currentTrack && currentTrack.url != this.$.audio.src) { - this.$.audio.src = currentTrack.url; - currentTrackUrl = this.$.audio.src; - if (this.playing) { - this.$.audio.play(); - } - } - } - - // The attributes may be being watched, so we change it at the last. - this.currenttrackurl = currentTrackUrl; - }, - - /** - * Invoked when playing is changed. - * @param {boolean} newValue new value. - * @param {boolean} oldValue old value. - */ - playingChanged: function(newValue, oldValue) { - if (newValue) { - if (!this.$.audio.src) { - const currentTrack = this.$.trackList.getCurrentTrack(); - if (currentTrack && currentTrack.url != this.$.audio.src) { - this.$.audio.src = currentTrack.url; - } - } - - if (this.$.audio.src) { - this.currenttrackurl = this.$.audio.src; - this.$.audio.play(); - return; - } - } - - // When the new status is "stopped". - this.cancelAutoAdvance_(); - this.$.audio.pause(); - this.currenttrackurl = ''; - }, - - /** - * Invoked when the next button in the controller is clicked. - * This handler is registered in the 'on-click' attribute of the element. - */ - onControllerNextClicked: function() { - this.advance_(true /* forward */, true /* repeat */); - }, - - /** - * Invoked when the previous button in the controller is clicked. - * This handler is registered in the 'on-click' attribute of the element. - */ - onControllerPreviousClicked: function() { - this.advance_(false /* forward */, true /* repeat */); - }, - - /** - * Invoked when the playback in the audio element is ended. - * This handler is registered in this.ready(). - */ - onAudioEnded: function() { - this.playcount++; - if (this.repeatMode === 'repeat-one') { - this.playing = true; - this.$.audio.currentTime = 0; - this.time = 0; - return; - } - this.advance_(true /* forward */, this.repeatMode === 'repeat-all'); - }, - - /** - * Invoked when the playback in the audio element gets error. - * This handler is registered in this.ready(). - */ - onAudioError: function() { - if (this.repeatMode === 'repeat-one') { - this.playing = false; - return; - } - this.scheduleAutoAdvance_( - true /* forward */, this.repeatMode === 'repeat-all'); - }, - - /** - * Invoked when the time of playback in the audio element is updated. - * This handler is registered in this.ready(). - * @private - */ - onAudioStatusUpdate_: function() { - this.playing = !this.$.audio.paused; - // If we're paused due to drag, do not update time. - if (this.playing) { - this.time = this.$.audio.currentTime * 1000; - } - if (!Number.isNaN(this.$.audio.duration)) { - this.duration = this.$.audio.duration * 1000; - } - }, - - /** - * Invoked when receivig a request to start playing the current music. - */ - onPlayCurrentTrack: function() { - this.$.audio.play(); - }, - - /** - * Invoked when receiving a request to replay the current music from the track - * list element. - */ - onReplayCurrentTrack: function() { - // Changes the current time back to the beginning, regardless of the current - // status (playing or paused). - this.$.audio.currentTime = 0; - this.time = 0; - this.$.audio.play(); - }, - - /** - * Goes to the previous or the next track. - * @param {boolean} forward True if next, false if previous. - * @param {boolean} repeat True if repeat-mode is "repeat-all". False - * "no-repeat". - * @private - */ - advance_: function(forward, repeat) { - this.cancelAutoAdvance_(); - - const nextTrackIndex = this.$.trackList.getNextTrackIndex(forward, true); - const isNextTrackAvailable = - (this.$.trackList.getNextTrackIndex(forward, repeat) !== -1); - - this.playing = isNextTrackAvailable; - - const shouldFireEvent = - this.$.trackList.currentTrackIndex === nextTrackIndex; - this.$.trackList.currentTrackIndex = nextTrackIndex; - this.$.audio.currentTime = 0; - this.time = 0; - // If the next track and current track is the same, - // the event will not be fired. - // So we will fire the event here. - // This happenes if there is only one song. - if (shouldFireEvent) { - this.$.trackList.fire('current-track-index-changed'); - } - }, - - /** - * Timeout ID of auto advance. Used internally in scheduleAutoAdvance_() and - * cancelAutoAdvance_(). - * @type {number?} - * @private - */ - autoAdvanceTimer_: null, - - /** - * Schedules automatic advance to the next track after a timeout. - * @param {boolean} forward True if next, false if previous. - * @param {boolean} repeat True if repeat-mode is enabled. False otherwise. - * @private - */ - scheduleAutoAdvance_: function(forward, repeat) { - this.cancelAutoAdvance_(); - const currentTrackIndex = this.currentTrackIndex; - - const timerId = setTimeout(() => { - // If the other timer is scheduled, do nothing. - if (this.autoAdvanceTimer_ !== timerId) { - return; - } - - this.autoAdvanceTimer_ = null; - - // If the track has been changed since the advance was scheduled, do - // nothing. - if (this.currentTrackIndex !== currentTrackIndex) { - return; - } - - // We are advancing only if the next track is not known to be invalid. - // This prevents an endless auto-advancing in the case when all tracks - // are invalid (we will only visit each track once). - this.advance_(forward, repeat); - }, 3000); - - this.autoAdvanceTimer_ = timerId; - }, - - /** - * Cancels the scheduled auto advance. - * @private - */ - cancelAutoAdvance_: function() { - if (this.autoAdvanceTimer_) { - clearTimeout(this.autoAdvanceTimer_); - this.autoAdvanceTimer_ = null; - } - }, - - /** - * The list of the tracks in the playlist. - * - * When it changed, current operation including playback is stopped and - * restarts playback with new tracks if necessary. - * - * @type {Array<TrackInfo>} - */ - get tracks() { - return this.$.trackList ? this.$.trackList.tracks : null; - }, - set tracks(tracks) { - if (this.$.trackList.tracks === tracks) { - return; - } - - this.cancelAutoAdvance_(); - - this.$.trackList.tracks = tracks; - const currentTrack = this.$.trackList.getCurrentTrack(); - if (currentTrack && currentTrack.url != this.$.audio.src) { - this.$.audio.src = currentTrack.url; - this.$.audio.play(); - } - }, - - /** - * Notifis the track-list element that the metadata for specified track is - * updated. - * @param {number} index The index of the track whose metadata is updated. - */ - notifyTrackMetadataUpdated: function(index) { - if (index < 0 || index >= this.tracks.length) { - return; - } - - this.$.trackList.notifyPath('tracks.' + index + '.title', - this.tracks[index].title); - this.$.trackList.notifyPath('tracks.' + index + '.artist', - this.tracks[index].artist); - - if (this.$.trackInfo.track && - this.$.trackInfo.track.url === this.tracks[index].url){ - this.$.trackInfo.notifyPath('track.title', this.tracks[index].title); - this.$.trackInfo.notifyPath('track.artist', this.tracks[index].artist); - const artworkUrl = this.tracks[index].artworkUrl; - if (artworkUrl) { - this.$.trackInfo.notifyPath('track.artworkUrl', - this.tracks[index].artworkUrl); - this.$.trackInfo.artworkAvailable = true; - } else { - this.$.trackInfo.notifyPath('track.artworkUrl', undefined); - this.$.trackInfo.artworkAvailable = false; - } - } - }, - - /** - * Invoked when the audio player is being unloaded. - */ - onPageUnload: function() { - this.$.audio.src = ''; // Hack to prevent crashing. - }, - - /** - * Invoked when dragging state of seek bar on control panel is changed. - * During the user is dragging it, audio playback is paused temporarily. - * @param {!Event} e - */ - onSeekingChanged_: function(e) { - e = /** @type {!CustomEvent<{value: boolean}>} */ (e); - if (e.detail.value && this.playing) { - this.$.audio.pause(); - this.wasPlayingOnDragStart_ = true; - return; - } - - if (!e.detail.value && this.wasPlayingOnDragStart_) { - this.wasPlayingOnDragStart_ = false; - this.$.audio.play(); - } - }, - - /** - * @param {!CustomEvent<number>} e - * @private - */ - onUpdateTime_: function(e) { - this.$.audio.currentTime = e.detail / 1000; - this.time = e.detail; - }, - - /** - * Computes volume value for audio element. (should be in [0.0, 1.0]) - * @param {number} volume Volume which is set in the UI. ([0, 100]) - * @return {number} - */ - computeAudioVolume_: function(volume) { - return volume / 100; - }, - - /** - * Toggle pause. - * @private - */ - onTogglePauseEvent_: function() { - this.$.audioController.playClick(); - }, - - /** - * Small skip forward. - * @private - */ - onSmallForwardSkipEvent_: function() { - this.$.audioController.smallSkip(true); - }, - - /** - * Small skip backword. - * @private - */ - onSmallBackwordSkipEvent_: function() { - this.$.audioController.smallSkip(false); - }, - - /** - * Big skip forward. - * @private - */ - onBigForwardSkipEvent_: function() { - this.$.audioController.bigSkip(true); - }, - - /** - * Big skip backword. - * @private - */ - onBigBackwordSkipEvent_: function() { - this.$.audioController.bigSkip(false); - }, - - /** @private */ - onNextTrackEvent_: function() { - this.onControllerNextClicked(); - }, - - /** @private */ - onPreviousTrackEvent_: function() { - this.onControllerPreviousClicked(); - }, -});
diff --git a/ui/file_manager/audio_player/elements/control_panel.html b/ui/file_manager/audio_player/elements/control_panel.html deleted file mode 100644 index 45b7206..0000000 --- a/ui/file_manager/audio_player/elements/control_panel.html +++ /dev/null
@@ -1,267 +0,0 @@ -<!-- - -- Copyright 2015 The Chromium Authors. All rights reserved. - -- Use of this source code is governed by a BSD-style license that can be - -- found in the LICENSE file. - --> - -<style> - /* Controls bar. */ - .controls { - align-items: center; - background-color: white; - display: flex; - flex-direction: column; - height: 96px; - justify-content: center; - padding: 0; - } - - .controls .upper-controls, - .controls .lower-controls { - box-sizing: border-box; - height: 48px; - padding: 8px; - width: 100%; - } - - .audio-controls { - align-items: center; - display: flex; - flex-direction: row; - justify-content: center; - padding: 0; - } - - /* Customized scrollbar for the playlist. */ - - .media-button { - background-color: transparent; - border: 0; - flex: none; - height: 32px; - outline: none; /* TODO(yoshiki): Show outline only on keyboard focus. */ - padding: 0; - position: relative; - width: 32px; - } - - .media-button > div, - .media-button.toggle > label > span { - background-position: center; - background-repeat: no-repeat; - display: inline-block; - height: 100%; - pointer-events: none; - transition: opacity 100ms linear; - width: 100%; - } - - .media-button > div { - left: 0; - opacity: 0; - position: absolute; - top: 0; - } - - /* Time and volume controls. */ - - .time-volume-controls { - align-items: center; - display: flex; - flex-direction: row; - height: 100%; - justify-content: center; - } - - .time-volume-controls > .time-container { - color: rgb(51, 51, 51); - cursor: default; - flex: none; - font-size: 12px; - padding: 8px; - position: relative; - } - - .time-container > .time { - position: absolute; - right: 8px; /* Should be same as time-container's right padding. */ - top: 8px; /* Should be same as time-container's top padding. */ - } - - .time-container > .time-spacer { - opacity: 0; /* This class is intended to be used as invisible spacer. */ - } - - .time-volume-controls > cr-slider { - --cr-slider-active-color: rgb(66, 133, 244); - --cr-slider-knob-color-rgb: 64, 138, 241; - } - - cr-slider { - cursor: pointer; - } - - #timeSlider { - flex: 3 1 auto; - width: 118px; - } - - #volumeSlider { - flex: 1 1 auto; - width: 82px; - } - - /* Media controls in order of appearance. */ - - .audio-controls { - align-items: center; - display: flex; - flex-direction: row; - height: 100%; - justify-content: center; - } - - /* Play/pause button. */ - - .media-button.toggle input { - position: absolute; - visibility: hidden; - } - - .media-button.shuffle-mode { - background-image: -webkit-image-set( - url(../assets/100/player_button_shuffle.png) 1x, - url(../assets/200/player_button_shuffle.png) 2x); - pointer-events: auto; - } - - .media-button.repeat-mode { - margin-left: 8px; - margin-right: 0; - } - - .media-button.play { - margin-left: 4px; - margin-right: 4px; - } - - .media-button.play { - background-image: -webkit-image-set( - url(../assets/100/player_button_play.png) 1x, - url(../assets/200/player_button_play.png) 2x); - } - - :host([playing]) .media-button.play { - background-image: -webkit-image-set( - url(../assets/100/player_button_pause.png) 1x, - url(../assets/200/player_button_pause.png) 2x); - } - - .media-button.previous { - background-image: -webkit-image-set( - url(../assets/100/player_button_previous.png) 1x, - url(../assets/200/player_button_previous.png) 2x); - margin-left: 8px; - margin-right: 0; - } - - .media-button.next { - background-image: -webkit-image-set( - url(../assets/100/player_button_next.png) 1x, - url(../assets/200/player_button_next.png) 2x); - margin-left: 0; - margin-right: 8px; - } - - .media-button.playlist { - background-image: -webkit-image-set( - url(../assets/100/player_button_playlist.png) 1x, - url(../assets/200/player_button_playlist.png) 2x); - pointer-events: auto; - } - - .media-button.volume { - background-image: -webkit-image-set( - url(../assets/100/player_button_volume.png) 1x, - url(../assets/200/player_button_volume.png) 2x); - pointer-events: auto; - } - - :host([volume='0']) .media-button.volume { - background-image: -webkit-image-set( - url(../assets/100/player_button_volume_muted.png) 1x, - url(../assets/200/player_button_volume_muted.png) 2x); - } - - /* Invisible div used to compute the width required for the elapsed time. */ - .time-controls > .time > .current { - align-items: center; - display: flex; - flex-direction: row; - height: 100%; - justify-content: flex-end; - position: absolute; - top: -1px; - } -</style> -<div class="controls"> - <div class="upper-controls audio-controls"> - <!-- Shuffle toggle button in the bottom line. --> - <files-icon-button toggles - id="shuffle" - class="shuffle-mode media-button toggle" - active="{{shuffle}}"> - </files-icon-button> - - <!-- RepeatMode toggle button in the bottom line. --> - <repeat-button - id="repeat" - class="repeat-mode media-button" - repeat-mode="{{repeatMode}}"> - </repeat-button> - - <!-- Prev button in the bottom line. --> - <files-icon-button - id="previous" - class="previous media-button" - on-click="previousClick"> - </files-icon-button> - - <!-- Play button in the bottom line. --> - <files-icon-button - id="play" - class="play media-button" - on-click="playClick"> - </files-icon-button> - - <!-- Next button in the bottom line. --> - <files-icon-button - id="next" - class="next media-button" - on-click="nextClick"> - </files-icon-button> - - <!-- Playlist button in the bottom line. --> - <files-icon-button toggles - id="playList" - class="playlist media-button toggle" - active="{{playlistExpanded}}"> - </files-icon-button> - </div> - <div class="lower-controls time-volume-controls"> - <!-- Play/pause button and seek slider in the bottom line. --> - <div class="time-container"> - <div class="time-spacer">[[computeTimeString_(duration, duration)]]</div> - <div class="time">[[computeTimeString_(time, duration)]]</div> - </div> - <cr-slider id="timeSlider" max="[[duration]]" value="[[time]]" - on-dragging-changed="onSeekingChanged_" no-keybindings></cr-slider> - <!-- Volume button and slider in the bottom line. --> - <files-icon-button - id="volumeButton" - class="volume media-button" - on-click="volumeClick"> - </files-icon-button> - <cr-slider id="volumeSlider"></cr-slider> - </div> -</div>
diff --git a/ui/file_manager/audio_player/elements/control_panel.js b/ui/file_manager/audio_player/elements/control_panel.js deleted file mode 100644 index ce13a14..0000000 --- a/ui/file_manager/audio_player/elements/control_panel.js +++ /dev/null
@@ -1,281 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/elements/files_icon_button.js'; -import './repeat_button.js'; -import 'chrome://resources/cr_elements/cr_slider/cr_slider.js'; - -import {assert} from 'chrome://resources/js/assert.m.js'; -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - - -/** - * @typedef {?{ - * mute: string, - * next: string, - * pause: string, - * play: string, - * playList: string, - * previous: string, - * repeat: string, - * seekSlider: string, - * shuffle: string, - * unmute: string, - * volumeSlider: string, - * }} - */ -export let AriaLabels; - -Polymer({ - _template: html`{__html_template__}`, - - is: 'control-panel', - - properties: { - /** - * Flag whether the audio is playing or paused. True if playing, or false - * paused. - */ - playing: { - type: Boolean, - value: false, - notify: true, - reflectToAttribute: true, - observer: 'playingChanged_', - }, - - /** - * Current elapsed time in the current music in millisecond. - */ - time: { - type: Number, - value: 0, - }, - - /** - * Total length of the current music in millisecond. - */ - duration: { - type: Number, - value: 0, - }, - - /** - * Whether the shuffle button is ON. - */ - shuffle: { - type: Boolean, - value: false, - notify: true, - }, - - /** - * What mode the repeat button indicates. - * repeat-modes can be "no-repeat", "repeat-all", "repeat-one". - */ - repeatMode: { - type: String, - value: 'no-repeat', - notify: true, - }, - - /** - * The audio volume. 0 is silent, and 100 is maximum loud. - */ - volume: { - type: Number, - value: 50, - notify: true, - reflectToAttribute: true, - observer: 'volumeChanged_', - }, - - /** - * Whether the playlist is expanded or not. - */ - playlistExpanded: { - type: Boolean, - value: false, - notify: true, - }, - - /** - * Whether the knob of time slider is being dragged. - */ - dragging: { - type: Boolean, - value: false, - notify: true, - }, - - /** - * Dictionary which contains aria-labels for each controls. - * @type {AriaLabels} - */ - ariaLabels: { - type: Object, - observer: 'ariaLabelsChanged_', - }, - }, - - /** - * Initializes an element. This method is called automatically when the - * element is ready. - */ - ready: function() { - const timeSlider = /** @type {!CrSliderElement} */ (this.$.timeSlider); - timeSlider.addEventListener('cr-slider-value-changed', () => { - this.fire('update-time', timeSlider.value); - }); - - const volumeSlider = - /** @type {!CrSliderElement} */ (this.$.volumeSlider); - volumeSlider.addEventListener('cr-slider-value-changed', () => { - this.volume = volumeSlider.value; - }); - }, - - /** - * Invoked when the next button is clicked. - */ - nextClick: function() { - this.fire('next-clicked'); - }, - - /** - * Invoked when the play button is clicked. - */ - playClick: function() { - this.playing = !this.playing; - }, - - /** - * Invoked when the previous button is clicked. - */ - previousClick: function() { - this.fire('previous-clicked'); - }, - - /** - * Invoked when the volume button is clicked. - */ - volumeClick: function() { - if (this.volume !== 0) { - this.savedVolume_ = this.volume; - this.volume = 0; - } else { - this.volume = this.savedVolume_ || 50; - } - }, - - /** - * @param {boolean} forward Whether to skip forward/backword. - */ - smallSkip: function(forward) { - this.skip_(true /* small */, forward); - }, - - /** - * @param {boolean} forward Whether to skip forward/backword. - */ - bigSkip: function(forward) { - this.skip_(false /* small */, forward); - }, - - /** - * Skips small min(5 seconds, 10% of duration) or large - * min(10 seconds, 20% of duration). - * @param {boolean} small Whether to skip small/large interval. - * @param {boolean} forward Whether to skip forward/backword. - * @private - */ - skip_: function(small, forward) { - const maxSkip = small ? 5000 : 10000; - const percentOfDuration = (small ? .1 : .2) * this.duration; - const update = (forward ? 1 : -1) * Math.min(maxSkip, percentOfDuration); - if (this.duration > 0) { - this.fire( - 'update-time', - Math.max(Math.min(this.time + update, this.duration), 0)); - } - }, - - /** - * Converts the time into human friendly string. - * @param {number} time Time to be converted. - * @return {string} String representation of the given time - */ - time2string_: function(time) { - return ~~(time / 60000) + ':' + ('0' + ~~(time / 1000 % 60)).slice(-2); - }, - - /** - * Converts the time and duration into human friendly string. - * @param {number} time Time to be converted. - * @param {number} duration Duration to be converted. - * @return {string} String representation of the given time - */ - computeTimeString_: function(time, duration) { - return this.time2string_(time) + ' / ' + this.time2string_(duration); - }, - - /** - * Invoked when the playing property is changed. - * @param {boolean} playing - * @private - */ - playingChanged_: function(playing) { - if (this.ariaLabels) { - this.$.play.setAttribute( - 'aria-label', playing ? this.ariaLabels.pause : this.ariaLabels.play); - } - }, - - /** - * Invoked when the volume property is changed. - * @param {number} volume - * @private - */ - volumeChanged_: function(volume) { - if (!this.$.volumeSlider.dragging) { - this.$.volumeSlider.value = volume; - } - - if (this.ariaLabels) { - this.$.volumeButton.setAttribute( - 'aria-label', - volume !== 0 ? this.ariaLabels.mute : this.ariaLabels.unmute); - } - }, - - /** - * @param {!CustomEvent<{value: boolean}>} e - * @private - */ - onSeekingChanged_: function(e) { - this.fire('seeking-changed', e.detail); - }, - - /** - * Invoked when the ariaLabels property is changed. - * @param {Object} ariaLabels - * @private - */ - ariaLabelsChanged_: function(ariaLabels) { - assert(ariaLabels); - // TODO(fukino): Use data bindings. - this.$.volumeSlider.setAttribute('aria-label', ariaLabels.volumeSlider); - this.$.shuffle.setAttribute('aria-label', ariaLabels.shuffle); - this.$.repeat.setAttribute('aria-label', ariaLabels.repeat); - this.$.previous.setAttribute('aria-label', ariaLabels.previous); - this.$.play.setAttribute( - 'aria-label', this.playing ? ariaLabels.pause : ariaLabels.play); - this.$.next.setAttribute('aria-label', ariaLabels.next); - this.$.playList.setAttribute('aria-label', ariaLabels.playList); - this.$.timeSlider.setAttribute('aria-label', ariaLabels.seekSlider); - this.$.volumeButton.setAttribute( - 'aria-label', this.volume !== 0 ? ariaLabels.mute : ariaLabels.unmute); - this.$.volumeSlider.setAttribute('aria-label', ariaLabels.volumeSlider); - }, -});
diff --git a/ui/file_manager/audio_player/elements/repeat_button.html b/ui/file_manager/audio_player/elements/repeat_button.html deleted file mode 100644 index c0585f7..0000000 --- a/ui/file_manager/audio_player/elements/repeat_button.html +++ /dev/null
@@ -1,45 +0,0 @@ -<!-- Copyright 2016 The Chromium Authors. All rights reserved. - -- Use of this source code is governed by a BSD-style license that can be - -- found in the LICENSE file. - --> - -<style> - :host { - border-radius: 2px; - cursor: pointer; - display: inline-block; - height: 32px; - outline: none; - position: relative; - width: 32px; - } - - .repeat-all, .no-repeat { - background-image: -webkit-image-set( - url(../assets/100/player_button_repeat.png) 1x, - url(../assets/200/player_button_repeat.png) 2x); - } - - .repeat-one { - background-image: -webkit-image-set( - url(../assets/100/player_button_repeat_one.png) 1x, - url(../assets/200/player_button_repeat_one.png) 2x); - } - - files-toggle-ripple { - background-position: center; - background-repeat: no-repeat; - height: 28px; - left: 2px; - pointer-events: none; - position: absolute; - top: 2px; - width: 28px; - } - - :host(.keyboard-focus) { - /* We use box-shadow rather than outline to make it rounded. */ - box-shadow: 0 0 0 1px rgba(66, 133, 244, 0.5); - } -</style> -<files-toggle-ripple activated="[[isActive(repeatMode)]]" class$="{{repeatMode}}"></files-toggle-ripple>
diff --git a/ui/file_manager/audio_player/elements/repeat_button.js b/ui/file_manager/audio_player/elements/repeat_button.js deleted file mode 100644 index 92e3bb77..0000000 --- a/ui/file_manager/audio_player/elements/repeat_button.js +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * Repeat Button. - * - * This is for repeat button in Control Panel for Audio Player. - */ -import 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/elements/files_toggle_ripple.js'; - -import {IronButtonState} from 'chrome://resources/polymer/v3_0/iron-behaviors/iron-button-state.js'; -import {IronControlState} from 'chrome://resources/polymer/v3_0/iron-behaviors/iron-control-state.js'; -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -Polymer({ - _template: html`{__html_template__}`, - - is: 'repeat-button', - - hostAttributes: { - role: 'button', - tabindex: 0, - }, - - behaviors: [ - IronButtonState, - IronControlState, - ], - - properties: { - 'repeatMode': { - type: String, - notify: true, - reflectToAttribute: true, - }, - }, - - listeners: { - click: '_clickHandler', - }, - - observers: [ - '_focusedChanged(receivedFocusFromKeyboard)', - ], - - _focusedChanged: function(receivedFocusFromKeyboard) { - if (receivedFocusFromKeyboard) { - this.classList.add('keyboard-focus'); - } else { - this.classList.remove('keyboard-focus'); - } - }, - - /** - * Initialize member variables. - */ - created: function() { - /** - * @private {Array<string>} - */ - this.modeName_ = [ - 'no-repeat', - 'repeat-all', - 'repeat-one', - ]; - }, - - _clickHandler: function() { - this.next_(); - }, - - /** - * Change the mode into next one. - * @private - */ - next_: function() { - this.index_ = this.index_ || this.modeName_.indexOf(this.repeatMode); - if (this.index_ === -1) { - return; - } - - const nextIndex = (this.index_ + 1) % this.modeName_.length; - this.repeatMode = this.modeName_[nextIndex]; - this.index_ = nextIndex; - }, - - /** - * Whether or not the button is active, which means it should be toggled. - * @param {string} mode Current mode name - * @return {boolean} True if the mode is repeat. - */ - isActive: function(mode) { - return mode === 'repeat-all' || mode === 'repeat-one'; - }, -});
diff --git a/ui/file_manager/audio_player/elements/track_info_panel.html b/ui/file_manager/audio_player/elements/track_info_panel.html deleted file mode 100644 index 629aa73..0000000 --- a/ui/file_manager/audio_player/elements/track_info_panel.html +++ /dev/null
@@ -1,171 +0,0 @@ -<!-- - -- Copyright 2016 The Chromium Authors. All rights reserved. - -- Use of this source code is governed by a BSD-style license that can be - -- found in the LICENSE file. - --> - -<style> - :host { - align-items: center; - background: rgb(245, 245, 245); - color: rgb(51, 51, 51); - cursor: default; - font-size: 10pt; - overflow: hidden; - } - - /* Track item. */ - .track { - align-items: center; - background-color: rgba(255, 255, 255, 1.0); - display: flex; - height: 48px; - justify-content: space-between; - width: 100%; - } - - :host([expanded]) .track { - background-color: rgba(255, 255, 255, 0.9); - bottom: 0; - position: absolute; - } - - /* artwork icon(expanded) */ - .track .icon-wrapper { - flex: none; - height: 48px; - width: 48px; - } - - :host([expanded]) .icon { - visibility: hidden; - } - - :host(:not([expanded])) .icon { - background-position: center; - background-repeat: no-repeat; - background-size: contain; - height: 48px; - pointer-events: none; - position: absolute; - width: 48px; - } - - /* artwork icon(expanded) */ - - .track-wrapper { - background-color: rgb(32, 32, 34); - position: relative; - } - - :host(:not([artwork-available])[expanded]) .track-wrapper { - height: 320px; - position: relative; - width: 100%; - } - - .icon-expanded { - background-size: 0 0; - } - - :host(:not([expanded])) .icon-unavailable-expanded { - background-size: 0 0; - } - - :host(:not([artwork-available])[expanded]) .icon-unavailable-expanded { - background-image: -webkit-image-set( - url(../assets/100/player_no_artwork.png) 1x, - url(../assets/200/player_no_artwork.png) 2x); - background-position: center; - background-repeat: no-repeat; - height: calc(320px - 48px); - margin-left: auto; - margin-right: auto; - width: 320px; - } - - :host([artwork-available][expanded]) .icon-expanded { - background-position: center; - background-repeat: no-repeat; - background-size: contain; - height: 320px; - margin-left: auto; - margin-right: auto; - width: 320px; - } - - /* expand icon. */ - .track .expand { - --ink-color: rgb(51, 51, 51); - background-color: transparent; - background-position: center; - background-repeat: no-repeat; - border: none; - border-radius: 0; - box-shadow: none; - flex: none; - height: 48px; - width: 48px; - } - - :host-context(.focus-outline-visible) .track .expand:focus { - background-color: rgba(153, 153, 153, .2); - } - - :host(:not([expanded])) .track .expand { - background-image: -webkit-image-set( - url(../assets/100/player_cover_open.png) 1x, - url(../assets/200/player_cover_open.png) 2x); - } - - :host([expanded]) .track .expand { - background-image: -webkit-image-set( - url(../assets/100/player_cover_close.png) 1x, - url(../assets/200/player_cover_close.png) 2x); - } - - /* Track data. */ - - .track .data { - display: flex; - flex-direction: column; - justify-content: space-around; - min-width: 0; - } - - .track .data .data-title, - .track .data .data-artist { - flex: auto; - overflow: hidden; - text-align: center; - text-overflow: ellipsis; - white-space: nowrap; - } - - .track .data .data-title { - color: rgb(51, 51, 51); - font-size: 13px; - font-weight: 500; - } - - .track .data .data-artist { - color: rgb(100, 100, 100); - font-size: 12px; - } - </style> -<div class="track-wrapper"> - <div class="icon-unavailable-expanded"></div> - <div class="icon-expanded" style="background-image: url([[track.artworkUrl]]);"></div> - <div class="track"> - <div class="icon-wrapper"> - <div class="icon" style="background-image: url([[track.artworkUrl]]);"></div> - </div> - <div class="data"> - <div class="data-title">[[track.title]]</div> - <div class="data-artist">[[track.artist]]</div> - </div> - <cr-button id="expand" class="expand" on-click="onExpandClick_" - aria-expanded="false" aria-label$="[[ariaExpandArtworkLabel]]"> - </cr-button> - </div> -</div>
diff --git a/ui/file_manager/audio_player/elements/track_info_panel.js b/ui/file_manager/audio_player/elements/track_info_panel.js deleted file mode 100644 index 7924441..0000000 --- a/ui/file_manager/audio_player/elements/track_info_panel.js +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; - -import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - - -Polymer({ - _template: html`{__html_template__}`, - - is: 'track-info-panel', - - properties: { - track: { - type: Object, - value: null, - }, - - expanded: { - type: Boolean, - value: false, - notify: true, - reflectToAttribute: true, - observer: 'onExpandedChanged_', - }, - - artworkAvailable: { - type: Boolean, - value: false, - reflectToAttribute: true, - }, - - ariaExpandArtworkLabel: String, - }, - - /** @private */ - onExpandClick_: function() { - this.expanded = !this.expanded; - }, - - /** @private */ - onExpandedChanged_: function() { - this.$.expand.setAttribute('aria-expanded', Boolean(this.expanded)); - }, -});
diff --git a/ui/file_manager/audio_player/elements/track_list.html b/ui/file_manager/audio_player/elements/track_list.html deleted file mode 100644 index 057ac8d..0000000 --- a/ui/file_manager/audio_player/elements/track_list.html +++ /dev/null
@@ -1,104 +0,0 @@ - -<style> - :host { - align-items: center; - background: rgb(245, 245, 245); - color: rgb(51, 51, 51); - cursor: default; - display: flex; - flex-direction: column; - font-size: 10pt; - justify-content: flex-start; - overflow-x: hidden; - overflow-y: auto; - } - - /* Track item. */ - .track { - align-items: center; - display: flex; - flex: 0 0 auto; - flex-direction: row; - height: 48px; - justify-content: flex-start; - position: relative; - width: 100%; - } - - :host([expanded]) > .track:hover { - background-color: rgba(0, 0, 0, 0.08); - } - - /* Track icon. */ - .track .icon { - background-position: center; - background-repeat: no-repeat; - flex: none; - height: 32px; - margin: 8px; - pointer-events: none; - width: 32px; - } - - .track:hover .icon { - background-image: -webkit-image-set( - url(../assets/100/playlist_play.png) 1x, - url(../assets/200/playlist_play.png) 2x); - pointer-events: auto; - } - - .track[active] .icon { - background-image: -webkit-image-set( - url(../assets/100/playlist_now_playing.png) 1x, - url(../assets/200/playlist_now_playing.png) 2x); - } - - /* Track data. */ - - .track .data { - display: flex; - flex: 1 1 auto; - flex-direction: column; - justify-content: center; - margin-left: 0; - margin-right: 4px; - min-width: 0; - } - - .track .data .data-title, - .track .data .data-artist { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .track .data .data-title { - color: rgb(51, 51, 51); - font-size: 13px; - font-weight: 500; - } - - .track .data .data-artist { - color: rgb(100, 100, 100); - font-size: 12px; - } - - paper-ripple { - bottom: 0; - color: rgb(51, 51, 51); - left: 0; - position: absolute; - right: 0; - top: 0; - } -</style> -<template is="dom-repeat" id="tracks" items="[[tracks]]"> - <div class="track" active$="[[item.active]]" index$="[[index]]" on-click="trackClicked"> - <div class="icon"></div> - <div class="data"> - <div class="data-title">[[item.title]]</div> - <div class="data-artist">[[item.artist]]</div> - </div> - <paper-ripple initial-opacity="0.08"></paper-ripple> - </div> -</template>
diff --git a/ui/file_manager/audio_player/elements/track_list.js b/ui/file_manager/audio_player/elements/track_list.js deleted file mode 100644 index 57bb54b..0000000 --- a/ui/file_manager/audio_player/elements/track_list.js +++ /dev/null
@@ -1,302 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {Polymer, html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import 'chrome://resources/polymer/v3_0/paper-ripple/paper-ripple.js'; - - -/** - * @typedef {?{ - * url: string, - * title: string, - * artist: string, - * artworkUrl: string, - * active: boolean - * }} - */ -export let TrackInfo; - -Polymer({ - _template: html`{__html_template__}`, - - is: 'track-list', - - properties: { - /** - * List of tracks. - */ - tracks: { - type: Array, - value: [], - observer: 'tracksChanged', - }, - - /** - * Track index of the current track. - * If the tracks property is empty, it should be -1. Otherwise, be a valid - * track number. - */ - currentTrackIndex: { - type: Number, - value: -1, - observer: 'currentTrackIndexChanged', - notify: true, - }, - - /** - * Whether shuffling play order is enabled or not. - */ - shuffle: { - type: Boolean, - value: false, - observer: 'shuffleChanged', - }, - - /** - * Whether playlist is expanded or not. - */ - expanded: { - type: Boolean, - value: false, - observer: 'expandedChanged', - }, - }, - - /** - * Play order of the tracks. Each value is the index of 'this.tracks'. - * @type {Array<number>} - */ - playOrder: [], - - /** - * Invoked when 'expanded' property is changed. - * @param {boolean} newValue New value. - * @param {boolean} oldValue Old value. - */ - expandedChanged: function(newValue, oldValue) { - this.ensureTrackInViewport_(this.currentTrackIndex); - }, - - /** - * Invoked when 'shuffle' property is changed. - * @param {boolean} newValue New value. - * @param {boolean} oldValue Old value. - */ - shuffleChanged: function(newValue, oldValue) { - this.generatePlayOrder(true /* keep the current track */); - }, - - /** - * Invoked when the current track index is changed. - * @param {number} newValue new value. - * @param {number} oldValue old value. - */ - currentTrackIndexChanged: function(newValue, oldValue) { - if (oldValue === newValue) { - return; - } - - if (!isNaN(oldValue) && 0 <= oldValue && oldValue < this.tracks.length) { - this.set('tracks.' + oldValue + '.active', false); - } - - if (0 <= newValue && newValue < this.tracks.length) { - const currentPlayOrder = this.playOrder.indexOf(newValue); - if (currentPlayOrder !== -1) { - // Success - this.set('tracks.' + newValue + '.active', true); - - this.ensureTrackInViewport_(newValue /* trackIndex */); - return; - } - } - - // Invalid index - if (this.tracks.length === 0) { - this.currentTrackIndex = -1; - } else { - this.generatePlayOrder(false /* no need to keep the current track */); - } - }, - - /** - * Invoked when 'tracks' property is changed. - * @param {Array<!TrackInfo>} newValue New value. - * @param {Array<!TrackInfo>} oldValue Old value. - */ - tracksChanged: function(newValue, oldValue) { - // Note: Sometimes both oldValue and newValue are null though the actual - // values are not null. Maybe it's a bug of Polymer. - - if (this.tracks.length !== 0) { - // Restore the active track. - if (this.currentTrackIndex !== -1 && - this.currentTrackIndex < this.tracks.length) { - this.set('tracks.' + this.currentTrackIndex + '.active', true); - } - - // Reset play order and current index. - this.generatePlayOrder(false /* no need to keep the current track */); - } else { - this.playOrder = []; - this.currentTrackIndex = -1; - } - }, - - /** - * Invoked when the track element is clicked. - * @param {Event} event Click event. - */ - trackClicked: function(event) { - const index = ~~event.currentTarget.getAttribute('index'); - const track = this.tracks[index]; - if (track) { - this.selectTrack(track); - } - }, - - /** - * Scrolls the track list to ensure the given track in the viewport. - * @param {number} trackIndex The index of the track to be in the viewport. - * @private - */ - ensureTrackInViewport_: function(trackIndex) { - const trackElement = this.$$('.track[index="' + trackIndex + '"]'); - if (trackElement) { - const viewTop = this.scrollTop; - const viewHeight = this.clientHeight; - const elementTop = trackElement.offsetTop - this.offsetTop; - const elementHeight = trackElement.offsetHeight; - - if (elementTop <= viewTop) { - // Adjust the tops. - this.scrollTop = elementTop; - } else if (elementTop + elementHeight >= viewTop + viewHeight) { - // Adjust the bottoms. - this.scrollTop = Math.max(0, (elementTop + elementHeight - viewHeight)); - } else { - // The entire element is in the viewport. Do nothing. - } - } - }, - - /** - * Invoked when the track element is clicked. - * @param {boolean} keepCurrentTrack Keep the current track or not. - */ - generatePlayOrder: function(keepCurrentTrack) { - console.assert( - (keepCurrentTrack !== undefined), - 'The argument "forward" is undefined'); - - if (this.tracks.length === 0) { - this.playOrder = []; - return; - } - - // Creates sequenced array. - this.playOrder = this.tracks.map(function(unused, index) { - return index; - }); - - if (this.shuffle) { - // Randomizes the play order array (Schwarzian-transform algorithm). - this.playOrder = this.playOrder - .map(function(a) { - return {weight: Math.random(), index: a}; - }) - .sort(function(a, b) { - return a.weight - b.weight; - }) - .map(function(a) { - return a.index; - }); - - if (keepCurrentTrack) { - // Puts the current track at the beginning of the play order. - this.playOrder = this.playOrder.filter(function(value) { - return this.currentTrackIndex !== value; - }, this); - this.playOrder.splice(0, 0, this.currentTrackIndex); - } - } - - if (!keepCurrentTrack) { - this.currentTrackIndex = this.playOrder[0]; - } - }, - - /** - * Sets the current track. - * @param {!TrackInfo} track TrackInfo to be set as the current - * track. - */ - selectTrack: function(track) { - let index = -1; - for (let i = 0; i < this.tracks.length; i++) { - if (this.tracks[i].url === track.url) { - index = i; - break; - } - } - if (index >= 0) { - if (this.currentTrackIndex === index) { - this.fire('replay'); - } else { - this.currentTrackIndex = index; - this.fire('play'); - } - } - }, - - /** - * Returns the current track. - * @return {TrackInfo} track TrackInfo of the current track. - */ - getCurrentTrack: function() { - if (this.tracks.length === 0) { - return null; - } - - return this.tracks[this.currentTrackIndex]; - }, - - /** - * Returns the next (or previous) track in the track list. If there is no - * next track, returns -1. - * - * @param {boolean} forward Specify direction: forward or previous mode. - * True: forward mode, false: previous mode. - * @param {boolean} cyclic Specify if cyclically or not: It true, the first - * track is succeeding to the last track, otherwise no track after the - * last. - * @return {number} The next track index. - */ - getNextTrackIndex: function(forward, cyclic) { - if (this.tracks.length === 0) { - return -1; - } - - const defaultTrackIndex = - forward ? this.playOrder[0] : this.playOrder[this.tracks.length - 1]; - - const currentPlayOrder = this.playOrder.indexOf(this.currentTrackIndex); - console.assert( - (0 <= currentPlayOrder && currentPlayOrder < this.tracks.length), - 'Insufficient TrackList.playOrder. The current track is not on the ' + - 'track list.'); - - const newPlayOrder = currentPlayOrder + (forward ? +1 : -1); - if (newPlayOrder === -1 || newPlayOrder === this.tracks.length) { - return cyclic ? defaultTrackIndex : -1; - } - - const newTrackIndex = this.playOrder[newPlayOrder]; - console.assert( - (0 <= newTrackIndex && newTrackIndex < this.tracks.length), - 'Insufficient TrackList.playOrder. New Play Order: ' + newPlayOrder); - - return newTrackIndex; - }, -});
diff --git a/ui/file_manager/audio_player/icons/audio-player-128.png b/ui/file_manager/audio_player/icons/audio-player-128.png deleted file mode 100644 index 049f99e..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-128.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-16.png b/ui/file_manager/audio_player/icons/audio-player-16.png deleted file mode 100644 index fd8e0b7..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-16.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-192.png b/ui/file_manager/audio_player/icons/audio-player-192.png deleted file mode 100644 index b71cbf45..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-192.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-256.png b/ui/file_manager/audio_player/icons/audio-player-256.png deleted file mode 100644 index a017036..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-256.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-32.png b/ui/file_manager/audio_player/icons/audio-player-32.png deleted file mode 100644 index 159cb6ae..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-32.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-48.png b/ui/file_manager/audio_player/icons/audio-player-48.png deleted file mode 100644 index dfad22b..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-48.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-64.png b/ui/file_manager/audio_player/icons/audio-player-64.png deleted file mode 100644 index 0ff1bff..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-64.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-96.png b/ui/file_manager/audio_player/icons/audio-player-96.png deleted file mode 100644 index ea7f885..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-96.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-favicon-16.png b/ui/file_manager/audio_player/icons/audio-player-favicon-16.png deleted file mode 100644 index 971bb366..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-favicon-16.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/icons/audio-player-favicon-32.png b/ui/file_manager/audio_player/icons/audio-player-favicon-32.png deleted file mode 100644 index 6f4941d..0000000 --- a/ui/file_manager/audio_player/icons/audio-player-favicon-32.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/audio_player/js/BUILD.gn b/ui/file_manager/audio_player/js/BUILD.gn deleted file mode 100644 index c6b763b3..0000000 --- a/ui/file_manager/audio_player/js/BUILD.gn +++ /dev/null
@@ -1,197 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//chrome/browser/resources/tools/optimize_webui.gni") -import("//third_party/closure_compiler/compile_js.gni") - -group("closure_compile") { - testonly = true - deps = [ - ":closure_compile_jsmodules", - ":closure_compile_polymer", - ] -} - -group("js_modules") { - deps = [ - ":audio_player", - ":background", - ":error_util", - ":main", - ":main_background", - ":test_util", - ] -} - -js_type_check("closure_compile_jsmodules") { - deps = [ - ":background", - ":error_util", - ":metadata_worker", - ] - closure_flags = default_closure_args + [ - "js_module_root=gen/ui/file_manager/", - "js_module_root=../../ui/file_manager/", - ] -} - -js_type_check("closure_compile_polymer") { - is_polymer3 = true - closure_flags = default_closure_args + [ - "js_module_root=gen/ui/file_manager/", - "js_module_root=../../ui/file_manager/", - "browser_resolver_prefix_replacements=\"chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/=./file_manager/\"", - "browser_resolver_prefix_replacements=\"chrome-extension://pmfjbimdmchhbnneeidfognadeopoehp/=./image_loader/\"", - ] - - deps = [ - ":audio_player", - ":main", - ] -} - -js_library("audio_player") { - deps = [ - "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", - "//ui/file_manager/audio_player/elements:audio_player", - "//ui/file_manager/file_manager/common/js:app_util", - "//ui/file_manager/file_manager/common/js:async_util", - "//ui/file_manager/file_manager/common/js:filtered_volume_manager", - "//ui/file_manager/file_manager/common/js:mediasession_types", - "//ui/file_manager/file_manager/common/js:util", - "//ui/file_manager/file_manager/common/js:volume_manager_types", - "//ui/file_manager/file_manager/externs:volume_manager", - "//ui/file_manager/file_manager/foreground/js/metadata:content_metadata_provider", - "//ui/file_manager/file_manager/foreground/js/metadata:metadata_model", - "//ui/webui/resources/js:load_time_data.m", - ] - - externs_list = [ - "//ui/file_manager/file_manager/externs/audio_player_foreground.js", - "$externs_path/mediasession.js", - ] -} - -js_library("background") { - deps = [ - "//ui/file_manager/file_manager/background/js:app_window_wrapper", - "//ui/file_manager/file_manager/background/js:background_base", - "//ui/file_manager/file_manager/common/js:file_type", - "//ui/file_manager/file_manager/common/js:util", - ] -} - -js_library("error_util") { -} - -js_library("metadata_worker") { - deps = [ - "//ui/file_manager/file_manager/foreground/js/metadata:metadata_dispatcher", - ] -} - -js_library("test_util") { - deps = [ - ":background", - "//ui/file_manager/file_manager/background/js:test_util_base", - ] -} - -js_library("main") { - deps = [ ":audio_player" ] -} - -js_library("main_background") { - deps = [ - ":background", - ":error_util", - ":test_util", - ] -} - -preprocess_folder = - rebase_path("$target_gen_dir/../../preprocessed/audio_player/js", - root_build_dir) - -files_app_path = - rebase_path("$root_gen_dir/ui/file_manager/preprocessed/file_manager", - root_build_dir) -image_loader_path = - rebase_path("$root_gen_dir/ui/file_manager/preprocessed/image_loader", - root_build_dir) -optimize_webui("build") { - host = "audio_player" - - input = preprocess_folder - js_module_in_files = [ "main.js" ] - - js_out_files = [ "main.rollup.js" ] - - external_paths = [ - "chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj|$files_app_path", - "chrome-extension://pmfjbimdmchhbnneeidfognadeopoehp|$image_loader_path", - ] - - deps = [ - ":main", - "//ui/file_manager:preprocess_generated", - "//ui/file_manager:preprocess_generated_image_loader", - "//ui/file_manager:preprocess_static", - "//ui/file_manager:preprocess_static_image_loader", - "//ui/webui/resources:library", - "//ui/webui/resources:preprocess", - ] -} - -optimize_webui("build_worker") { - host = "audio_player" - - input = preprocess_folder - js_module_in_files = [ "metadata_worker.js" ] - - js_out_files = [ "metadata_worker.rollup.js" ] - - external_paths = [ - "chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj|$files_app_path", - "chrome-extension://pmfjbimdmchhbnneeidfognadeopoehp|$image_loader_path", - ] - - deps = [ - "//ui/file_manager:preprocess_generated", - "//ui/file_manager:preprocess_generated_image_loader", - "//ui/file_manager:preprocess_static", - "//ui/file_manager:preprocess_static_image_loader", - "//ui/webui/resources:preprocess", - ] -} - -optimize_webui("build_background") { - host = "audio_player" - - input = preprocess_folder - js_module_in_files = [ - "main_background.js", - "../../file_manager/background/js/runtime_loaded_test_util.js", - ] - - js_out_files = [ - "main_background.rollup.js", - "runtime_loaded_test_util.rollup.js", - "shared.rollup.js", - ] - - external_paths = [ - "chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj|$files_app_path", - "chrome-extension://pmfjbimdmchhbnneeidfognadeopoehp|$image_loader_path", - ] - - deps = [ - ":main_background", - "//ui/file_manager:preprocess_generated", - "//ui/file_manager:preprocess_generated_image_loader", - "//ui/file_manager:preprocess_static", - "//ui/file_manager:preprocess_static_image_loader", - "//ui/webui/resources:preprocess", - ] -}
diff --git a/ui/file_manager/audio_player/js/audio_player.js b/ui/file_manager/audio_player/js/audio_player.js deleted file mode 100644 index 0211ae7..0000000 --- a/ui/file_manager/audio_player/js/audio_player.js +++ /dev/null
@@ -1,719 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import '../elements/audio_player.js'; - -import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -import {dashToCamelCase} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -import {appUtil} from '../../file_manager/common/js/app_util.js'; -import {AsyncUtil} from '../../file_manager/common/js/async_util.js'; -import {FilteredVolumeManager} from '../../file_manager/common/js/filtered_volume_manager.js'; -import {MediaSessionPlaybackState} from '../../file_manager/common/js/mediasession_types.js'; -import {util} from '../../file_manager/common/js/util.js'; -import {AllowedPaths} from '../../file_manager/common/js/volume_manager_types.js'; -import {ExternallyUnmountedEvent} from '../../file_manager/externs/volume_manager.js'; -import {ContentMetadataProvider} from '../../file_manager/foreground/js/metadata/content_metadata_provider.js'; -import {MetadataModel} from '../../file_manager/foreground/js/metadata/metadata_model.js'; - -/** - * @param {Element} container Container element. - * @constructor - */ -export function AudioPlayer(container) { - this.container_ = container; - - this.volumeManager_ = new FilteredVolumeManager( - AllowedPaths.ANY_PATH, false, appUtil.getVolumeManager(), []); - - this.resolveMetadataModel_ = null; - this.metadataModelReady_ = new Promise(resolve => { - this.resolveMetadataModel_ = resolve; - }); - this.metadataModel_ = null; - - this.selectedEntry_ = null; - this.invalidTracks_ = {}; - this.entries_ = []; - this.currentTrackIndex_ = -1; - this.playlistGeneration_ = 0; - - /** - * Whether if the playlist is expanded or not. This value is changed by - * this.syncPlaylistExpanded(). - * True: expanded, false: collapsed, null: unset. - * - * @type {?boolean} - * @private - */ - // Initial value is null. It'll be set in load(). - this.isPlaylistExpanded_ = null; - - /** - * Whether if the trackinfo is expanded or not. - * True: expanded, false: collapsed, null: unset. - * - * @type {?boolean} - * @private - */ - // Initial value is null. It'll be set in load(). - this.isTrackInfoExpanded_ = null; - - this.player_ = - /** @type {AudioPlayerElement} */ (document.querySelector('audio-player')); - this.player_.tracks = []; - this.isRtl_ = window.getComputedStyle(this.player_)['direction'] === 'rtl'; - - /** - * Queue to throttle concurrent reading of audio file metadata. - * Here we loads up to 25 songs concurrently to cover the number of songs in - * an album in most cases. This number should not be too large so that the - * number of open file descriptors will not hit the system limit. - * @private {AsyncUtil.ConcurrentQueue} - */ - this.loadMetadataQueue_ = new AsyncUtil.ConcurrentQueue(25); - - // Restore the saved state from local storage, and update the local storage - // if the states are changed. - const STORAGE_PREFIX = 'audioplayer-'; - const KEYS_TO_SAVE_STATES = [ - 'shuffle', - 'repeat-mode', - 'volume', - 'playlist-expanded', - 'track-info-expanded', - ]; - const storageKeys = KEYS_TO_SAVE_STATES.map(a => STORAGE_PREFIX + a); - chrome.storage.local.get(storageKeys, function(results) { - // Update the UI by loaded state. - for (const storageKey in results) { - const key = storageKey.substr(STORAGE_PREFIX.length); - this.player_[dashToCamelCase(key)] = results[storageKey]; - } - // Start listening to UI changes to write back the states to local storage. - for (let i = 0; i < KEYS_TO_SAVE_STATES.length; i++) { - this.player_.addEventListener( - KEYS_TO_SAVE_STATES[i] + '-changed', function(storageKey, event) { - const objectToBeSaved = {}; - objectToBeSaved[storageKey] = event.detail.value; - chrome.storage.local.set(objectToBeSaved); - }.bind(this, storageKeys[i])); - } - }.bind(this)); - - // Update the window size when UI's 'playlist-expanded' state is changed. - this.player_.addEventListener('playlist-expanded-changed', function(event) { - this.onPlaylistExpandedChanged_(event.detail.value); - }.bind(this)); - - // Update the window size when UI's 'track-info-expanded' state is changed. - this.player_.addEventListener('track-info-expanded-changed', function(event) { - this.onTrackInfoExpandedChanged_(event.detail.value); - }.bind(this)); - - this.player_.addEventListener( - 'playing-changed', this.updateMediaSessionPlaybackState_.bind(this)); - - // Run asynchronously after an event of model change is delivered. - setTimeout(function() { - this.errorString_ = ''; - this.offlineString_ = ''; - chrome.fileManagerPrivate.getStrings(function(strings) { - strings = /** @type {!Object<string>} */ (strings); - loadTimeData.data = strings; - - container.ownerDocument.title = strings['AUDIO_PLAYER_TITLE']; - this.errorString_ = strings['AUDIO_ERROR']; - this.offlineString_ = strings['AUDIO_OFFLINE']; - AudioPlayer.TrackInfo.DEFAULT_ARTIST = - strings['AUDIO_PLAYER_DEFAULT_ARTIST']; - // Pass translated labels to the AudioPlayerElement. - this.player_.ariaLabels = { - shuffle: strings['AUDIO_PLAYER_SHUFFLE_BUTTON_LABEL'], - repeat: strings['AUDIO_PLAYER_REPEAT_BUTTON_LABEL'], - previous: strings['MEDIA_PLAYER_PREVIOUS_BUTTON_LABEL'], - play: strings['MEDIA_PLAYER_PLAY_BUTTON_LABEL'], - pause: strings['MEDIA_PLAYER_PAUSE_BUTTON_LABEL'], - next: strings['MEDIA_PLAYER_NEXT_BUTTON_LABEL'], - playList: strings['AUDIO_PLAYER_OPEN_PLAY_LIST_BUTTON_LABEL'], - seekSlider: strings['MEDIA_PLAYER_SEEK_SLIDER_LABEL'], - mute: strings['MEDIA_PLAYER_MUTE_BUTTON_LABEL'], - unmute: strings['MEDIA_PLAYER_UNMUTE_BUTTON_LABEL'], - volumeSlider: strings['MEDIA_PLAYER_VOLUME_SLIDER_LABEL'], - }; - this.player_.ariaExpandArtworkLabel = - strings['AUDIO_PLAYER_ARTWORK_EXPAND_BUTTON_LABEL']; - - // Override metadata worker's path. - ContentMetadataProvider.configure( - '/js/metadata_worker.js', - /*isModule=*/ true); - - this.metadataModel_ = MetadataModel.create(this.volumeManager_); - this.resolveMetadataModel_(); - }.bind(this)); - - this.volumeManager_.addEventListener('externally-unmounted', - this.onExternallyUnmounted_.bind(this)); - - window.addEventListener('resize', this.onResize_.bind(this)); - document.addEventListener('keydown', this.onKeyDown_.bind(this)); - - // Show the window after DOM is processed. - const currentWindow = chrome.app.window.current(); - if (currentWindow) { - setTimeout(currentWindow.show.bind(currentWindow), 0); - } - }.bind(this), 0); -} - -/** - * Initial load method (static). - */ -AudioPlayer.load = function() { - document.ondragstart = function(e) { - e.preventDefault(); - }; - - AudioPlayer.instance = - new AudioPlayer(document.querySelector('.audio-player')); - - reload(); -}; - -/** - * Unloads the player. - */ -export function unload() { - if (AudioPlayer.instance) { - AudioPlayer.instance.onUnload(); - } -} - -/** - * Reloads the player. - */ -export function reload() { - AudioPlayer.instance.load(/** @type {Playlist} */ (window.appState)); -} - -/** - * Loads a new playlist. - * @param {Playlist} playlist Playlist object passed via mediaPlayerPrivate. - */ -AudioPlayer.prototype.load = function(playlist) { - this.playlistGeneration_++; - this.currentTrackIndex_ = -1; - - // Save the app state, in case of restart. Make a copy of the object, so the - // playlist member is not changed after entries are resolved. - window.appState = /** @type {Playlist} */ ( - JSON.parse(JSON.stringify(playlist))); // cloning - appUtil.saveAppState(); - - this.isPlaylistExpanded_ = this.player_.playlistExpanded; - this.isTrackInfoExpanded_ = this.player_.trackInfoExpanded; - - // Resolving entries has to be done after the volume manager is initialized. - this.volumeManager_.ensureInitialized(function() { - util.URLsToEntries(playlist.items || [], function(entries) { - this.entries_ = entries; - - const position = playlist.position || 0; - - if (this.entries_.length == 0) { - return; - } - - const newTracks = []; - const currentTracks = this.player_.tracks; - let unchanged = (currentTracks.length === this.entries_.length); - - for (let i = 0; i != this.entries_.length; i++) { - const entry = this.entries_[i]; - newTracks.push(new AudioPlayer.TrackInfo(entry)); - - if (unchanged && entry.toURL() !== currentTracks[i].url) { - unchanged = false; - } - } - - if (!unchanged) { - this.player_.tracks = newTracks; - } - - // Run asynchronously, to makes it sure that the handler of the track list - // is called, before the handler of the track index. - setTimeout(function() { - this.select_(position); - - // Load the selected track metadata first, then load the rest. - this.loadMetadata_(position); - for (let i = 0; i != this.entries_.length; i++) { - if (i != position) { - this.loadMetadata_(i); - } - } - }.bind(this), 0); - }.bind(this)); - }.bind(this)); -}; - -/** - * Loads metadata for a track. - * @param {number} track Track number. - * @private - */ -AudioPlayer.prototype.loadMetadata_ = function(track) { - this.loadMetadataQueue_.run(function(callback) { - this.fetchMetadata_(this.entries_[track], function(metadata) { - this.displayMetadata_(track, metadata); - callback(); - }.bind(this)); - }.bind(this)); -}; - -/** - * Displays track's metadata. - * @param {number} track Track number. - * @param {Object} metadata Metadata object. - * @param {string=} opt_error Error message. - * @private - */ -AudioPlayer.prototype.displayMetadata_ = function(track, metadata, opt_error) { - this.player_.tracks[track].setMetadata(metadata, opt_error); - this.player_.notifyTrackMetadataUpdated(track); -}; - -/** - * Closes audio player when a volume containing the selected item is unmounted. - * @param {Event} event The unmount event. - * @private - */ -AudioPlayer.prototype.onExternallyUnmounted_ = function(event) { - if (!this.selectedEntry_) { - return; - } - - event = /** @type {!ExternallyUnmountedEvent} */ (event); - if (this.volumeManager_.getVolumeInfo(this.selectedEntry_) === event.detail) { - window.close(); - } -}; - -/** - * Called on window is being unloaded. - */ -AudioPlayer.prototype.onUnload = function() { - if (this.player_) { - this.player_.onPageUnload(); - } - - if (this.volumeManager_) { - this.volumeManager_.dispose(); - } -}; - -/** - * Selects a new track to play. - * @param {number} newTrack New track number. - * @private - */ -AudioPlayer.prototype.select_ = function(newTrack) { - if (this.currentTrackIndex_ == newTrack) return; - - this.currentTrackIndex_ = newTrack; - this.player_.currentTrackIndex = this.currentTrackIndex_; - this.player_.time = 0; - - // Run asynchronously after an event of current track change is delivered. - setTimeout(function() { - if (!window.appReopen) { - this.player_.play(); - } - - window.appState.position = this.currentTrackIndex_; - window.appState.time = 0; - appUtil.saveAppState(); - - const entry = this.entries_[this.currentTrackIndex_]; - - this.fetchMetadata_(entry, function(metadata) { - if (this.currentTrackIndex_ != newTrack) { - return; - } - - this.selectedEntry_ = entry; - }.bind(this)); - }.bind(this), 0); -}; - -/** - * @param {FileEntry} entry Track file entry. - * @param {function(Object)} callback Callback. - * @private - */ -AudioPlayer.prototype.fetchMetadata_ = async function(entry, callback) { - await this.metadataModelReady_; - this.metadataModel_.get( - [entry], - ['mediaTitle', 'mediaArtist', 'present', 'contentThumbnailUrl']).then( - function(generation, metadata) { - // Do nothing if another load happened since the metadata request. - if (this.playlistGeneration_ == generation) { - callback(metadata[0]); - } - }.bind(this, this.playlistGeneration_)); -}; - -/** - * Media error handler. - * @private - */ -AudioPlayer.prototype.onError_ = function() { - const track = this.currentTrackIndex_; - - this.invalidTracks_[track] = true; - - this.fetchMetadata_(this.entries_[track], function(metadata) { - const error = (!navigator.onLine && !metadata.present) ? - this.offlineString_ : - this.errorString_; - this.displayMetadata_(track, metadata, error); - this.player_.onAudioError(); - }.bind(this)); -}; - -/** - * Toggles the expanded mode when resizing. - * - * @param {Event} event Resize event. - * @private - */ -AudioPlayer.prototype.onResize_ = function(event) { - const trackListHeight = - (/** @type {{trackList:TrackListElement}} */ (this.player_.$)) - .trackList.clientHeight; - if (trackListHeight > AudioPlayer.TOP_PADDING_HEIGHT) { - this.isPlaylistExpanded_ = true; - this.player_.playlistExpanded = true; - } else { - this.isPlaylistExpanded_ = false; - this.player_.playlistExpanded = false; - } -}; - -/** - * Handles keydown event to open inspector with shortcut keys. - * - * @param {Event} event KeyDown event. - * @private - */ -AudioPlayer.prototype.onKeyDown_ = function(event) { - switch (util.getKeyModifiers(event) + event.key) { - case 'Ctrl-w': // Ctrl+W => Close the player. - case 'BrowserBack': - chrome.app.window.current().close(); - break; - - // Handle debug shortcut keys. - case 'Ctrl-Shift-I': // Ctrl+Shift+I - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.NORMAL); - break; - case 'Ctrl-Shift-J': // Ctrl+Shift+J - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.CONSOLE); - break; - case 'Ctrl-Shift-C': // Ctrl+Shift+C - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.ELEMENT); - break; - case 'Ctrl-Shift-B': // Ctrl+Shift+B - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.BACKGROUND); - break; - - case ' ': // Space - case 'k': - case 'MediaPlayPause': - this.player_.dispatchEvent(new Event('toggle-pause-event')); - break; - case 'ArrowUp': - this.player_.dispatchEvent(new Event('small-forward-skip-event')); - break; - case 'ArrowDown': - this.player_.dispatchEvent(new Event('small-backword-skip-event')); - break; - case 'ArrowRight': { - const eventName = this.isRtl_ ? 'small-backword-skip-event' : - 'small-forward-skip-event'; - this.player_.dispatchEvent(new Event(eventName)); - } break; - case 'ArrowLeft': { - const eventName = this.isRtl_ ? 'small-forward-skip-event' : - 'small-backword-skip-event'; - this.player_.dispatchEvent(new Event(eventName)); - } break; - case 'l': - this.player_.dispatchEvent(new Event('big-forward-skip-event')); - break; - case 'j': - this.player_.dispatchEvent(new Event('big-backword-skip-event')); - break; - case ']': - case 'MediaTrackNext': - this.player_.dispatchEvent(new Event('next-track-event')); - break; - case '[': - case 'MediaTrackPrevious': - this.player_.dispatchEvent(new Event('previous-track-event')); - break; - case 'MediaStop': - // TODO: Define "Stop" behavior. - break; - } -}; - -/** - * Updates the Media Session API with the current playback state of the audio - * player. - * @param {Event} event The playing event. - * @private - */ -AudioPlayer.prototype.updateMediaSessionPlaybackState_ = function(event) { - if (!navigator.mediaSession) { - return; - } - - navigator.mediaSession.playbackState = event.detail.value ? - MediaSessionPlaybackState.PLAYING : - MediaSessionPlaybackState.PAUSED; -}; - -/* Keep the below constants in sync with the CSS. */ - -/** - * Window header size in pixels. - * @type {number} - * @const - */ -AudioPlayer.HEADER_HEIGHT = 33; // 32px + border 1px - -/** - * Top padding height of audio player in pixels. - * @type {number} - * @const - */ -AudioPlayer.TOP_PADDING_HEIGHT = 4; - -/** - * Track height in pixels. - * @type {number} - * @const - */ -AudioPlayer.TRACK_HEIGHT = 48; - -/** - * artwork panel height in pixels, when it's closed. - * @type {number} - * @const - */ -AudioPlayer.CLOSED_ARTWORK_HEIGHT = 48; - -/** - * artwork panel height in pixels, when it's opened. - * @type {number} - * @const - */ -AudioPlayer.EXPANDED_ARTWORK_HEIGHT = 320; - -/** - * Controls bar height in pixels. - * @type {number} - * @const - */ -AudioPlayer.CONTROLS_HEIGHT = 96; - -/** - * Default number of items in the expanded mode. - * @type {number} - * @const - */ -AudioPlayer.DEFAULT_EXPANDED_ITEMS = 5; - -/** - * Minimum size of the window in the expanded mode in pixels. - * @type {number} - * @const - */ -AudioPlayer.EXPANDED_MODE_MIN_HEIGHT = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.EXPANDED_ARTWORK_HEIGHT + - AudioPlayer.CONTROLS_HEIGHT; - -/** - * Minimum size of the window in the mode in pixels. - * @type {number} - * @const - */ -AudioPlayer.CLOSED_MODE_MIN_HEIGHT = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.CLOSED_ARTWORK_HEIGHT + - AudioPlayer.CONTROLS_HEIGHT; - -/** - * Invoked when the 'playlist-expanded' property in the model is changed. - * @param {boolean} newValue New value. - * @private - */ -AudioPlayer.prototype.onPlaylistExpandedChanged_ = function(newValue) { - if (this.isPlaylistExpanded_ !== null && - this.isPlaylistExpanded_ === newValue) { - return; - } - - if (this.isPlaylistExpanded_ && !newValue) { - this.lastExpandedInnerHeight_ = window.innerHeight; - } - - if (this.isPlaylistExpanded_ !== newValue) { - this.isPlaylistExpanded_ = newValue; - this.syncHeightForPlaylist_(); - - // Saves new state. - window.appState.playlistExpanded = newValue; - appUtil.saveAppState(); - } -}; - -/** - * Invoked when the 'track-info-expanded' property in the model is changed. - * @param {boolean} newValue New value. - * @private - */ -AudioPlayer.prototype.onTrackInfoExpandedChanged_ = function(newValue) { - if (this.isTrackInfoExpanded_ !== null && - this.isTrackInfoExpanded_ === newValue) { - return; - } - - this.lastExpandedInnerHeight_ = window.innerHeight; - - if (this.isTrackInfoExpanded_ !== newValue) { - this.isTrackInfoExpanded_ = newValue; - const state = chrome.app.window.current(); - let newHeight = window.outerHeight; - if (newValue) { - state.innerBounds.minHeight = AudioPlayer.EXPANDED_MODE_MIN_HEIGHT; - newHeight += AudioPlayer.EXPANDED_MODE_MIN_HEIGHT - - AudioPlayer.CLOSED_MODE_MIN_HEIGHT; - } else { - state.innerBounds.minHeight = AudioPlayer.CLOSED_MODE_MIN_HEIGHT; - newHeight -= AudioPlayer.EXPANDED_MODE_MIN_HEIGHT - - AudioPlayer.CLOSED_MODE_MIN_HEIGHT; - } - window.resizeTo(window.outerWidth, newHeight); - - // Saves new state. - window.appState.isTrackInfoExpanded_ = newValue; - appUtil.saveAppState(); - } -}; - -/** - * @private - */ -AudioPlayer.prototype.syncHeightForPlaylist_ = function() { - let targetInnerHeight; - - if (this.player_.playlistExpanded) { - // playllist expanded. - if (!this.lastExpandedInnerHeight_ || - this.lastExpandedInnerHeight_ < AudioPlayer.EXPANDED_MODE_MIN_HEIGHT) { - const expandedListHeight = - Math.min(this.entries_.length, AudioPlayer.DEFAULT_EXPANDED_ITEMS) * - AudioPlayer.TRACK_HEIGHT; - if (this.player_.trackInfoExpanded) { - targetInnerHeight = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.EXPANDED_ARTWORK_HEIGHT + - expandedListHeight + - AudioPlayer.CONTROLS_HEIGHT; - } else { - targetInnerHeight = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.TRACK_HEIGHT + - expandedListHeight + - AudioPlayer.CONTROLS_HEIGHT; - } - this.lastExpandedInnerHeight_ = targetInnerHeight; - } else { - targetInnerHeight = this.lastExpandedInnerHeight_; - } - } else { - // playllist not expanded. - if (this.player_.trackInfoExpanded) { - targetInnerHeight = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.EXPANDED_ARTWORK_HEIGHT + - AudioPlayer.CONTROLS_HEIGHT; - } else { - targetInnerHeight = AudioPlayer.TOP_PADDING_HEIGHT + - AudioPlayer.TRACK_HEIGHT + - AudioPlayer.CONTROLS_HEIGHT; - } - } - window.resizeTo(window.outerWidth, - AudioPlayer.HEADER_HEIGHT + targetInnerHeight); -}; - -/** - * Create a TrackInfo object encapsulating the information about one track. - * - * @param {FileEntry} entry FileEntry to be retrieved the track info from. - * @constructor - */ -AudioPlayer.TrackInfo = function(entry) { - this.url = entry.toURL(); - this.title = this.getDefaultTitle(); - this.artist = this.getDefaultArtist(); - - this.artworkUrl = ''; - this.active = false; -}; - -/** - * @return {string} Default track title (file name extracted from the url). - */ -AudioPlayer.TrackInfo.prototype.getDefaultTitle = function() { - let title = this.url.split('/').pop(); - const dotIndex = title.lastIndexOf('.'); - if (dotIndex >= 0) { - title = title.substr(0, dotIndex); - } - title = decodeURIComponent(title); - return title; -}; - -/** - * TODO(kaznacheev): Localize. - */ -AudioPlayer.TrackInfo.DEFAULT_ARTIST = 'Unknown Artist'; - -/** - * @return {string} 'Unknown artist' string. - */ -AudioPlayer.TrackInfo.prototype.getDefaultArtist = function() { - return AudioPlayer.TrackInfo.DEFAULT_ARTIST; -}; - -/** - * @param {Object} metadata The metadata object. - * @param {string} error Error string. - */ -AudioPlayer.TrackInfo.prototype.setMetadata = function( - metadata, error) { - // TODO(yoshiki): Handle error in better way. - this.title = metadata.mediaTitle || this.getDefaultTitle(); - this.artist = error || metadata.mediaArtist || this.getDefaultArtist(); - this.artworkUrl = metadata.contentThumbnailUrl || ''; -}; - -AudioPlayer.load();
diff --git a/ui/file_manager/audio_player/js/background.js b/ui/file_manager/audio_player/js/background.js deleted file mode 100644 index 4636e8d..0000000 --- a/ui/file_manager/audio_player/js/background.js +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {SingletonAppWindowWrapper} from '../../file_manager/background/js/app_window_wrapper.js'; -import {BackgroundBaseImpl} from '../../file_manager/background/js/background_base.js'; -import {FileType} from '../../file_manager/common/js/file_type.js'; -import {util} from '../../file_manager/common/js/util.js'; - -/** - * Icon of the audio player. - * Use maximum size and let ash downsample the icon. - * - * @type {!string} - * @const - */ -const AUDIO_PLAYER_ICON = 'icons/audio-player-192.png'; - -/** - * HTML source of the audio player as JS module. - * @type {!string} - * @const - */ -const AUDIO_PLAYER_APP_URL = 'audio_player.html'; - -/** - * Configuration of the audio player. - * @type {!Object} - * @const - */ -const audioPlayerCreateOptions = { - id: 'audio-player', - minHeight: 4 + 48 + 96, // 4px: border-top, 48px: track, 96px: controller - minWidth: 320, - height: 4 + 48 + 96, // collapsed - width: 320, - frame: {color: '#fafafa'}, -}; - -class AudioPlayerBackground extends BackgroundBaseImpl { - constructor() { - super(); - } - - async ready() { - return await this.initializationPromise_; - } - - /** - * Called when an audio player app is restarted. - */ - onRestarted_() { - getAudioPlayer.then(audioPlayer => { - audioPlayer.reopen(function() { - // If the audioPlayer is reopened, change its window's icon. Otherwise - // there is no reopened window so just skip the call of setIcon. - if (audioPlayer.rawAppWindow) { - audioPlayer.setIcon(AUDIO_PLAYER_ICON); - } - }); - }); - } -} - -/** - * Backgound object. This is necessary for AppWindowWrapper. - * @type {!AudioPlayerBackground} - */ -window.background = new AudioPlayerBackground(); - - -/** - * Audio player app window wrapper. - * @type {!Promise<!SingletonAppWindowWrapper>} - */ -const getAudioPlayer = new Promise(async (resolve) => { - await window.background.ready(); - const url = AUDIO_PLAYER_APP_URL; - resolve(new SingletonAppWindowWrapper(url, audioPlayerCreateOptions)); -}); - -/** - * Opens the audio player window. - * @param {!Array<string>} urls List of audios to play and index to start - * playing. - * @return {!Promise} Promise to be fulfilled on success, or rejected on error. - */ -export async function open(urls) { - let position = 0; - const startUrl = (position < urls.length) ? urls[position] : ''; - - if (urls.length === 0) { - throw new Error('No file to open.'); - } - - try { - const entries = await new Promise(function(fulfill, reject) { - // Gets the current list of the children of the parent. - window.webkitResolveLocalFileSystemURL(urls[0], function(fileEntry) { - fileEntry.getParent(function(parentEntry) { - const dirReader = parentEntry.createReader(); - let entries = []; - - // Call the reader.readEntries() until no more results are - // returned. - const readEntries = function() { - dirReader.readEntries(function(results) { - if (!results.length) { - fulfill(entries.sort(util.compareName)); - } else { - entries = - entries.concat(Array.prototype.slice.call(results, 0)); - readEntries(); - } - }, reject); - }; - - // Start reading. - readEntries(); - }, reject); - }, reject); - }); - - // Omits non-audio files. - const audioEntries = entries.filter(entry => FileType.isAudio(entry)); - - // Adjusts the position to start playing. - const maybePosition = util.entriesToURLs(audioEntries).indexOf(startUrl); - if (maybePosition !== -1) { - position = maybePosition; - } - - // Opens the audio player. - const urlsToOpen = util.entriesToURLs(audioEntries); - const audioPlayer = await getAudioPlayer; - await audioPlayer.launch({items: urlsToOpen, position: position}, false); - - audioPlayer.setIcon(AUDIO_PLAYER_ICON); - audioPlayer.rawAppWindow.focus(); - return AUDIO_PLAYER_APP_URL; - } catch (error) { - console.error('Launch failed: ' + (error.stack || error)); - throw error; - } -} - -window.background.setLaunchHandler(open);
diff --git a/ui/file_manager/audio_player/js/error_util.js b/ui/file_manager/audio_player/js/error_util.js deleted file mode 100644 index 2028eb5..0000000 --- a/ui/file_manager/audio_player/js/error_util.js +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * This variable is checked in SelectFileDialogExtensionBrowserTest. - * @type {number} - */ -window.JSErrorCount = 0; - -/** - * Counts uncaught exceptions. - */ -window.onerror = function() { - window.JSErrorCount++; -};
diff --git a/ui/file_manager/audio_player/js/main.js b/ui/file_manager/audio_player/js/main.js deleted file mode 100644 index b52c219..0000000 --- a/ui/file_manager/audio_player/js/main.js +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Main JS Module for Audio Player. It replaces - * audio_player_scripts.js - */ - -import {AudioPlayer, reload, unload} from './audio_player.js'; - -window.reload = reload; -window.unload = unload; -window.AudioPlayer = AudioPlayer; - -console.log('AudioPlayer main.js loaded');
diff --git a/ui/file_manager/audio_player/js/main_background.js b/ui/file_manager/audio_player/js/main_background.js deleted file mode 100644 index c5e1ffc4..0000000 --- a/ui/file_manager/audio_player/js/main_background.js +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Entry point for the background page. - */ - -import './error_util.js'; -import './test_util.js'; -import './background.js';
diff --git a/ui/file_manager/audio_player/js/metadata_worker.js b/ui/file_manager/audio_player/js/metadata_worker.js deleted file mode 100644 index b6932e999..0000000 --- a/ui/file_manager/audio_player/js/metadata_worker.js +++ /dev/null
@@ -1,5 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import '../../file_manager/foreground/js/metadata/metadata_dispatcher.js';
diff --git a/ui/file_manager/audio_player/js/test_util.js b/ui/file_manager/audio_player/js/test_util.js deleted file mode 100644 index 801d852..0000000 --- a/ui/file_manager/audio_player/js/test_util.js +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {test} from '../../file_manager/background/js/test_util_base.js'; - -import {open} from './background.js'; - -/** - * Opens the audio player and waits until it is ready. - * - * @param {!Array<string>} urls URLs to be opened. - * - */ -test.util.async.openAudioPlayer = function(urls, callback) { - open(urls).then(callback); -}; - -// Register the test utils. -test.util.registerRemoteTestUtils('/js/runtime_loaded_test_util.js');
diff --git a/ui/file_manager/audio_player/manifest.json b/ui/file_manager/audio_player/manifest.json deleted file mode 100644 index fbc7230..0000000 --- a/ui/file_manager/audio_player/manifest.json +++ /dev/null
@@ -1,52 +0,0 @@ -{ - // chrome-extension://cjbfomnbifhcdnihkgipgfcihmgjfhbf/ - "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsU2jLo1oiASjXO+/+qYfgojW4Y5TCIBNFzcAdxaF78BRteygWkJqbUVyGZxtSk/RDe3NdNyQCxsyU1YfYXZQvGRNDwKw5tzGyE4dcedveipaJW174VGd3GViS0WWist3HRxfYRZvRP5E8l/4NxXB0+crfq2WolO8La25js1QkCsggQ1lC8g24NRrPnTAWZxvSD6L64R0UoVoe68HdC4mRISe9/OqjyiAfb4Ajgooq8dyzkV8AJTKRjFTmYPlcc5Ba21rXzRt22TnDh2U38m/OEvTu69cyTIxAkBjUa/2gu7N588k9XzaMhTjiolSWxBDQuLZRp8fNjO0R27jouo3FwIDAQAB", - "manifest_version": 2, - "name": "Audio Player", - "version": "1.2", - "description": "Audio Player", - "display_in_launcher": false, - "incognito" : "split", - "icons": { - "16": "icons/audio-player-16.png", - "32": "icons/audio-player-32.png", - "48": "icons/audio-player-48.png", - "64": "icons/audio-player-64.png", - "96": "icons/audio-player-96.png", - "128": "icons/audio-player-128.png", - "192": "icons/audio-player-192.png", - "256": "icons/audio-player-256.png" - }, - "permissions": [ - "commandLinePrivate", - "fileSystem", - "fileManagerPrivate", - { - "fileSystem": ["requestFileSystem", "write"] - }, - "fullscreen", - "power", - "storage", - "chrome://resources/", - "chrome://theme/" - ], - "file_handlers": { - "audio": { - "extensions": [ - "amr", - "flac", - "m4a", - "mp3", - "oga", - "ogg", - "wav" - ] - } - }, - "app": { - "background": { - "page": "background.html" - }, - "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj; style-src 'self' blob: filesystem: chrome://resources 'unsafe-inline'; img-src 'self' blob: filesystem: chrome://theme chrome://resources data: https://www.googledrive.com; media-src 'self' blob: filesystem:; connect-src chrome://resources ; object-src 'self' blob: filesystem:; font-src chrome://resources;" - } -}
diff --git a/ui/file_manager/file_manager/background/js/BUILD.gn b/ui/file_manager/file_manager/background/js/BUILD.gn index cae7dd7e..59d9e1c 100644 --- a/ui/file_manager/file_manager/background/js/BUILD.gn +++ b/ui/file_manager/file_manager/background/js/BUILD.gn
@@ -14,10 +14,7 @@ # document externally-exposed targets visible with this helper, and hide # transitive dependencies (but note those transitive dependencies should move # elsewhere too). -related_apps = [ - "//ui/file_manager/audio_player/*", - "//ui/file_manager/file_manager/*", -] +related_apps = [ "//ui/file_manager/file_manager/*" ] group("closure_compile") { testonly = true
diff --git a/ui/file_manager/file_manager/foreground/elements/BUILD.gn b/ui/file_manager/file_manager/foreground/elements/BUILD.gn index 6745010..ff8f8a1 100644 --- a/ui/file_manager/file_manager/foreground/elements/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/elements/BUILD.gn
@@ -74,7 +74,6 @@ } js_library("files_format_dialog") { - visibility += [ "//ui/file_manager/audio_player/*" ] deps = [ "//third_party/polymer/v3_0/components-chromium/iron-icon:iron-icon", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", @@ -91,7 +90,6 @@ } js_library("files_icon_button") { - visibility += [ "//ui/file_manager/audio_player/*" ] deps = [ ":files_toggle_ripple", "//third_party/polymer/v3_0/components-chromium/iron-behaviors:iron-button-state", @@ -176,10 +174,6 @@ # TODO(tapted): Move this to //ui/file_manager/base. js_library("files_toggle_ripple") { - visibility += [ "//ui/file_manager/audio_player/*" ] - - #visibility += [ "//ui/file_manager/gallery/*" ] - deps = [ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", ]
diff --git a/ui/file_manager/file_manager/foreground/js/BUILD.gn b/ui/file_manager/file_manager/foreground/js/BUILD.gn index f023b40f..9db8996 100644 --- a/ui/file_manager/file_manager/foreground/js/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/BUILD.gn
@@ -179,7 +179,7 @@ "ui:file_manager_ui", "//ui/file_manager/file_manager/externs:volume_manager", "//ui/file_manager/file_manager/externs/background:drive_sync_handler", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", + "//ui/webui/resources/js/cr/ui:context_menu_handler", ] } @@ -396,7 +396,7 @@ "//ui/file_manager/file_manager/externs:volume_manager", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } @@ -652,9 +652,9 @@ "//ui/webui/resources/js:util.m", "//ui/webui/resources/js/cr:event_target.m", "//ui/webui/resources/js/cr/ui:array_data_model.m", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", + "//ui/webui/resources/js/cr/ui:context_menu_handler", "//ui/webui/resources/js/cr/ui:list.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -694,8 +694,8 @@ "//ui/file_manager/file_manager/externs:volume_manager", "//ui/file_manager/file_manager/foreground/elements:files_format_dialog", "//ui/webui/resources/js:assert.m", - "//ui/webui/resources/js/cr/ui:command.m", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", + "//ui/webui/resources/js/cr/ui:command", + "//ui/webui/resources/js/cr/ui:context_menu_handler", "//ui/webui/resources/js/cr/ui:list.m", ] } @@ -760,7 +760,7 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:load_time_data.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -814,7 +814,7 @@ "//ui/file_manager/file_manager/foreground/elements:files_toast", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", "//ui/webui/resources/js/cr/ui:list.m", ] } @@ -847,7 +847,7 @@ "//ui/webui/resources/cr_elements/cr_input:cr_input.m", "//ui/webui/resources/js:util.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", "//ui/webui/resources/js/cr/ui:list_selection_model.m", ] } @@ -1256,7 +1256,7 @@ "//ui/file_manager/file_manager/foreground/elements:files_toggle_ripple", "//ui/file_manager/file_manager/foreground/elements:files_tooltip", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -1300,7 +1300,7 @@ "//ui/file_manager/file_manager/externs/background:progress_center", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:load_time_data.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } @@ -1327,7 +1327,7 @@ "//ui/file_manager/file_manager/externs/background:progress_center", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } @@ -1373,14 +1373,14 @@ "//ui/file_manager/file_manager/externs:volume_manager", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } js_library("webui_command_extender") { deps = [ "//ui/webui/resources/js:cr.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] }
diff --git a/ui/file_manager/file_manager/foreground/js/actions_controller.js b/ui/file_manager/file_manager/foreground/js/actions_controller.js index 6c8dcdb7..cd61ac93 100644 --- a/ui/file_manager/file_manager/foreground/js/actions_controller.js +++ b/ui/file_manager/file_manager/foreground/js/actions_controller.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; import {DriveSyncHandler} from '../../externs/background/drive_sync_handler.js'; import {VolumeManager} from '../../externs/volume_manager.js';
diff --git a/ui/file_manager/file_manager/foreground/js/dialog_action_controller.js b/ui/file_manager/file_manager/foreground/js/dialog_action_controller.js index 8b611ad9..463f670 100644 --- a/ui/file_manager/file_manager/foreground/js/dialog_action_controller.js +++ b/ui/file_manager/file_manager/foreground/js/dialog_action_controller.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {$} from 'chrome://resources/js/util.m.js'; import {DialogType} from '../../common/js/dialog_type.js';
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager.js b/ui/file_manager/file_manager/foreground/js/file_manager.js index 9999fdf..6d9c6c9 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager.js
@@ -5,9 +5,9 @@ import {assert, assertInstanceof} from 'chrome://resources/js/assert.m.js'; import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js'; import {ArrayDataModel} from 'chrome://resources/js/cr/ui/array_data_model.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; import {List} from 'chrome://resources/js/cr/ui/list.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js';
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 ab017462..9e4b435 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
@@ -5,8 +5,8 @@ import './webui_command_extender.js'; import {assert} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; import {List} from 'chrome://resources/js/cr/ui/list.m.js'; import {getHoldingSpaceState, startIOTask} from '../../common/js/api.js';
diff --git a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js index 57bab95a..6aa60c76 100644 --- a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js +++ b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {List} from 'chrome://resources/js/cr/ui/list.m.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js';
diff --git a/ui/file_manager/file_manager/foreground/js/file_transfer_controller_unittest.js b/ui/file_manager/file_manager/foreground/js/file_transfer_controller_unittest.js index 0b129e2..83cfc0a 100644 --- a/ui/file_manager/file_manager/foreground/js/file_transfer_controller_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/file_transfer_controller_unittest.js
@@ -5,7 +5,7 @@ import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {ListSelectionModel} from 'chrome://resources/js/cr/ui/list_selection_model.m.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
diff --git a/ui/file_manager/file_manager/foreground/js/selection_menu_controller.js b/ui/file_manager/file_manager/foreground/js/selection_menu_controller.js index 2903fda..0bf6d75 100644 --- a/ui/file_manager/file_manager/foreground/js/selection_menu_controller.js +++ b/ui/file_manager/file_manager/foreground/js/selection_menu_controller.js
@@ -4,7 +4,7 @@ import '../elements/files_toggle_ripple.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js'; import {FilesTooltip} from '../elements/files_tooltip.js';
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller.js b/ui/file_manager/file_manager/foreground/js/task_controller.js index 8393191..ea7a6bf 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {startIOTask} from '../../common/js/api.js';
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller_unittest.js b/ui/file_manager/file_manager/foreground/js/task_controller_unittest.js index 5931f1f0..b274edc 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller_unittest.js
@@ -4,7 +4,7 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {assertNotReached} from 'chrome://webui-test/chai_assert.js'; import {createCrostiniForTest} from '../../background/js/mock_crostini.js';
diff --git a/ui/file_manager/file_manager/foreground/js/toolbar_controller.js b/ui/file_manager/file_manager/foreground/js/toolbar_controller.js index 29c1f46..ec4dbe4b 100644 --- a/ui/file_manager/file_manager/foreground/js/toolbar_controller.js +++ b/ui/file_manager/file_manager/foreground/js/toolbar_controller.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assert, assertInstanceof} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js'; import {str, strf, util} from '../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn b/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn index c611da5..679cf21 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/ui/BUILD.gn
@@ -135,9 +135,9 @@ "//ui/file_manager/file_manager/common/js:util", "//ui/file_manager/file_manager/foreground/js:actions_model", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:command.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:command", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_item", ] } @@ -148,7 +148,7 @@ "//ui/file_manager/file_manager/common/js:util", "//ui/file_manager/file_manager/foreground/js:mock_actions_model", "//ui/webui/resources/js:assert.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -172,7 +172,7 @@ ":multi_menu_button", "//ui/file_manager/file_manager/common/js:util", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:menu_item", ] externs_list = [ "//ui/file_manager/file_manager/externs/paper_elements.js" ] @@ -183,7 +183,7 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:cr.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", + "//ui/webui/resources/js/cr/ui:command", ] } @@ -231,9 +231,9 @@ "//ui/file_manager/file_manager/foreground/js/metadata:metadata_model", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:cr.m", - "//ui/webui/resources/js/cr/ui:command.m", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:command", + "//ui/webui/resources/js/cr/ui:context_menu_handler", + "//ui/webui/resources/js/cr/ui:menu", ] visibility += [ "//ui/file_manager/file_manager/externs:command_handler_deps" ] @@ -381,9 +381,9 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:util.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:context_menu_handler.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:context_menu_handler", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_item", ] visibility += [ "//ui/file_manager/file_manager/externs:command_handler_deps" ] @@ -508,8 +508,8 @@ js_library("files_menu") { deps = [ "//ui/webui/resources/js:assert.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_item", ] externs_list = [ "//ui/file_manager/file_manager/externs/paper_elements.js" ] } @@ -582,8 +582,8 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:event_tracker.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_item", ] } @@ -594,10 +594,10 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:event_tracker.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu.m", - "//ui/webui/resources/js/cr/ui:menu_button.m", - "//ui/webui/resources/js/cr/ui:menu_item.m", - "//ui/webui/resources/js/cr/ui:position_util.m", + "//ui/webui/resources/js/cr/ui:menu", + "//ui/webui/resources/js/cr/ui:menu_button", + "//ui/webui/resources/js/cr/ui:menu_item", + "//ui/webui/resources/js/cr/ui:position_util", ] } @@ -608,8 +608,8 @@ "//ui/file_manager/file_manager/common/js:util", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:command.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:command", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -630,7 +630,7 @@ "//ui/file_manager/file_manager/foreground/js:providers_model", "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js/cr:ui.m", - "//ui/webui/resources/js/cr/ui:menu.m", + "//ui/webui/resources/js/cr/ui:menu", ] } @@ -677,7 +677,7 @@ "//ui/webui/resources/js/cr/ui:list.m", "//ui/webui/resources/js/cr/ui:list_item.m", "//ui/webui/resources/js/cr/ui:list_single_selection_model.m", - "//ui/webui/resources/js/cr/ui:position_util.m", + "//ui/webui/resources/js/cr/ui:position_util", ] }
diff --git a/ui/file_manager/file_manager/foreground/js/ui/actions_submenu.js b/ui/file_manager/file_manager/foreground/js/ui/actions_submenu.js index e3d1007..a0415b2 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/actions_submenu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/actions_submenu.js
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js'; import {util} from '../../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/actions_submenu_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/actions_submenu_unittest.js index 07c3b89d4..b3a0aaa 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/actions_submenu_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/ui/actions_submenu_unittest.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assertInstanceof} from 'chrome://resources/js/assert.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {util} from '../../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/autocomplete_list.js b/ui/file_manager/file_manager/foreground/js/ui/autocomplete_list.js index afb623e..78394bb 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/autocomplete_list.js +++ b/ui/file_manager/file_manager/foreground/js/ui/autocomplete_list.js
@@ -7,7 +7,7 @@ import {List} from 'chrome://resources/js/cr/ui/list.m.js'; import {ListItem} from 'chrome://resources/js/cr/ui/list_item.m.js'; import {ListSingleSelectionModel} from 'chrome://resources/js/cr/ui/list_single_selection_model.m.js'; -import {AnchorType, positionPopupAroundElement} from 'chrome://resources/js/cr/ui/position_util.m.js'; +import {AnchorType, positionPopupAroundElement} from 'chrome://resources/js/cr/ui/position_util.js'; /**
diff --git a/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner.js b/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner.js index 687a176..f5c05b4 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner.js +++ b/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {assertInstanceof} from 'chrome://resources/js/assert.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {util} from '../../../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner_unittest.js index 76bd8d8..fab45956 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/ui/banners/state_banner_unittest.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {mockUtilVisitURL} from '../../../../common/js/mock_util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/combobutton.js b/ui/file_manager/file_manager/foreground/js/ui/combobutton.js index d53b2cf..da1ea5f 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/combobutton.js +++ b/ui/file_manager/file_manager/foreground/js/ui/combobutton.js
@@ -4,7 +4,7 @@ import {getPropertyDescriptor, PropertyKind} from 'chrome://resources/js/cr.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {util} from '../../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js b/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js index 59f62d5..10d3d3c 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js +++ b/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js
@@ -9,7 +9,7 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {getPropertyDescriptor, PropertyKind} from 'chrome://resources/js/cr.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; /** * Creates a new button element.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js index 0b05527..56a40e00 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js +++ b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js
@@ -4,9 +4,9 @@ import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {dispatchSimpleEvent, getPropertyDescriptor, PropertyKind} from 'chrome://resources/js/cr.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {FileType} from '../../../common/js/file_type.js'; import {vmTypeToIconName} from '../../../common/js/icon_util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js index c83846776..7e4deaf9 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js
@@ -4,9 +4,9 @@ import {assertInstanceof} from 'chrome://resources/js/assert.m.js'; import {decorate, define as crUiDefine} from 'chrome://resources/js/cr/ui.m.js'; -import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {contextMenuHandler} from 'chrome://resources/js/cr/ui/context_menu_handler.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {queryRequiredElement} from 'chrome://resources/js/util.m.js'; import {DialogType} from '../../../common/js/dialog_type.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/files_menu.js b/ui/file_manager/file_manager/foreground/js/ui/files_menu.js index 029f38b..c500240 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/files_menu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/files_menu.js
@@ -3,8 +3,8 @@ // found in the LICENSE file. import {assertInstanceof} from 'chrome://resources/js/assert.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; /** * Menu item with ripple animation.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js b/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js index 67784152..c20d0b7 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/multi_menu.js
@@ -4,8 +4,8 @@ import {assertInstanceof} from 'chrome://resources/js/assert.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; /**
diff --git a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_button.js b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_button.js index a83d402..a29f0bb 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_button.js +++ b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_button.js
@@ -4,10 +4,10 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; -import {HideType} from 'chrome://resources/js/cr/ui/menu_button.m.js'; -import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.m.js'; -import {AnchorType, positionPopupAroundElement} from 'chrome://resources/js/cr/ui/position_util.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; +import {HideType} from 'chrome://resources/js/cr/ui/menu_button.js'; +import {MenuItem} from 'chrome://resources/js/cr/ui/menu_item.js'; +import {AnchorType, positionPopupAroundElement} from 'chrome://resources/js/cr/ui/position_util.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {util} from '../../../common/js/util.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js index 1e7583f..26883814 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/ui/multi_menu_unittest.js
@@ -4,8 +4,8 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/providers_menu.js b/ui/file_manager/file_manager/foreground/js/ui/providers_menu.js index f79073cc..9eebbcb 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/providers_menu.js +++ b/ui/file_manager/file_manager/foreground/js/ui/providers_menu.js
@@ -4,7 +4,7 @@ import {assert} from 'chrome://resources/js/assert.m.js'; import {decorate} from 'chrome://resources/js/cr/ui.m.js'; -import {Menu} from 'chrome://resources/js/cr/ui/menu.m.js'; +import {Menu} from 'chrome://resources/js/cr/ui/menu.js'; import {util} from '../../../common/js/util.js'; import {ProvidersModel} from '../providers_model.js';
diff --git a/ui/file_manager/file_manager/foreground/js/webui_command_extender.js b/ui/file_manager/file_manager/foreground/js/webui_command_extender.js index da8587d..5470a58 100644 --- a/ui/file_manager/file_manager/foreground/js/webui_command_extender.js +++ b/ui/file_manager/file_manager/foreground/js/webui_command_extender.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {dispatchPropertyChange} from 'chrome://resources/js/cr.m.js'; -import {Command} from 'chrome://resources/js/cr/ui/command.m.js'; +import {Command} from 'chrome://resources/js/cr/ui/command.js'; /** * Sets 'hidden' property of a Command instance and dispatches
diff --git a/ui/file_manager/file_manager_resources.grd b/ui/file_manager/file_manager_resources.grd index c6b963c..c03502b1 100644 --- a/ui/file_manager/file_manager_resources.grd +++ b/ui/file_manager/file_manager_resources.grd
@@ -29,21 +29,6 @@ <include name="IDR_FILE_MANAGER_ICON_192" file="file_manager/common/images/icon192.png" type="BINDATA" /> <include name="IDR_FILE_MANAGER_ICON_256" file="file_manager/common/images/icon256.png" type="BINDATA" /> - <!-- The AudioPlayer app pages and scripts. --> - <include name="IDR_AUDIO_PLAYER_MANIFEST" file="audio_player/manifest.json" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_BACKGROUND_HTML" file="audio_player/background.html" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_MODULE" file="audio_player/audio_player.html" allowexternalscript="true" flattenhtml="true" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_FAVICON_16" file="audio_player/icons/audio-player-favicon-16.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_FAVICON_32" file="audio_player/icons/audio-player-favicon-32.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_16" file="audio_player/icons/audio-player-16.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_32" file="audio_player/icons/audio-player-32.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_48" file="audio_player/icons/audio-player-48.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_64" file="audio_player/icons/audio-player-64.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_96" file="audio_player/icons/audio-player-96.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_128" file="audio_player/icons/audio-player-128.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_192" file="audio_player/icons/audio-player-192.png" type="BINDATA" /> - <include name="IDR_AUDIO_PLAYER_ICON_256" file="audio_player/icons/audio-player-256.png" type="BINDATA" /> - <!-- Image loader extension manifest and scripts. --> <if expr="chromeos_ash"> <include name="IDR_IMAGE_LOADER_MANIFEST" file="image_loader/manifest.json" type="BINDATA" />
diff --git a/ui/file_manager/integration_tests/audio_player/OWNERS b/ui/file_manager/integration_tests/audio_player/OWNERS deleted file mode 100644 index 13c6f49f..0000000 --- a/ui/file_manager/integration_tests/audio_player/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -tapted@chromium.org
diff --git a/ui/file_manager/integration_tests/audio_player/background.html b/ui/file_manager/integration_tests/audio_player/background.html deleted file mode 100644 index dfb4d4e..0000000 --- a/ui/file_manager/integration_tests/audio_player/background.html +++ /dev/null
@@ -1,4 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> - -<script type="module" src="background.js"></script>
diff --git a/ui/file_manager/integration_tests/audio_player/background.js b/ui/file_manager/integration_tests/audio_player/background.js deleted file mode 100644 index ed113a2..0000000 --- a/ui/file_manager/integration_tests/audio_player/background.js +++ /dev/null
@@ -1,110 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import './click_control_buttons.js'; -import './open_audio_files.js'; - -import {RemoteCall} from '../remote_call.js'; -import {addEntries, RootPath, sendBrowserTestCommand, testPromiseAndApps} from '../test_util.js'; -import {testcase} from '../testcase.js'; - -/* eslint-disable no-var */ - -/** - * Extension ID of audio player. - * @type {string} - * @const - */ -export const AUDIO_PLAYER_APP_ID = 'cjbfomnbifhcdnihkgipgfcihmgjfhbf'; - -export const remoteCallAudioPlayer = new RemoteCall(AUDIO_PLAYER_APP_ID); - -/** - * Launches the audio player with the given entries. - * - * @param {string} testVolumeName Test volume name passed to the addEntries - * function. Either 'drive' or 'local'. - * @param {VolumeManagerCommon.VolumeType} volumeType Volume type. - * @param {Array<TestEntryInfo>} entries Entries to be parepared and passed to - * the application. - * @param {Array<TestEntryInfo>=} opt_selected Entries to be selected. Should - * be a sub-set of the entries argument. - * @return {Promise} Promise to be fulfilled with the audio player element. - */ -export function launch(testVolumeName, volumeType, entries, opt_selected) { - var entriesPromise = addEntries([testVolumeName], entries).then(function() { - var selectedEntries = opt_selected || entries; - var selectedEntryNames = selectedEntries.map(function(entry) { - return entry.nameText; - }); - return remoteCallAudioPlayer.getFilesUnderVolume( - volumeType, selectedEntryNames); - }); - - var appWindow = null; - return entriesPromise.then(function(urls) { - return remoteCallAudioPlayer.callRemoteTestUtil( - 'openAudioPlayer', null, [urls]); - }).then(function(windowId) { - appWindow = windowId; - return remoteCallAudioPlayer.waitForElement(appWindow, 'body'); - }).then(function() { - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appWindow, 'audio-player[playing]'), - ]); - }).then(function(args) { - return [appWindow, args[0]]; - }); -} - -/** - * When the FileManagerBrowserTest harness loads this test extension, request - * configuration and other details from that harness, including the test case - * name to run. Use the configuration/details to setup the test ennvironment, - * then run the test case using chrome.test.RunTests. - */ -window.addEventListener('load', function() { - var steps = [ - // Request the guest mode state. - function() { - sendBrowserTestCommand({name: 'isInGuestMode'}, steps.shift()); - }, - // Request the root entry paths. - function(mode) { - if (JSON.parse(mode) != chrome.extension.inIncognitoContext) { - return; - } - sendBrowserTestCommand({name: 'getRootPaths'}, steps.shift()); - }, - // Request the test case name. - function(paths) { - var roots = JSON.parse(paths); - RootPath.DOWNLOADS = roots.downloads; - RootPath.DRIVE = roots.drive; - sendBrowserTestCommand({name: 'getTestName'}, steps.shift()); - }, - // Run the test case. - function(testCaseName) { - // Get the test function from testcase namespace testCaseName. - var test = testcase[testCaseName]; - // Verify test is an unnamed (aka 'anonymous') Function. - if (!(test instanceof Function) || test.name) { - chrome.test.fail('[' + testCaseName + '] not found.'); - return; - } - // Define the test case and its name for chrome.test logging. - test.generatedName = testCaseName; - var testCaseSymbol = Symbol(testCaseName); - var testCase = { - [testCaseSymbol] :() => { - return testPromiseAndApps(test(), [remoteCallAudioPlayer]); - }, - }; - // Run the test. - chrome.test.runTests([testCase[testCaseSymbol]]); - }, - ]; - steps.shift()(); -});
diff --git a/ui/file_manager/integration_tests/audio_player/click_control_buttons.js b/ui/file_manager/integration_tests/audio_player/click_control_buttons.js deleted file mode 100644 index d0fd0b7..0000000 --- a/ui/file_manager/integration_tests/audio_player/click_control_buttons.js +++ /dev/null
@@ -1,379 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {ENTRIES, sendTestMessage} from '../test_util.js'; -import {testcase} from '../testcase.js'; - -import {launch, remoteCallAudioPlayer} from './background.js'; - -/* eslint-disable no-var */ - -/** - * @param {string} query Query for an element inside <track-list> element. - * @return {!Array<string>} Deep query selector for an element inside - * <track-list> polymer element. - */ -function trackListQuery(query) { - return ['audio-player', 'track-list', query]; -} - -/** - * @param {!Array<string>|string} query Query for an element inside - * <control-panel> element. - * @return {!Array<string>} Deep query selector for an element inside - * <control-panel> polymer element. - */ -function controlPanelQuery(query) { - return ['audio-player', 'control-panel'].concat(query); -} - -/** - * Confirms that clicking the play button changes the audio player state and - * updates the play button label. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.togglePlayState = function() { - var openAudio = launch('local', 'downloads', [ENTRIES.beautiful]); - var appId; - return openAudio - .then(function(args) { - appId = args[0]; - }) - .then(function() { - // Audio player should start playing automatically, - return remoteCallAudioPlayer.waitForElement( - appId, 'audio-player[playing]'); - }) - .then(function() { - // .. and the play button label should be 'Pause'. - return remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Pause"]')]); - }) - .then(function() { - - // First test a media key, before any element may have acquired focus. - return remoteCallAudioPlayer.fakeKeyDown( - appId, null, 'MediaPlayPause', false, false, false); - }) - .then(function(result) { - chrome.test.assertTrue(!!result, 'fakeKeyDown failed.'); - return remoteCallAudioPlayer.waitForElement( - appId, 'audio-player:not([playing])'); - }) - .then(function(element) { - chrome.test.assertTrue(!!element); - return remoteCallAudioPlayer.fakeKeyDown( - appId, null, 'MediaPlayPause', false, false, false); - }) - .then(function(result) { - chrome.test.assertTrue(!!result, 'fakeKeyDown failed.'); - return remoteCallAudioPlayer.waitForElement( - appId, 'audio-player[playing]'); - }) - .then(function(element) { - chrome.test.assertTrue(!!element); - - // Clicking on the play button should Play. - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#play')]); - }) - .then(function(result) { - chrome.test.assertTrue(!!result, 'fakeMouseClick failed.'); - // ... change the audio playback state to pause, - return remoteCallAudioPlayer.waitForElement( - appId, 'audio-player:not([playing])'); - }) - .then(function() { - // ... and the play button label should be 'Play'. - return remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Play"]')]); - }) - .then(function() { - // Clicking on the play button again should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#play')]); - }) - .then(function(result) { - chrome.test.assertTrue(!!result, 'fakeMouseClick failed.'); - // ... change the audio playback state to playing, - return remoteCallAudioPlayer.waitForElement( - appId, 'audio-player[playing]'); - }) - .then(function() { - // ... and the play button label should be 'Pause'. - return remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Pause"]')]); - }); -}; - - -/** - * Confirms that native media keys are dispatched correctly. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.mediaKeyNative = function() { - const openAudio = launch('local', 'downloads', [ENTRIES.beautiful]); - let appId; - function ensurePlaying() { - return remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]') - .then((element) => { - chrome.test.assertTrue(!!element, 'Not Playing.'); - }); - } - function ensurePaused() { - return remoteCallAudioPlayer - .waitForElement(appId, 'audio-player:not([playing])') - .then((element) => { - chrome.test.assertTrue(!!element, 'Not Paused.'); - }); - } - function sendMediaKey() { - return sendTestMessage({name: 'dispatchNativeMediaKey'}).then((result) => { - chrome.test.assertEq( - result, 'mediaKeyDispatched', 'Key dispatch failure'); - }); - } - function pauseAndUnpause() { - // Audio player should be playing when this is called, - return Promise.resolve() - .then(ensurePlaying) - .then(sendMediaKey) - .then(ensurePaused) - .then(sendMediaKey) - .then(ensurePlaying); - } - function enableTabletMode() { - return sendTestMessage({name: 'enableTabletMode'}).then((result) => { - chrome.test.assertEq(result, 'tabletModeEnabled'); - }); - } - return openAudio - .then((args) => { - appId = args[0]; - }) - .then(pauseAndUnpause) - .then(enableTabletMode) - .then(pauseAndUnpause); -}; - -/** - * Confirms that the AudioPlayer default volume is 50, and that clicking the - * volume button mutes / unmutes the volume. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.changeVolumeLevel = function() { - var openAudio = launch('local', 'downloads', [ENTRIES.beautiful]); - var appId; - return openAudio - .then(function(args) { - appId = args[0]; - }) - .then(function() { - // The Audio Player default volume level should be 50. - return remoteCallAudioPlayer.waitForElement( - appId, [['audio-player', 'control-panel[volume="50"]']]); - }) - .then(function() { - // Clicking the volume button should mute the player. - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, ['#volumeButton']); - }) - .then(function() { - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, [['audio-player', 'control-panel[volume="0"]']]), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#volumeButton[aria-label="Unmute"]')]), - ]); - }) - .then(function() { - // Clicking it again should unmute and restore the volume. - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, ['#volumeButton']); - }) - .then(function() { - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, [['audio-player', 'control-panel[volume="50"]']]), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#volumeButton[aria-label="Mute"]')]), - ]); - }); -}; - -/** - * Confirms that the Audio Player active track changes and plays when a user - * clicks the "next" button. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.changeTracks = function() { - var openAudio = launch('local', 'downloads', - [ENTRIES.beautiful, ENTRIES.newlyAdded]); - var appId; - return openAudio.then(function(args) { - appId = args[0]; - }).then(function() { - // Audio player starts playing automatically - return Promise.all([ - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Pause"]')]), - ]); - }).then(function() { - // ... and track 0 should be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the play button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#play')]); - }).then(function(result) { - chrome.test.assertTrue(!!result, 'failed to click play on track #1'); - // ... change the playback state to pause - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, 'audio-player:not([playing])'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Play"]')]), - ]); - }).then(function() { - // ... and track 0 should still be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the player's "next" button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#next')]); - }).then(function(result) { - chrome.test.assertTrue(!!result, 'failed to click play on #next button'); - // ... activate and play track 1. - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="1"][active]')]), - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - ]); - }); -}; - -/** - * Confirms that the track-list expands when the play-list button is clicked, - * then clicking on a track in the play-list, plays that track. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.changeTracksPlayList = function() { - var openAudio = launch('local', 'downloads', - [ENTRIES.beautiful, ENTRIES.newlyAdded]); - var appId; - return openAudio.then(function(args) { - appId = args[0]; - }).then(function() { - // Audio player starts playing automatically - return Promise.all([ - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Pause"]')]), - ]); - }).then(function() { - // ... and track 0 should be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the play button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#play')]); - }).then(function() { - // ... change the playback state to pause, - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, 'audio-player:not([playing])'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Play"]')]), - ]); - }).then(function() { - // ... and track 0 should still be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the play-list button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#playList')]); - }).then(function() { - // ... expand the Audio Player track-list. - return remoteCallAudioPlayer.waitForElement( - appId, ['audio-player', 'track-list[expanded]']); - }).then(function() { - // Clicking on a track (track 0 here) should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [trackListQuery('.track[index="0"]')]); - }).then(function() { - // ... activate and start playing that track. - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, trackListQuery('.track[index="0"][active]')), - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - ]); - }); -}; - -/** - * Confirms that the track-list expands when the play-list button is clicked, - * then clicking on a track 'Play' icon in the play-list, plays that track. - * @return {Promise} Promise to be fulfilled on success. - */ -testcase.changeTracksPlayListIcon = function() { - var openAudio = launch('local', 'downloads', - [ENTRIES.beautiful, ENTRIES.newlyAdded]); - var appId; - return openAudio.then(function(args) { - appId = args[0]; - }).then(function() { - // Audio player starts playing automatically - return Promise.all([ - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Pause"]')]), - ]); - }).then(function() { - // ... and track 0 should be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the play button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#play')]); - }).then(function() { - // ... change the playback state to pause, - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, 'audio-player:not([playing])'), - remoteCallAudioPlayer.waitForElement( - appId, [controlPanelQuery('#play[aria-label="Play"]')]), - ]); - }).then(function() { - // ... and track 0 should still be active. - return remoteCallAudioPlayer.waitForElement( - appId, [trackListQuery('.track[index="0"][active]')]); - }).then(function() { - // Clicking the play-list button should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [controlPanelQuery('#playList')]); - }).then(function() { - // ... expand the Audio Player track-list. - return remoteCallAudioPlayer.waitForElement( - appId, ['audio-player', 'track-list[expanded]']); - }).then(function() { - // Clicking a track (track 1 here) 'Play' icon should - return remoteCallAudioPlayer.callRemoteTestUtil( - 'fakeMouseClick', appId, [trackListQuery('.track[index="1"] .icon')]); - }).then(function(result) { - chrome.test.assertTrue(!!result, 'failed to click play on track #1'); - // ... activate and start playing that track. - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appId, trackListQuery('.track[index="1"][active]')), - remoteCallAudioPlayer.waitForElement(appId, 'audio-player[playing]'), - ]); - }); -}; -
diff --git a/ui/file_manager/integration_tests/audio_player/open_audio_files.js b/ui/file_manager/integration_tests/audio_player/open_audio_files.js deleted file mode 100644 index 7698e99b..0000000 --- a/ui/file_manager/integration_tests/audio_player/open_audio_files.js +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {ENTRIES} from '../test_util.js'; -import {testcase} from '../testcase.js'; - -import {launch, remoteCallAudioPlayer} from './background.js'; - -/* eslint-disable no-var */ - -/** - * Test of Audio Palyer window and initial elements. - * - * @param {string} volumeName Test volume name passed to the addEntries - * @param {VolumeManagerCommon.VolumeType} volumeType Volume type. - * @return {Promise} Promise to be fulfilled with on success. - */ -function openAudioPlayer(volumeName, volumeType) { - var test = launch(volumeName, volumeType, [ENTRIES.newlyAdded]); - return test.then(function(args) { - var appWindow = args[0]; - return Promise.all([ - remoteCallAudioPlayer.waitForElement( - appWindow, [['audio-player', 'track-list']]), - remoteCallAudioPlayer.waitForElement( - appWindow, [['audio-player', 'control-panel']]), - remoteCallAudioPlayer.waitForElement( - appWindow, [['audio-player', 'audio']]), - ]); - }); -} - -/** - * The open audio player test for Downloads. - * @return {Promise} Promise to be fulfilled with on success. - */ -testcase.openAudioOnDownloads = function() { - return openAudioPlayer('local', 'downloads'); -}; - -/** - * The open audio player test for Drive - * @return {Promise} Promise to be fulfilled with on success. - */ -testcase.openAudioOnDrive = function() { - return openAudioPlayer('drive', 'drive'); -};
diff --git a/ui/file_manager/integration_tests/audio_player_test_manifest.json b/ui/file_manager/integration_tests/audio_player_test_manifest.json deleted file mode 100644 index 0056f11c..0000000 --- a/ui/file_manager/integration_tests/audio_player_test_manifest.json +++ /dev/null
@@ -1,18 +0,0 @@ -{ - // chrome-extension:/ddabbgbggambiildohfagdkliahiecfl/ - "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqyMPfoy88DMSxVONd2NEK9u7OQfKjWQujB541dn+NNSFUEqSF6lYehgX77x7eGEs1DCHhZynX71o5JYLe2oeWt/HBDR/tWpdwwh80owIQDwaKJrfRtisyVL++dMmf0pNjFv1F5tFXObO84F22oZyBA89Z0S0jNlHjyVzm7U4BwbDHhHBoGXGJxf5AXL5quLdwlVe69d6ZjiSkYvaAAGwwYDWuqG8VFaZuz4Onh/bSYocBtd6rpeRwS7tAkTugCU0Mnivaj/x9WYajomcg+/QSQhwjbH+9+8zqsmpnKIeCY/qxadI9CYMMyg3Kbo53THQKRe6/DaXazgthMqAL9TGAwIDAQAB", - "name": "Audio Player test extension", - "version": "0.1", - "manifest_version": 2, - "description": "Audio Player test extension", - "web_accessible_resources": ["*"], - "background": { - "page": "audio_player/background.html" - }, - "incognito" : "split", - "permissions": [ - "commandLinePrivate", - "chrome://resources/" - ], - "content_security_policy": "script-src 'self' chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj chrome://resources ;" -}
diff --git a/ui/file_manager/integration_tests/file_manager/background.js b/ui/file_manager/integration_tests/file_manager/background.js index 732050e..9f29ed2 100644 --- a/ui/file_manager/integration_tests/file_manager/background.js +++ b/ui/file_manager/integration_tests/file_manager/background.js
@@ -71,15 +71,6 @@ export let remoteCall; /** - * Extension ID of Audio Player. - * @type {string} - * @const - */ -export const AUDIO_PLAYER_APP_ID = 'cjbfomnbifhcdnihkgipgfcihmgjfhbf'; - -export const audioPlayerApp = new RemoteCall(AUDIO_PLAYER_APP_ID); - -/** * Opens a Files app's main window. * * TODO(mtomasz): Pass a volumeId or an enum value instead of full paths.
diff --git a/ui/gfx/x/xlib_support.cc b/ui/gfx/x/xlib_support.cc index 281c318..00d979df 100644 --- a/ui/gfx/x/xlib_support.cc +++ b/ui/gfx/x/xlib_support.cc
@@ -32,7 +32,7 @@ } // namespace -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void InitXlib() { auto* xlib_loader = GetXlibLoader(); if (xlib_loader->loaded()) @@ -53,17 +53,17 @@ SetXlibErrorHandler(); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void SetXlibErrorHandler() { GetXlibLoader()->XSetErrorHandler(XlibErrorHandler); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void XlibFree(void* data) { GetXlibLoader()->XFree(data); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM XlibDisplay::XlibDisplay(const std::string& address) { InitXlib(); @@ -71,7 +71,7 @@ : address.c_str()); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM XlibDisplay::~XlibDisplay() { if (!display_) return; @@ -84,7 +84,7 @@ loader->XCloseDisplay(display_); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM XlibDisplayWrapper::XlibDisplayWrapper(struct _XDisplay* display, XlibDisplayType type) : display_(display), type_(type) { @@ -94,7 +94,7 @@ GetXlibLoader()->XSynchronize(display_, true); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM XlibDisplayWrapper::~XlibDisplayWrapper() { if (!display_) return; @@ -119,7 +119,7 @@ return *this; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM struct xcb_connection_t* XlibDisplayWrapper::GetXcbConnection() { return GetXlibXcbLoader()->XGetXCBConnection(display_); }
diff --git a/ui/gl/direct_composition_child_surface_win.cc b/ui/gl/direct_composition_child_surface_win.cc index 823b96d..f94fc66 100644 --- a/ui/gl/direct_composition_child_surface_win.cc +++ b/ui/gl/direct_composition_child_surface_win.cc
@@ -186,7 +186,7 @@ } TRACE_EVENT2( "gpu", "DirectCompositionChildSurfaceWin::PresentSwapChain", - "interval", interval, "dirty_rect", + "has_alpha", has_alpha_, "dirty_rect", actually_force_full_damage ? "full_damage" : swap_rect_.ToString()); if (actually_force_full_damage) { hr = swap_chain_->Present(interval, flags);
diff --git a/ui/gtk/gtk_compat.cc b/ui/gtk/gtk_compat.cc index b5c7af5..2ba5b4c4 100644 --- a/ui/gtk/gtk_compat.cc +++ b/ui/gtk/gtk_compat.cc
@@ -18,7 +18,7 @@ namespace gtk { // IMPORTANT: All functions in this file that call dlsym()'ed -// functions should be annotated with DISABLE_CFI_ICALL. +// functions should be annotated with DISABLE_CFI_DLSYM. namespace { @@ -150,7 +150,7 @@ return GtkVersion() >= base::Version({major, minor, micro}); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM bool GtkInitCheck(int* argc, char** argv) { static void* gtk_init_check = DlSym(GetLibGtk(), "gtk_init_check"); if (GtkCheckVersion(4)) @@ -163,7 +163,7 @@ } } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM gfx::Insets GtkStyleContextGetPadding(GtkStyleContext* context) { static void* get_padding = DlSym(GetLibGtk(), "gtk_style_context_get_padding"); @@ -177,7 +177,7 @@ return InsetsFromGtkBorder(padding); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM gfx::Insets GtkStyleContextGetBorder(GtkStyleContext* context) { static void* get_border = DlSym(GetLibGtk(), "gtk_style_context_get_border"); GtkBorder border; @@ -190,7 +190,7 @@ return InsetsFromGtkBorder(border); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM gfx::Insets GtkStyleContextGetMargin(GtkStyleContext* context) { static void* get_margin = DlSym(GetLibGtk(), "gtk_style_context_get_margin"); GtkBorder margin; @@ -203,7 +203,7 @@ return InsetsFromGtkBorder(margin); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM SkColor GtkStyleContextGetColor(GtkStyleContext* context) { static void* get_color = DlSym(GetLibGtk(), "gtk_style_context_get_color"); if (GtkCheckVersion(4)) { @@ -217,7 +217,7 @@ return GdkRgbaToSkColor(color); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM SkColor GtkStyleContextGetBackgroundColor(GtkStyleContext* context) { DCHECK(!GtkCheckVersion(4)); static void* get_bg_color = @@ -228,7 +228,7 @@ return GdkRgbaToSkColor(color); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM absl::optional<SkColor> GtkStyleContextLookupColor(GtkStyleContext* context, const gchar* color_name) { DCHECK(!GtkCheckVersion(4)); @@ -242,7 +242,7 @@ return absl::nullopt; } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM bool GtkImContextFilterKeypress(GtkIMContext* context, GdkEventKey* event) { static void* filter = DlSym(GetLibGtk(), "gtk_im_context_filter_keypress"); if (GtkCheckVersion(4)) { @@ -252,7 +252,7 @@ return DlCast<bool(GtkIMContext*, GdkEventKey*)>(filter)(context, event); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM bool GtkFileChooserSetCurrentFolder(GtkFileChooser* dialog, const base::FilePath& path) { static void* set = DlSym(GetLibGtk(), "gtk_file_chooser_set_current_folder"); @@ -265,7 +265,7 @@ path.value().c_str()); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void GtkRenderIcon(GtkStyleContext* context, cairo_t* cr, GdkPixbuf* pixbuf, @@ -284,7 +284,7 @@ } } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM GtkWidget* GtkToplevelWindowNew() { static void* window_new = DlSym(GetLibGtk(), "gtk_window_new"); if (GtkCheckVersion(4)) @@ -292,7 +292,7 @@ return DlCast<GtkWidget*(GtkWindowType)>(window_new)(GTK_WINDOW_TOPLEVEL); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM void GtkCssProviderLoadFromData(GtkCssProvider* css_provider, const char* data, gssize length) { @@ -327,7 +327,7 @@ va_end(args); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM ScopedGObject<GtkIconInfo> Gtk3IconThemeLookupByGiconForScale( GtkIconTheme* theme, GIcon* icon, @@ -342,7 +342,7 @@ lookup)(theme, icon, size, scale, flags)); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM ScopedGObject<GtkIconPaintable> Gtk4IconThemeLookupIcon( GtkIconTheme* theme, const char* icon_name, @@ -358,7 +358,7 @@ lookup)(theme, icon_name, fallbacks, size, scale, direction, flags)); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM ScopedGObject<GtkIconPaintable> Gtk4IconThemeLookupByGicon( GtkIconTheme* theme, GIcon* icon, @@ -374,7 +374,7 @@ theme, icon, size, scale, direction, flags)); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM GtkWidget* GtkFileChooserDialogNew(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, @@ -389,19 +389,19 @@ second_button_text, second_response, nullptr); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM GtkTreeStore* GtkTreeStoreNew(GType type) { static void* create = DlSym(GetLibGtk(), "gtk_tree_store_new"); return DlCast<GtkTreeStore*(gint, ...)>(create)(1, type); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM GdkEventType GdkEventGetEventType(GdkEvent* event) { static void* get = DlSym(GetLibGtk(), "gdk_event_get_event_type"); return DlCast<GdkEventType(GdkEvent*)>(get)(event); } -DISABLE_CFI_ICALL +DISABLE_CFI_DLSYM guint32 GdkEventGetTime(GdkEvent* event) { static void* get = DlSym(GetLibGtk(), "gdk_event_get_time"); return DlCast<guint32(GdkEvent*)>(get)(event);
diff --git a/ui/message_center/message_center_impl.cc b/ui/message_center/message_center_impl.cc index bb02c85..27ee46fb 100644 --- a/ui/message_center/message_center_impl.cc +++ b/ui/message_center/message_center_impl.cc
@@ -160,33 +160,22 @@ Notification* MessageCenterImpl::FindParentNotification( Notification* notification) { // For a notification to have a parent notification, they must have identical - // origin urls and profile_ids. To make sure that the notifications come from - // the same website for the same user. If either fields are empty there can - // not be a parent notification. Also make sure to only group notifications - // from web pages. + // notifier_ids. To make sure that the notifications come from + // the same website for the same user. Also make sure to only group + // notifications from web pages with valid origin urls. if (notification->origin_url().is_empty() || - notification->notifier_id().profile_id.empty() || notification->notifier_id().type != NotifierType::WEB_PAGE) { return nullptr; } NotificationList::Notifications notifications = - notification_list_->GetNotificationsByOriginUrl( - notification->origin_url()); - - std::string account_id = notification->notifier_id().profile_id; - auto account_match = [&account_id](Notification* notification) { - return account_id == notification->notifier_id().profile_id; - }; + notification_list_->GetNotificationsByNotifierId( + notification->notifier_id()); // `notifications` keeps notifications ordered with the most recent one in the - // front. We do a lookup starting with the oldest notification to find the - // parent notification. - auto parent_notification = - std::find_if(notifications.rbegin(), notifications.rend(), account_match); - - return parent_notification == notifications.rend() ? nullptr - : *parent_notification; + // front. If we have notifications for this notifier_id we return the last + // notification.. + return notifications.size() ? *notifications.rbegin() : nullptr; } Notification* MessageCenterImpl::FindPopupNotificationById(
diff --git a/ui/message_center/views/notification_view_base.h b/ui/message_center/views/notification_view_base.h index e2373320..3603267 100644 --- a/ui/message_center/views/notification_view_base.h +++ b/ui/message_center/views/notification_view_base.h
@@ -390,7 +390,7 @@ // Counter for view layouting, which is used during the CreateOrUpdate* // phases to keep track of the view ordering. See crbug.com/901045 - int left_content_count_; + size_t left_content_count_; std::unique_ptr<ui::EventHandler> click_activator_;
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing.cc b/ui/ozone/platform/wayland/host/wayland_buffer_backing.cc index b4a964b2..f94f87b 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing.cc +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing.cc
@@ -12,8 +12,12 @@ WaylandBufferBacking::WaylandBufferBacking(const WaylandConnection* connection, uint32_t buffer_id, - const gfx::Size& size) - : connection_(connection), buffer_id_(buffer_id), size_(size) { + const gfx::Size& size, + uint32_t format) + : connection_(connection), + format_(format), + buffer_id_(buffer_id), + size_(size) { DCHECK(connection_); DCHECK_NE(buffer_id_, kInvalidBufferId); }
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing.h b/ui/ozone/platform/wayland/host/wayland_buffer_backing.h index 0dd0eb62..96231ac 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing.h +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing.h
@@ -8,6 +8,7 @@ #include "base/callback_forward.h" #include "base/containers/flat_map.h" #include "base/memory/raw_ptr.h" +#include "drm_fourcc.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/native_widget_types.h" #include "ui/ozone/platform/wayland/common/wayland_object.h" @@ -31,9 +32,12 @@ WaylandBufferBacking& operator=(const WaylandBufferBacking&) = delete; WaylandBufferBacking(const WaylandConnection* connection, uint32_t buffer_id, - const gfx::Size& size); + const gfx::Size& size, + uint32_t format = DRM_FORMAT_INVALID); virtual ~WaylandBufferBacking(); + const WaylandConnection* connection() const { return connection_; } + uint32_t format() const { return format_; } uint32_t id() const { return buffer_id_; } gfx::Size size() const { return size_; } @@ -49,11 +53,13 @@ // Same as above but does not do the requesting. WaylandBufferHandle* GetBufferHandle(WaylandSurface* requestor); - protected: + private: // Non-owned pointer to the main connection. raw_ptr<const WaylandConnection> connection_; - private: + // DRM buffer format if specified, otherwise DRM_FORMAT_INVALID (0) + const uint32_t format_; + // Requests a new wl_buffer. |callback| will be run with the created wl_buffer // object when creation is complete. virtual void RequestBufferHandle(
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.cc b/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.cc index 30232ffd..8d7d99b 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.cc +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.cc
@@ -19,12 +19,11 @@ uint32_t format, uint32_t planes_count, uint32_t buffer_id) - : WaylandBufferBacking(connection, buffer_id, size), + : WaylandBufferBacking(connection, buffer_id, size, format), fd_(std::move(fd)), strides_(std::move(strides)), offsets_(std::move(offsets)), modifiers_(std::move(modifiers)), - format_(format), planes_count_(planes_count) {} WaylandBufferBackingDmabuf::~WaylandBufferBackingDmabuf() = default; @@ -33,8 +32,8 @@ base::OnceCallback<void(wl::Object<wl_buffer>)> callback) { DCHECK(!callback.is_null()); DCHECK(fd_.is_valid()); - connection_->wayland_buffer_factory()->CreateDmabufBuffer( - fd_, size(), strides_, offsets_, modifiers_, format_, planes_count_, + connection()->wayland_buffer_factory()->CreateDmabufBuffer( + fd_, size(), strides_, offsets_, modifiers_, format(), planes_count_, std::move(callback)); if (UseExplicitSyncRelease())
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.h b/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.h index 2d524ac..e86f029 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.h +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing_dmabuf.h
@@ -37,7 +37,6 @@ const std::vector<uint32_t> strides_; const std::vector<uint32_t> offsets_; const std::vector<uint64_t> modifiers_; - const uint32_t format_; const uint32_t planes_count_; };
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing_shm.cc b/ui/ozone/platform/wayland/host/wayland_buffer_backing_shm.cc index 2854b90..e6dc7d65 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing_shm.cc +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing_shm.cc
@@ -40,7 +40,7 @@ const bool with_alpha_channel = true; #endif std::move(callback).Run( - connection_->wayland_buffer_factory()->CreateShmBuffer( + connection()->wayland_buffer_factory()->CreateShmBuffer( fd_, length_, size(), with_alpha_channel)); if (UseExplicitSyncRelease()) auto close = std::move(fd_);
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_backing_solid_color.cc b/ui/ozone/platform/wayland/host/wayland_buffer_backing_solid_color.cc index 4c83a4e..f51fdee 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_backing_solid_color.cc +++ b/ui/ozone/platform/wayland/host/wayland_buffer_backing_solid_color.cc
@@ -22,7 +22,8 @@ base::OnceCallback<void(wl::Object<wl_buffer>)> callback) { DCHECK(!callback.is_null()); std::move(callback).Run( - connection_->surface_augmenter()->CreateSolidColorBuffer(color_, size())); + connection()->surface_augmenter()->CreateSolidColorBuffer(color_, + size())); } } // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.cc b/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.cc index a34f69da..dcb1f4f6 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.cc +++ b/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.cc
@@ -245,6 +245,18 @@ return it->second->GetBufferHandle(requestor); } +uint32_t WaylandBufferManagerHost::GetBufferFormat(WaylandSurface* requestor, + uint32_t buffer_id) { + DCHECK(base::CurrentUIThread::IsSet()); + DCHECK(requestor); + + auto it = buffer_backings_.find(buffer_id); + if (it == buffer_backings_.end()) + return DRM_FORMAT_INVALID; + + return it->second.get()->format(); +} + void WaylandBufferManagerHost::CommitOverlays( gfx::AcceleratedWidget widget, uint32_t frame_id,
diff --git a/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h b/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h index fbc1e1b..fda3f9b0 100644 --- a/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h +++ b/ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h
@@ -122,6 +122,10 @@ WaylandBufferHandle* GetBufferHandle(WaylandSurface* requestor, uint32_t buffer_id); + // Gets the buffer format of |buffer_id| used for |requestor| if it is a + // DMA based buffer. + uint32_t GetBufferFormat(WaylandSurface* requestor, uint32_t buffer_id); + // Tells the |buffer_manager_gpu_ptr_| the result of a swap call and provides // it with the presentation feedback. void OnSubmission(gfx::AcceleratedWidget widget,
diff --git a/ui/views/examples/designer_example.cc b/ui/views/examples/designer_example.cc index 3726e45..ed79771 100644 --- a/ui/views/examples/designer_example.cc +++ b/ui/views/examples/designer_example.cc
@@ -300,7 +300,7 @@ if (GetVisible() && attached_view_) { PositionOnView(); if (reorder) - parent()->ReorderChildView(this, -1); + parent()->ReorderChildView(this, parent()->children().size()); } }
diff --git a/ui/views/layout/composite_layout_tests.cc b/ui/views/layout/composite_layout_tests.cc index 78e9238d..6e5df03 100644 --- a/ui/views/layout/composite_layout_tests.cc +++ b/ui/views/layout/composite_layout_tests.cc
@@ -199,12 +199,10 @@ } } - void MoveIcon(int from, int to) { - DCHECK_GE(from, 0); - DCHECK_GE(to, 0); + void MoveIcon(size_t from, size_t to) { DCHECK_NE(from, to); - DCHECK_LT(from, static_cast<int>(children().size()) - 1); - DCHECK_LT(to, static_cast<int>(children().size()) - 1); + DCHECK_LT(from, children().size() - 1); + DCHECK_LT(to, children().size() - 1); ReorderChildView(children()[from], to); }
diff --git a/ui/views/view.cc b/ui/views/view.cc index 7f8f67a..ca209451 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc
@@ -286,16 +286,14 @@ return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget()); } -void View::ReorderChildView(View* view, int index) { +void View::ReorderChildView(View* view, size_t index) { DCHECK_EQ(view->parent_, this); const auto i = std::find(children_.begin(), children_.end(), view); DCHECK(i != children_.end()); // If |view| is already at the desired position, there's nothing to do. - const bool move_to_end = - (index < 0) || (static_cast<size_t>(index) >= children_.size()); - const auto pos = move_to_end ? std::prev(children_.end()) - : std::next(children_.begin(), index); + const auto pos = + std::next(children_.begin(), std::min(index, children_.size() - 1)); if (i == pos) return;
diff --git a/ui/views/view.h b/ui/views/view.h index 2d4c5485..7bb7653 100644 --- a/ui/views/view.h +++ b/ui/views/view.h
@@ -433,11 +433,9 @@ return view; } - // Moves |view| to the specified |index|. A negative value for |index| moves - // the view at the end. - // TODO(crbug.com/1292951): Change `index` to size_t and remove negative - // indexing behavior. - void ReorderChildView(View* view, int index); + // Moves |view| to the specified |index|. An |index| at least as large as that + // of the last child moves the view to the end. + void ReorderChildView(View* view, size_t index); // Removes |view| from this view. The view's parent will change to null. void RemoveChildView(View* view);
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index 3f6ae0f..52f00ad 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -3565,7 +3565,7 @@ ASSERT_EQ(nullptr, foo3->GetNextFocusableView()); // Move |foo2| at the end. - child->ReorderChildView(foo2, -1); + child->ReorderChildView(foo2, child->children().size()); ASSERT_EQ(0u, child->GetIndexOf(foo1)); ASSERT_EQ(1u, child->GetIndexOf(foo3)); ASSERT_EQ(2u, child->GetIndexOf(foo2)); @@ -3574,7 +3574,7 @@ ASSERT_EQ(nullptr, foo2->GetNextFocusableView()); // Move |foo1| at the end. - child->ReorderChildView(foo1, -1); + child->ReorderChildView(foo1, child->children().size()); ASSERT_EQ(0u, child->GetIndexOf(foo3)); ASSERT_EQ(1u, child->GetIndexOf(foo2)); ASSERT_EQ(2u, child->GetIndexOf(foo1)); @@ -4483,7 +4483,7 @@ EXPECT_EQ(c2->layer(), parent_layer->children()[1]); // Move c1 to the front. The layers should have moved too. - content->ReorderChildView(c1, -1); + content->ReorderChildView(c1, content->children().size()); EXPECT_EQ(c1->layer(), parent_layer->children()[1]); EXPECT_EQ(c2->layer(), parent_layer->children()[0]); }
diff --git a/ui/views/widget/window_reorderer_unittest.cc b/ui/views/widget/window_reorderer_unittest.cc index 4fabc4c1..d06110e2 100644 --- a/ui/views/widget/window_reorderer_unittest.cc +++ b/ui/views/widget/window_reorderer_unittest.cc
@@ -97,24 +97,24 @@ // 2) Test the z-order of the windows and layers as a result of reordering the // views. - contents_view->ReorderChildView(host_view1, -1); + contents_view->ReorderChildView(host_view1, contents_view->children().size()); EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); EXPECT_EQ("v w2 w1", ui::test::ChildLayerNamesAsString(*parent_window->layer())); - contents_view->ReorderChildView(host_view2, -1); + contents_view->ReorderChildView(host_view2, contents_view->children().size()); EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); EXPECT_EQ("v w1 w2", ui::test::ChildLayerNamesAsString(*parent_window->layer())); // 3) Test the z-order of the windows and layers as a result of reordering the // views in situations where the window order remains unchanged. - contents_view->ReorderChildView(v, -1); + contents_view->ReorderChildView(v, contents_view->children().size()); EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); EXPECT_EQ("w1 w2 v", ui::test::ChildLayerNamesAsString(*parent_window->layer())); - contents_view->ReorderChildView(host_view2, -1); + contents_view->ReorderChildView(host_view2, contents_view->children().size()); EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); EXPECT_EQ("w1 v w2", ui::test::ChildLayerNamesAsString(*parent_window->layer()));
diff --git a/ui/webui/resources/BUILD.gn b/ui/webui/resources/BUILD.gn index 1f61f4d..7aa89cc68e 100644 --- a/ui/webui/resources/BUILD.gn +++ b/ui/webui/resources/BUILD.gn
@@ -194,9 +194,9 @@ if (is_chromeos_ash || is_fuchsia || is_linux || is_mac || is_win) { checked_in_dts_files += [ - "js/cr/ui/context_menu_handler.m.d.ts", - "js/cr/ui/menu_button.m.d.ts", - "js/cr/ui/menu_item.m.d.ts", + "js/cr/ui/context_menu_handler.d.ts", + "js/cr/ui/menu_button.d.ts", + "js/cr/ui/menu_item.d.ts", ] } @@ -235,7 +235,7 @@ "js/cr/ui.m.js", "js/cr/ui/focus_outline_manager.m.js", "js/cr/ui/focus_row.m.js", - "js/cr/ui/keyboard_shortcut_list.m.js", + "js/cr/ui/keyboard_shortcut_list.js", "js/cr/ui/store.js", "js/event_tracker.m.js", "js/load_time_data.m.js", @@ -247,9 +247,9 @@ if (is_chromeos_ash || is_fuchsia || is_linux || is_mac || is_win) { generate_definitions_js_files += [ - "js/cr/ui/menu.m.js", - "js/cr/ui/command.m.js", - "js/cr/ui/position_util.m.js", + "js/cr/ui/menu.js", + "js/cr/ui/command.js", + "js/cr/ui/position_util.js", ] }
diff --git a/ui/webui/resources/cr_components/app_management/BUILD.gn b/ui/webui/resources/cr_components/app_management/BUILD.gn index 2043f861..d4f505c 100644 --- a/ui/webui/resources/cr_components/app_management/BUILD.gn +++ b/ui/webui/resources/cr_components/app_management/BUILD.gn
@@ -8,22 +8,11 @@ import("//tools/polymer/html_to_wrapper.gni") import("//tools/typescript/ts_library.gni") import("//ui/webui/resources/tools/generate_grd.gni") +import("//ui/webui/webui_features.gni") import("app_management.gni") assert(!is_android && !is_ios) -preprocess_folder_tmp = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/app_management_tmp" -preprocess_folder = - "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/app_management" - -css_to_wrapper("css_wrapper_files") { - in_files = css_files -} - -html_to_wrapper("html_wrapper_files") { - in_files = html_files + html_icons_files -} - mojom("mojo_bindings") { sources = [ "app_management.mojom" ] webui_module_path = "/" @@ -86,22 +75,35 @@ ] } -preprocess_if_expr("preprocess_src") { - visibility = [ ":build_ts" ] - in_folder = "." - out_folder = preprocess_folder_tmp - in_files = ts_files -} +preprocess_folder_tmp = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/app_management_tmp" +preprocess_folder = + "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/app_management" -preprocess_if_expr("preprocess_generated") { - visibility = [ ":build_ts" ] - deps = [ +preprocess_if_expr("preprocess") { + visibility = [ + ":build_ts", ":css_wrapper_files", ":html_wrapper_files", ] - in_folder = target_gen_dir + in_folder = "." out_folder = preprocess_folder_tmp - in_files = html_wrapper_files + css_wrapper_files + in_files = ts_files + html_files + html_icons_files + css_files +} + +html_to_wrapper("html_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp + in_files = html_files + html_icons_files + minify = optimize_webui +} + +css_to_wrapper("css_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp + in_files = css_files + minify = optimize_webui } copy("copy_mojo") { @@ -131,8 +133,9 @@ ] extra_deps = [ ":copy_mojo", - ":preprocess_generated", - ":preprocess_src", + ":css_wrapper_files", + ":html_wrapper_files", + ":preprocess", ] }
diff --git a/ui/webui/resources/cr_components/certificate_manager/BUILD.gn b/ui/webui/resources/cr_components/certificate_manager/BUILD.gn index a3413715..afef6f3 100644 --- a/ui/webui/resources/cr_components/certificate_manager/BUILD.gn +++ b/ui/webui/resources/cr_components/certificate_manager/BUILD.gn
@@ -8,6 +8,7 @@ import("//tools/polymer/html_to_wrapper.gni") import("//tools/typescript/ts_library.gni") import("//ui/webui/resources/tools/generate_grd.gni") +import("//ui/webui/webui_features.gni") import("certificate_manager.gni") assert(use_nss_certs) @@ -15,6 +16,33 @@ preprocess_folder_tmp = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/certificate_manager_tmp" preprocess_folder = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/certificate_manager" +preprocess_if_expr("preprocess") { + visibility = [ + ":build_ts", + ":css_wrapper_files", + ":html_wrapper_files", + ] + in_folder = "." + out_folder = preprocess_folder_tmp + in_files = ts_files + html_files + css_files +} + +css_to_wrapper("css_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp + in_files = css_files + minify = optimize_webui +} + +html_to_wrapper("html_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp + in_files = html_files + minify = optimize_webui +} + ts_library("build_ts") { root_dir = preprocess_folder_tmp out_dir = preprocess_folder @@ -28,36 +56,10 @@ "//ui/webui/resources:library", ] extra_deps = [ - ":preprocess_generated", - ":preprocess_src", - ] -} - -css_to_wrapper("css_wrapper_files") { - visibility = [ ":preprocess_generated" ] - in_files = css_files -} - -html_to_wrapper("html_wrapper_files") { - in_files = html_files -} - -preprocess_if_expr("preprocess_src") { - visibility = [ ":build_ts" ] - in_folder = "." - out_folder = preprocess_folder_tmp - in_files = ts_files -} - -preprocess_if_expr("preprocess_generated") { - visibility = [ ":build_ts" ] - deps = [ ":css_wrapper_files", ":html_wrapper_files", + ":preprocess", ] - in_folder = target_gen_dir - out_folder = preprocess_folder_tmp - in_files = html_wrapper_files + css_wrapper_files } generate_grd("build_grdp") {
diff --git a/ui/webui/resources/cr_components/customize_themes/BUILD.gn b/ui/webui/resources/cr_components/customize_themes/BUILD.gn index 0bf17d9..93d6305f 100644 --- a/ui/webui/resources/cr_components/customize_themes/BUILD.gn +++ b/ui/webui/resources/cr_components/customize_themes/BUILD.gn
@@ -7,6 +7,7 @@ import("//tools/polymer/html_to_wrapper.gni") import("//tools/typescript/ts_library.gni") import("//ui/webui/resources/tools/generate_grd.gni") +import("//ui/webui/webui_features.gni") import("customize_themes.gni") assert(!is_android && !is_ios) @@ -22,16 +23,32 @@ webui_module_path = "chrome://resources/cr_components/customize_themes/" } -html_to_wrapper("html_wrapper_files") { - in_files = html_files -} - # Output folder used to hold preprocess_if_expr() output. preprocess_folder_tmp = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/customize_themes_tmp" # Output folder used to hold ts_library() output. preprocess_folder = "$root_gen_dir/ui/webui/resources/preprocessed/cr_components/customize_themes" +preprocess_if_expr("preprocess") { + in_folder = "." + out_folder = preprocess_folder_tmp + in_files = ts_files + html_files +} + +html_to_wrapper("html_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp + in_files = html_files + minify = optimize_webui +} + +copy("copy_mojom") { + deps = [ ":mojom_webui_js" ] + sources = [ "$root_gen_dir/mojom-webui/ui/webui/resources/cr_components/customize_themes/customize_themes.mojom-webui.js" ] + outputs = [ "$preprocess_folder_tmp/{{source_file_part}}" ] +} + ts_library("build_ts") { root_dir = preprocess_folder_tmp out_dir = preprocess_folder @@ -46,30 +63,11 @@ ] extra_deps = [ ":copy_mojom", - ":preprocess_generated", - ":preprocess_src", + ":html_wrapper_files", + ":preprocess", ] } -preprocess_if_expr("preprocess_src") { - in_folder = "." - out_folder = preprocess_folder_tmp - in_files = ts_files -} - -preprocess_if_expr("preprocess_generated") { - deps = [ ":html_wrapper_files" ] - in_folder = target_gen_dir - out_folder = preprocess_folder_tmp - in_files = html_wrapper_files -} - -copy("copy_mojom") { - deps = [ ":mojom_webui_js" ] - sources = [ "$root_gen_dir/mojom-webui/ui/webui/resources/cr_components/customize_themes/customize_themes.mojom-webui.js" ] - outputs = [ "$preprocess_folder_tmp/{{source_file_part}}" ] -} - generate_grd("build_grdp") { grd_prefix = "cr_components_customize_themes" out_grd = "$target_gen_dir/resources.grdp"
diff --git a/ui/webui/resources/cr_components/history_clusters/BUILD.gn b/ui/webui/resources/cr_components/history_clusters/BUILD.gn index dc2e1e4..5d11b25 100644 --- a/ui/webui/resources/cr_components/history_clusters/BUILD.gn +++ b/ui/webui/resources/cr_components/history_clusters/BUILD.gn
@@ -8,6 +8,7 @@ import("//tools/polymer/html_to_wrapper.gni") import("//tools/typescript/ts_library.gni") import("//ui/webui/resources/tools/generate_grd.gni") +import("//ui/webui/webui_features.gni") import("history_clusters.gni") assert(!is_android) @@ -29,12 +30,26 @@ webui_module_path = "chrome://resources/cr_components/history_clusters/" } +preprocess_if_expr("preprocess") { + in_folder = "." + out_folder = preprocess_folder_tmp + in_files = ts_files + html_files + css_files +} + css_to_wrapper("css_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp in_files = css_files + minify = optimize_webui } html_to_wrapper("html_wrapper_files") { + deps = [ ":preprocess" ] + in_folder = preprocess_folder_tmp + out_folder = preprocess_folder_tmp in_files = html_files + minify = optimize_webui } copy("copy_history_clusters_mojom") { @@ -43,22 +58,6 @@ deps = [ ":mojo_bindings_webui_js" ] } -preprocess_if_expr("preprocess") { - in_folder = "." - out_folder = preprocess_folder_tmp - in_files = ts_files -} - -preprocess_if_expr("preprocess_generated") { - deps = [ - ":css_wrapper_files", - ":html_wrapper_files", - ] - in_folder = target_gen_dir - out_folder = preprocess_folder_tmp - in_files = html_wrapper_files + css_wrapper_files -} - ts_library("build_ts") { root_dir = preprocess_folder_tmp out_dir = preprocess_folder @@ -74,8 +73,9 @@ definitions = [ "//tools/typescript/definitions/metrics_private.d.ts" ] extra_deps = [ ":copy_history_clusters_mojom", + ":css_wrapper_files", + ":html_wrapper_files", ":preprocess", - ":preprocess_generated", ] }
diff --git a/ui/webui/resources/cr_components/most_visited/BUILD.gn b/ui/webui/resources/cr_components/most_visited/BUILD.gn index cf37adc..3015af1a 100644 --- a/ui/webui/resources/cr_components/most_visited/BUILD.gn +++ b/ui/webui/resources/cr_components/most_visited/BUILD.gn
@@ -6,6 +6,7 @@ import("//tools/polymer/html_to_wrapper.gni") import("//tools/typescript/ts_library.gni") import("//ui/webui/resources/tools/generate_grd.gni") +import("//ui/webui/webui_features.gni") import("most_visited.gni") assert(!is_android && !is_ios) @@ -25,6 +26,7 @@ html_to_wrapper("html_wrapper_files") { in_files = html_files + minify = optimize_webui } copy("copy_mojom") {
diff --git a/ui/webui/resources/cr_elements/BUILD.gn b/ui/webui/resources/cr_elements/BUILD.gn index 53937a4e..6996d90 100644 --- a/ui/webui/resources/cr_elements/BUILD.gn +++ b/ui/webui/resources/cr_elements/BUILD.gn
@@ -394,7 +394,7 @@ "//ui/webui/resources/js:assert.m", "//ui/webui/resources/js:cr.m", "//ui/webui/resources/js:util.m", - "//ui/webui/resources/js/cr/ui:keyboard_shortcut_list.m", + "//ui/webui/resources/js/cr/ui:keyboard_shortcut_list", ] } }
diff --git a/ui/webui/resources/cr_elements/find_shortcut_behavior.js b/ui/webui/resources/cr_elements/find_shortcut_behavior.js index 393a7e9..fee963c 100644 --- a/ui/webui/resources/cr_elements/find_shortcut_behavior.js +++ b/ui/webui/resources/cr_elements/find_shortcut_behavior.js
@@ -4,7 +4,7 @@ import {assert, assertNotReached} from '../js/assert.m.js'; import {isMac} from '../js/cr.m.js'; -import {KeyboardShortcutList} from '../js/cr/ui/keyboard_shortcut_list.m.js'; +import {KeyboardShortcutList} from '../js/cr/ui/keyboard_shortcut_list.js'; import {isTextInputElement} from '../js/util.m.js'; /**
diff --git a/ui/webui/resources/cr_elements/find_shortcut_mixin.ts b/ui/webui/resources/cr_elements/find_shortcut_mixin.ts index 1a48887..d6e435b 100644 --- a/ui/webui/resources/cr_elements/find_shortcut_mixin.ts +++ b/ui/webui/resources/cr_elements/find_shortcut_mixin.ts
@@ -6,7 +6,7 @@ import {assert, assertNotReached} from '../js/assert.m.js'; import {isMac} from '../js/cr.m.js'; -import {KeyboardShortcutList} from '../js/cr/ui/keyboard_shortcut_list.m.js'; +import {KeyboardShortcutList} from '../js/cr/ui/keyboard_shortcut_list.js'; import {isTextInputElement} from '../js/util.m.js'; /**
diff --git a/ui/webui/resources/html/BUILD.gn b/ui/webui/resources/html/BUILD.gn index 8f77ffb..3cba5c2 100644 --- a/ui/webui/resources/html/BUILD.gn +++ b/ui/webui/resources/html/BUILD.gn
@@ -25,20 +25,13 @@ "cr/event_target.html", "cr/ui.html", "cr/ui/array_data_model.html", - "cr/ui/command.html", - "cr/ui/context_menu_handler.html", "cr/ui/focus_manager.html", "cr/ui/focus_outline_manager.html", "cr/ui/focus_row.html", - "cr/ui/keyboard_shortcut_list.html", "cr/ui/list.html", "cr/ui/list_item.html", "cr/ui/list_selection_controller.html", "cr/ui/list_selection_model.html", - "cr/ui/menu_button.html", - "cr/ui/menu.html", - "cr/ui/menu_item.html", - "cr/ui/position_util.html", "event_tracker.html", "promise_resolver.html", "util.html",
diff --git a/ui/webui/resources/html/cr/ui/command.html b/ui/webui/resources/html/cr/ui/command.html deleted file mode 100644 index 04b6e53c..0000000 --- a/ui/webui/resources/html/cr/ui/command.html +++ /dev/null
@@ -1,4 +0,0 @@ -<link rel="import" href="../../../html/cr/ui.html"> -<link rel="import" href="../../../html/cr/ui/keyboard_shortcut_list.html"> - -<script src="../../../js/cr/ui/command.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/context_menu_handler.html b/ui/webui/resources/html/cr/ui/context_menu_handler.html deleted file mode 100644 index d4e2641..0000000 --- a/ui/webui/resources/html/cr/ui/context_menu_handler.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="../../../js/cr/ui/context_menu_handler.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/keyboard_shortcut_list.html b/ui/webui/resources/html/cr/ui/keyboard_shortcut_list.html deleted file mode 100644 index 7b330f8..0000000 --- a/ui/webui/resources/html/cr/ui/keyboard_shortcut_list.html +++ /dev/null
@@ -1,3 +0,0 @@ -<link rel="import" href="../../../html/cr.html"> - -<script src="../../../js/cr/ui/keyboard_shortcut_list.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/menu.html b/ui/webui/resources/html/cr/ui/menu.html deleted file mode 100644 index 16ec5e3..0000000 --- a/ui/webui/resources/html/cr/ui/menu.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="../../../js/cr/ui/menu.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/menu_button.html b/ui/webui/resources/html/cr/ui/menu_button.html deleted file mode 100644 index c203da5..0000000 --- a/ui/webui/resources/html/cr/ui/menu_button.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="../../../js/cr/ui/menu_button.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/menu_item.html b/ui/webui/resources/html/cr/ui/menu_item.html deleted file mode 100644 index d28138f..0000000 --- a/ui/webui/resources/html/cr/ui/menu_item.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="../../../js/cr/ui/menu_item.js"></script>
diff --git a/ui/webui/resources/html/cr/ui/position_util.html b/ui/webui/resources/html/cr/ui/position_util.html deleted file mode 100644 index ef06075..0000000 --- a/ui/webui/resources/html/cr/ui/position_util.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="../../../js/cr/ui/position_util.js"></script>
diff --git a/ui/webui/resources/js/cr/ui/BUILD.gn b/ui/webui/resources/js/cr/ui/BUILD.gn index 21226194..5681035 100644 --- a/ui/webui/resources/js/cr/ui/BUILD.gn +++ b/ui/webui/resources/js/cr/ui/BUILD.gn
@@ -47,29 +47,38 @@ in_folder = "./" out_folder = "$preprocess_folder" out_manifest = "$target_gen_dir/$preprocess_src_manifest" - in_files = [ "store.js" ] + in_files = [ + "keyboard_shortcut_list.js", + "store.js", + ] + + if (!is_android) { + # The files below are deprecated, and are included on non-CrOS builds only + # for the old NTP (chrome://apps) page. + in_files += [ + "command.js", + "context_menu_handler.js", + "menu_button.js", + "menu_item.js", + "menu.js", + "position_util.js", + ] + } if (is_chromeos_ash) { in_files += [ "array_data_model.js", - "command.js", - "context_menu_handler.js", "focus_manager.js", "focus_outline_manager.js", "focus_row.js", "focus_row_behavior.js", "focus_without_ink.js", "grid.js", - "keyboard_shortcut_list.js", "list_item.js", "list.js", "list_selection_controller.js", "list_selection_model.js", "list_single_selection_model.js", - "menu_button.js", - "menu_item.js", - "menu.js", - "position_util.js", "store_client.js", ] } @@ -83,19 +92,12 @@ in_files = [ "focus_outline_manager.m.js", "focus_row.m.js", - "keyboard_shortcut_list.m.js", ] if (!is_android) { in_files += [ - "command.m.js", - "context_menu_handler.m.js", "focus_row_behavior.m.js", "focus_without_ink.m.js", - "menu_button.m.js", - "menu_item.m.js", - "menu.m.js", - "position_util.m.js", ] } @@ -124,24 +126,17 @@ uses_legacy_modules = true deps = [ ":array_data_model", - ":command", - ":context_menu_handler", ":focus_manager", ":focus_outline_manager", ":focus_row", ":focus_row_behavior", ":focus_without_ink", ":grid", - ":keyboard_shortcut_list", ":list", ":list_item", ":list_selection_controller", ":list_selection_model", ":list_single_selection_model", - ":menu", - ":menu_button", - ":menu_item", - ":position_util", ] } @@ -152,25 +147,6 @@ ] } - js_library("command") { - deps = [ - ":keyboard_shortcut_list", - "..:ui", - "../..:cr", - ] - } - - js_library("context_menu_handler") { - deps = [ - ":menu", - ":menu_button", - ":position_util", - "..:event_target", - "..:ui", - "../..:cr", - ] - } - js_library("focus_manager") { deps = [ "../..:cr" ] } @@ -210,10 +186,6 @@ } } - js_library("keyboard_shortcut_list") { - deps = [ "../..:cr" ] - } - if (is_chromeos_ash) { js_library("list") { deps = [ @@ -249,62 +221,21 @@ ] } } - - js_library("menu_button") { - deps = [ - ":menu", - ":menu_item", - ":position_util", - "..:ui", - "../..:assert", - "../..:cr", - "../..:event_tracker", - ] - } - - js_library("menu_item") { - deps = [ - ":command", - "..:ui", - "../..:cr", - "../..:load_time_data", - ] - } - - js_library("menu") { - deps = [ - ":menu_item", - "..:ui", - "../..:assert", - "../..:cr", - ] - } - - js_library("position_util") { - deps = [ "../..:cr" ] - } } js_modulizer("modulize") { input_files = [ "array_data_model.js", - "command.js", - "context_menu_handler.js", "focus_outline_manager.js", "focus_row.js", "focus_row_behavior.js", "focus_without_ink.js", "grid.js", - "keyboard_shortcut_list.js", "list.js", "list_item.js", "list_selection_controller.js", "list_selection_model.js", "list_single_selection_model.js", - "menu.js", - "menu_button.js", - "menu_item.js", - "position_util.js", ] namespace_rewrites = cr_namespace_rewrites } @@ -321,19 +252,19 @@ if (is_chromeos_ash) { deps += [ ":array_data_model.m", - ":command.m", - ":context_menu_handler.m", + ":command", + ":context_menu_handler", ":grid.m", - ":keyboard_shortcut_list.m", + ":keyboard_shortcut_list", ":list.m", ":list_item.m", ":list_selection_controller.m", ":list_selection_model.m", ":list_single_selection_model.m", - ":menu.m", - ":menu_button.m", - ":menu_item.m", - ":position_util.m", + ":menu", + ":menu_button", + ":menu_item", + ":position_util", ":store_client", ] } @@ -351,35 +282,27 @@ extra_deps = [ ":modulize" ] } - js_library("command.m") { - sources = [ "$root_gen_dir/ui/webui/resources/js/cr/ui/command.m.js" ] + js_library("command") { deps = [ - ":keyboard_shortcut_list.m", + ":keyboard_shortcut_list", "../:ui.m", "../..:assert.m", "../..:cr.m", ] - - extra_deps = [ ":modulize" ] } - js_library("context_menu_handler.m") { - sources = [ - "$root_gen_dir/ui/webui/resources/js/cr/ui/context_menu_handler.m.js", - ] + js_library("context_menu_handler") { deps = [ - ":menu.m", - ":menu_button.m", - ":menu_item.m", - ":position_util.m", + ":menu", + ":menu_button", + ":menu_item", + ":position_util", "..:event_target.m", "../:ui.m", "../..:assert.m", "../..:cr.m", "../..:event_tracker.m", ] - - extra_deps = [ ":modulize" ] } } @@ -434,11 +357,7 @@ extra_deps = [ ":modulize" ] } - js_library("keyboard_shortcut_list.m") { - sources = [ - "$root_gen_dir/ui/webui/resources/js/cr/ui/keyboard_shortcut_list.m.js", - ] - extra_deps = [ ":modulize" ] + js_library("keyboard_shortcut_list") { } js_library("list.m") { @@ -489,46 +408,38 @@ extra_deps = [ ":modulize" ] } - js_library("menu.m") { - sources = [ "$root_gen_dir/ui/webui/resources/js/cr/ui/menu.m.js" ] + js_library("menu") { deps = [ - ":menu_item.m", + ":menu_item", "../:ui.m", "../..:assert.m", "../..:cr.m", ] - extra_deps = [ ":modulize" ] } - js_library("menu_button.m") { - sources = [ "$root_gen_dir/ui/webui/resources/js/cr/ui/menu_button.m.js" ] + js_library("menu_button") { deps = [ - ":menu.m", - ":menu_item.m", - ":position_util.m", + ":menu", + ":menu_item", + ":position_util", "../:ui.m", "../..:assert.m", "../..:cr.m", "../..:event_tracker.m", ] - extra_deps = [ ":modulize" ] } - js_library("menu_item.m") { - sources = [ "$root_gen_dir/ui/webui/resources/js/cr/ui/menu_item.m.js" ] + js_library("menu_item") { deps = [ - ":command.m", + ":command", "../:ui.m", "../..:assert.m", "../..:cr.m", "../..:load_time_data.m", ] - extra_deps = [ ":modulize" ] } - js_library("position_util.m") { - sources = [ "$root_gen_dir/ui/webui/resources/js/cr/ui/position_util.m.js" ] - extra_deps = [ ":modulize" ] + js_library("position_util") { } }
diff --git a/ui/webui/resources/js/cr/ui/command.js b/ui/webui/resources/js/cr/ui/command.js index 4421578..9f68bb8 100644 --- a/ui/webui/resources/js/cr/ui/command.js +++ b/ui/webui/resources/js/cr/ui/command.js
@@ -21,20 +21,19 @@ */ // clang-format off -// #import {assert} from '../../assert.m.js'; -// #import {define as crUiDefine} from '../ui.m.js'; -// #import {KeyboardShortcutList} from './keyboard_shortcut_list.m.js'; -// #import {dispatchPropertyChange, getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; -// #import {MenuItem} from './menu_item.m.js'; +import {assert} from '../../assert.m.js'; +import {define as crUiDefine} from '../ui.m.js'; +import {KeyboardShortcutList} from './keyboard_shortcut_list.js'; +import {dispatchPropertyChange, getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; +import {MenuItem} from './menu_item.js'; // clang-format on -cr.define('cr.ui', function() { /** * Creates a new command element. * @constructor * @extends {HTMLElement} */ - /* #export */ const Command = cr.ui.define('command'); + export const Command = crUiDefine('command'); Command.prototype = { __proto__: HTMLElement.prototype, @@ -102,11 +101,11 @@ set shortcut(shortcut) { const oldShortcut = this.shortcut_; if (shortcut !== oldShortcut) { - this.keyboardShortcuts_ = new cr.ui.KeyboardShortcutList(shortcut); + this.keyboardShortcuts_ = new KeyboardShortcutList(shortcut); // Set this after the keyboardShortcuts_ since that might throw. this.shortcut_ = shortcut; - cr.dispatchPropertyChange( + dispatchPropertyChange( this, 'shortcut', this.shortcut_, oldShortcut); } }, @@ -131,7 +130,7 @@ Command.prototype.label; Object.defineProperty( Command.prototype, 'label', - cr.getPropertyDescriptor('label', cr.PropertyKind.ATTR)); + getPropertyDescriptor('label', PropertyKind.ATTR)); /** * Whether the command is disabled or not. @@ -140,14 +139,14 @@ Command.prototype.disabled; Object.defineProperty( Command.prototype, 'disabled', - cr.getPropertyDescriptor('disabled', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('disabled', PropertyKind.BOOL_ATTR)); /** * Whether the command is hidden or not. */ Object.defineProperty( Command.prototype, 'hidden', - cr.getPropertyDescriptor('hidden', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('hidden', PropertyKind.BOOL_ATTR)); /** * Whether the command is checked or not. @@ -156,7 +155,7 @@ Command.prototype.checked; Object.defineProperty( Command.prototype, 'checked', - cr.getPropertyDescriptor('checked', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('checked', PropertyKind.BOOL_ATTR)); /** * The flag that prevents the shortcut text from being displayed on menu. @@ -169,11 +168,11 @@ Command.prototype.hideShortcutText; Object.defineProperty( Command.prototype, 'hideShortcutText', - cr.getPropertyDescriptor('hideShortcutText', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('hideShortcutText', PropertyKind.BOOL_ATTR)); /** * Dispatches a canExecute event on the target. - * @param {!cr.ui.Command} command The command that we are testing for. + * @param {!Command} command The command that we are testing for. * @param {EventTarget} target The target element to dispatch the event on. */ function dispatchCanExecuteEvent(command, target) { @@ -224,7 +223,7 @@ const target = e.target; // Ignore focus on a menu button or command item. - if (target.menu || target.command || (target instanceof cr.ui.MenuItem)) { + if (target.menu || target.command || (target instanceof MenuItem)) { return; } @@ -266,12 +265,12 @@ /** * The event type used for canExecute events. - * @param {!cr.ui.Command} command The command that we are evaluating. + * @param {!Command} command The command that we are evaluating. * @extends {Event} * @constructor * @class */ - /* #export */ function CanExecuteEvent(command) { + export function CanExecuteEvent(command) { const e = new Event('canExecute', {bubbles: true, cancelable: true}); e.__proto__ = CanExecuteEvent.prototype; e.command = command; @@ -283,7 +282,7 @@ /** * The current command - * @type {cr.ui.Command} + * @type {Command} */ command: null, @@ -303,12 +302,3 @@ this.preventDefault(); }, }; - - // Export - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return { - Command: Command, - CanExecuteEvent: CanExecuteEvent, - }; -});
diff --git a/ui/webui/resources/js/cr/ui/context_menu_handler.m.d.ts b/ui/webui/resources/js/cr/ui/context_menu_handler.d.ts similarity index 87% rename from ui/webui/resources/js/cr/ui/context_menu_handler.m.d.ts rename to ui/webui/resources/js/cr/ui/context_menu_handler.d.ts index 0227a74b..03ca296b 100644 --- a/ui/webui/resources/js/cr/ui/context_menu_handler.m.d.ts +++ b/ui/webui/resources/js/cr/ui/context_menu_handler.d.ts
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {Menu} from './menu.m.js'; -import {HideType} from './menu_button.m.js'; +import {Menu} from './menu.js'; +import {HideType} from './menu_button.js'; export const contextMenuHandler: ContextMenuHandler;
diff --git a/ui/webui/resources/js/cr/ui/context_menu_handler.js b/ui/webui/resources/js/cr/ui/context_menu_handler.js index 52c5662..a699a8d 100644 --- a/ui/webui/resources/js/cr/ui/context_menu_handler.js +++ b/ui/webui/resources/js/cr/ui/context_menu_handler.js
@@ -7,36 +7,32 @@ // should only be used by legacy UIs that have not yet been updated to new // patterns. Use Web Components in any new code. -// require: event_target.js - // clang-format off -// #import {assertInstanceof} from '../../assert.m.js'; -// #import {NativeEventTarget as EventTarget} from '../event_target.m.js' -// #import {EventTracker} from '../../event_tracker.m.js' -// #import {isWindows, isLinux, isMac, isLacros, dispatchPropertyChange} from '../../cr.m.js'; -// #import {decorate} from '../ui.m.js'; -// #import {Menu} from './menu.m.js'; -// #import {MenuItem} from './menu_item.m.js'; -// #import {HideType} from './menu_button.m.js'; -// #import {positionPopupAtPoint} from './position_util.m.js'; +import {assertInstanceof} from '../../assert.m.js'; +import {NativeEventTarget as EventTarget} from '../event_target.m.js'; +import {EventTracker} from '../../event_tracker.m.js'; +import {isWindows, isLinux, isMac, isLacros, dispatchPropertyChange} from '../../cr.m.js'; +import {decorate} from '../ui.m.js'; +import {Menu} from './menu.js'; +import {MenuItem} from './menu_item.js'; +import {HideType} from './menu_button.js'; +import {positionPopupAtPoint} from './position_util.js'; // clang-format on -cr.define('cr.ui', function() { - /* #ignore */ /** @const */ const Menu = cr.ui.Menu; /** * Handles context menus. * @implements {EventListener} */ - class ContextMenuHandler extends cr.EventTarget { + class ContextMenuHandler extends EventTarget { constructor() { super(); - /** @private {!cr.EventTracker} */ - this.showingEvents_ = new cr.EventTracker(); + /** @private {!EventTracker} */ + this.showingEvents_ = new EventTracker(); /** * The menu that we are currently showing. - * @private {?cr.ui.Menu} + * @private {?Menu} */ this.menu_ = null; @@ -55,7 +51,7 @@ * Shows a menu as a context menu. * @param {!Event} e The event triggering the show (usually a contextmenu * event). - * @param {!cr.ui.Menu} menu The menu to show. + * @param {!Menu} menu The menu to show. */ showMenu(e, menu) { menu.updateCommands(assertInstanceof(e.currentTarget, Node)); @@ -90,8 +86,8 @@ /** * Hide the currently shown menu. - * @param {cr.ui.HideType=} opt_hideType Type of hide. - * default: cr.ui.HideType.INSTANT. + * @param {HideType=} opt_hideType Type of hide. + * default: HideType.INSTANT. */ hideMenu(opt_hideType) { const menu = this.menu; @@ -99,7 +95,7 @@ return; } - if (opt_hideType === cr.ui.HideType.DELAYED) { + if (opt_hideType === HideType.DELAYED) { menu.classList.add('hide-delayed'); } else { menu.classList.remove('hide-delayed'); @@ -114,7 +110,7 @@ // On windows we might hide the menu in a right mouse button up and if // that is the case we wait some short period before we allow the menu // to be shown again. - this.hideTimestamp_ = cr.isWindows ? Date.now() : 0; + this.hideTimestamp_ = isWindows ? Date.now() : 0; const ev = new Event('hide'); ev.element = originalContextElement; @@ -125,7 +121,7 @@ /** * Positions the menu * @param {!Event} e The event object triggering the showing. - * @param {!cr.ui.Menu} menu The menu to position. + * @param {!Menu} menu The menu to position. * @private */ positionMenu_(e, menu) { @@ -148,7 +144,7 @@ y = e.clientY; } - cr.ui.positionPopupAtPoint(x, y, menu); + positionPopupAtPoint(x, y, menu); } /** @@ -181,7 +177,7 @@ if (!this.menu.contains(e.target)) { this.hideMenu(); if (e.button === 0 /* Left button */ && - (cr.isLinux || cr.isMac || cr.isLacros)) { + (isLinux || isMac || isLacros)) { // Emulate Mac and Linux, which swallow native 'mousedown' events // that close menus. e.preventDefault(); @@ -214,9 +210,9 @@ case 'activate': const hideDelayed = - e.target instanceof cr.ui.MenuItem && e.target.checkable; + e.target instanceof MenuItem && e.target.checkable; this.hideMenu( - hideDelayed ? cr.ui.HideType.DELAYED : cr.ui.HideType.INSTANT); + hideDelayed ? HideType.DELAYED : HideType.INSTANT); break; case 'focus': @@ -266,7 +262,7 @@ if (typeof menu === 'string' && menu[0] === '#') { menu = this.ownerDocument.getElementById(menu.slice(1)); - cr.ui.decorate(menu, Menu); + decorate(menu, Menu); } if (menu === oldContextMenu) { @@ -290,7 +286,7 @@ this.setAttribute('contextmenu', '#' + menu.id); } - cr.dispatchPropertyChange(this, 'contextMenu', menu, oldContextMenu); + dispatchPropertyChange(this, 'contextMenu', menu, oldContextMenu); }); if (!target.getRectForContextMenu) { @@ -308,7 +304,7 @@ * Sets the given contextMenu to the given element. A contextMenu property * would be added if necessary. * @param {!Element} element The element or class to set the contextMenu to. - * @param {!cr.ui.Menu} contextMenu The contextMenu property to be set. + * @param {!Menu} contextMenu The contextMenu property to be set. */ setContextMenu(element, contextMenu) { if (!element.contextMenu) { @@ -322,12 +318,4 @@ * The singleton context menu handler. * @type {!ContextMenuHandler} */ - /* #export */ const contextMenuHandler = new ContextMenuHandler(); - - // Export - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return { - contextMenuHandler: contextMenuHandler, - }; -}); + export const contextMenuHandler = new ContextMenuHandler();
diff --git a/ui/webui/resources/js/cr/ui/keyboard_shortcut_list.js b/ui/webui/resources/js/cr/ui/keyboard_shortcut_list.js index 0322d99..951e7fa 100644 --- a/ui/webui/resources/js/cr/ui/keyboard_shortcut_list.js +++ b/ui/webui/resources/js/cr/ui/keyboard_shortcut_list.js
@@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -cr.define('cr.ui', function() { /** This is used to identify keyboard shortcuts. */ class KeyboardShortcut { /** @@ -66,7 +65,7 @@ } /** A list of keyboard shortcuts which all perform one command. */ - /* #export */ class KeyboardShortcutList { + export class KeyboardShortcutList { /** * @param {string} shortcuts Text-based representation of one or more * keyboard shortcuts, separated by spaces. @@ -90,9 +89,3 @@ } } - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return { - KeyboardShortcutList: KeyboardShortcutList, - }; -});
diff --git a/ui/webui/resources/js/cr/ui/menu.js b/ui/webui/resources/js/cr/ui/menu.js index 55444eb..14738e5 100644 --- a/ui/webui/resources/js/cr/ui/menu.js +++ b/ui/webui/resources/js/cr/ui/menu.js
@@ -7,13 +7,11 @@ // should only be used by legacy UIs that have not yet been updated to new // patterns. Use Web Components in any new code. -// #import {assert, assertInstanceof} from '../../assert.m.js'; -// #import {define as crUiDefine, decorate} from '../ui.m.js'; -// #import {getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; -// #import {MenuItem} from './menu_item.m.js'; +import {assert, assertInstanceof} from '../../assert.m.js'; +import {define as crUiDefine, decorate} from '../ui.m.js'; +import {getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; +import {MenuItem} from './menu_item.js'; -cr.define('cr.ui', function() { - /* #ignore */ /** @const */ const MenuItem = cr.ui.MenuItem; /** * Creates a new menu element. Menu dispatches all commands on the element it @@ -23,7 +21,7 @@ * @constructor * @extends {HTMLElement} */ - /* #export */ const Menu = cr.ui.define('cr-menu'); + export const Menu = crUiDefine('cr-menu'); Menu.prototype = { __proto__: HTMLElement.prototype, @@ -50,20 +48,21 @@ // Decorate the children as menu items. const menuItems = this.menuItems; for (let i = 0, menuItem; menuItem = menuItems[i]; i++) { - cr.ui.decorate(menuItem, MenuItem); + decorate(menuItem, MenuItem); } }, /** * Adds menu item at the end of the list. * @param {Object} item Menu item properties. - * @return {!cr.ui.MenuItem} The created menu item. + * @return {!MenuItem} The created menu item. */ addMenuItem(item) { - const menuItem = this.ownerDocument.createElement('cr-menu-item'); + const menuItem = /** @type {!MenuItem} */ ( + this.ownerDocument.createElement('cr-menu-item')); this.appendChild(menuItem); - cr.ui.decorate(menuItem, MenuItem); + decorate(menuItem, MenuItem); if (item.label) { menuItem.label = item.label; @@ -81,7 +80,7 @@ */ addSeparator() { const separator = this.ownerDocument.createElement('hr'); - cr.ui.decorate(separator, MenuItem); + decorate(separator, MenuItem); this.appendChild(separator); }, @@ -97,7 +96,7 @@ * Walks up the ancestors of |node| until a menu item belonging to this menu * is found. * @param {Node} node The node to start searching from. - * @return {cr.ui.MenuItem} The found menu item or null. + * @return {MenuItem} The found menu item or null. * @private */ findMenuItem_(node) { @@ -166,7 +165,7 @@ /** * The selected menu item or null if none. - * @type {cr.ui.MenuItem} + * @type {MenuItem} */ get selectedItem() { return this.menuItems[this.selectedIndex]; @@ -215,7 +214,7 @@ /** * Returns whether the given menu item is visible. - * @param {!cr.ui.MenuItem} menuItem + * @param {!MenuItem} menuItem * @return {boolean} * @private */ @@ -391,8 +390,8 @@ Menu.prototype.selectedIndex; Object.defineProperty( Menu.prototype, 'selectedIndex', - cr.getPropertyDescriptor( - 'selectedIndex', cr.PropertyKind.JS, selectedIndexChanged)); + getPropertyDescriptor( + 'selectedIndex', PropertyKind.JS, selectedIndexChanged)); /** * Selector for children which are menu items. @@ -401,10 +400,4 @@ Menu.prototype.menuItemSelector; Object.defineProperty( Menu.prototype, 'menuItemSelector', - cr.getPropertyDescriptor('menuItemSelector', cr.PropertyKind.ATTR)); - - // Export - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return {Menu: Menu}; -}); + getPropertyDescriptor('menuItemSelector', PropertyKind.ATTR));
diff --git a/ui/webui/resources/js/cr/ui/menu_button.m.d.ts b/ui/webui/resources/js/cr/ui/menu_button.d.ts similarity index 100% rename from ui/webui/resources/js/cr/ui/menu_button.m.d.ts rename to ui/webui/resources/js/cr/ui/menu_button.d.ts
diff --git a/ui/webui/resources/js/cr/ui/menu_button.js b/ui/webui/resources/js/cr/ui/menu_button.js index 8b3003e5..250c470 100644 --- a/ui/webui/resources/js/cr/ui/menu_button.js +++ b/ui/webui/resources/js/cr/ui/menu_button.js
@@ -7,30 +7,26 @@ // should only be used by legacy UIs that have not yet been updated to new // patterns. Use Web Components in any new code. -// #import {assert} from '../../assert.m.js'; -// #import {isWindows} from '../../cr.m.js'; -// #import {EventTracker} from '../../event_tracker.m.js' -// #import {define as crUiDefine, decorate} from '../ui.m.js'; -// #import {positionPopupAroundElement, AnchorType} from './position_util.m.js'; -// #import {Menu} from './menu.m.js'; -// #import {MenuItem} from './menu_item.m.js'; +import {assert} from '../../assert.m.js'; +import {isWindows} from '../../cr.m.js'; +import {EventTracker} from '../../event_tracker.m.js'; +import {define as crUiDefine, decorate} from '../ui.m.js'; +import {positionPopupAroundElement, AnchorType} from './position_util.js'; +import {Menu} from './menu.js'; +import {MenuItem} from './menu_item.js'; -cr.define('cr.ui', function() { - /* #ignore */ const Menu = cr.ui.Menu; /** * Enum for type of hide. Delayed is used when called by clicking on a * checkable menu item. * @enum {number} */ - /* #export */ const HideType = { + export const HideType = { INSTANT: 0, DELAYED: 1, }; /** @const */ - /* #ignore */ const positionPopupAroundElement = - /* #ignore */ cr.ui.positionPopupAroundElement; /** * Creates a new menu button element. @@ -39,7 +35,7 @@ * @extends {HTMLButtonElement} * @implements {EventListener} */ - /* #export */ const MenuButton = cr.ui.define('button'); + export const MenuButton = crUiDefine('button'); MenuButton.prototype = { __proto__: HTMLButtonElement.prototype, @@ -68,15 +64,15 @@ // An event tracker for events we only connect to while the menu is // displayed. - this.showingEvents_ = new cr.EventTracker(); + this.showingEvents_ = new EventTracker(); - this.anchorType = cr.ui.AnchorType.BELOW; + this.anchorType = AnchorType.BELOW; this.invertLeftRight = false; }, /** * The menu associated with the menu button. - * @type {cr.ui.Menu} + * @type {Menu} */ get menu() { return this.menu_; @@ -84,7 +80,7 @@ set menu(menu) { if (typeof menu === 'string' && menu[0] === '#') { menu = assert(this.ownerDocument.getElementById(menu.slice(1))); - cr.ui.decorate(menu, Menu); + decorate(menu, Menu); } this.menu_ = menu; @@ -181,7 +177,7 @@ break; case 'activate': const hideDelayed = - e.target instanceof cr.ui.MenuItem && e.target.checkable; + e.target instanceof MenuItem && e.target.checkable; const hideType = hideDelayed ? HideType.DELAYED : HideType.INSTANT; if (e.originalEvent instanceof MouseEvent || e.originalEvent instanceof TouchEvent) { @@ -260,8 +256,8 @@ /** * Hides the menu. If your menu can go out of scope, make sure to call this * first. - * @param {cr.ui.HideType=} opt_hideType Type of hide. - * default: cr.ui.HideType.INSTANT. + * @param {HideType=} opt_hideType Type of hide. + * default: HideType.INSTANT. */ hideMenu(opt_hideType) { this.hideMenuInternal_(true, opt_hideType); @@ -270,8 +266,8 @@ /** * Hides the menu. If your menu can go out of scope, make sure to call this * first. - * @param {cr.ui.HideType=} opt_hideType Type of hide. - * default: cr.ui.HideType.INSTANT. + * @param {HideType=} opt_hideType Type of hide. + * default: HideType.INSTANT. */ hideMenuWithoutTakingFocus_(opt_hideType) { this.hideMenuInternal_(false, opt_hideType); @@ -281,8 +277,8 @@ * Hides the menu. If your menu can go out of scope, make sure to call this * first. * @param {boolean} shouldTakeFocus Moves the focus to the button if true. - * @param {cr.ui.HideType=} opt_hideType Type of hide. - * default: cr.ui.HideType.INSTANT. + * @param {HideType=} opt_hideType Type of hide. + * default: HideType.INSTANT. */ hideMenuInternal_(shouldTakeFocus, opt_hideType) { if (!this.isMenuShown()) { @@ -309,7 +305,7 @@ // On windows we might hide the menu in a right mouse button up and if // that is the case we wait some short period before we allow the menu // to be shown again. - this.hideTimestamp_ = cr.isWindows ? Date.now() : 0; + this.hideTimestamp_ = isWindows ? Date.now() : 0; }, /** @@ -353,12 +349,3 @@ } }, }; - - // Export - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return { - HideType: HideType, - MenuButton: MenuButton, - }; -});
diff --git a/ui/webui/resources/js/cr/ui/menu_item.m.d.ts b/ui/webui/resources/js/cr/ui/menu_item.d.ts similarity index 100% rename from ui/webui/resources/js/cr/ui/menu_item.m.d.ts rename to ui/webui/resources/js/cr/ui/menu_item.d.ts
diff --git a/ui/webui/resources/js/cr/ui/menu_item.js b/ui/webui/resources/js/cr/ui/menu_item.js index b59cfd320..e90c8546 100644 --- a/ui/webui/resources/js/cr/ui/menu_item.js +++ b/ui/webui/resources/js/cr/ui/menu_item.js
@@ -8,15 +8,13 @@ // patterns. Use Web Components in any new code. // clang-format off -// #import {loadTimeData} from '../../load_time_data.m.js'; -// #import {assert} from '../../assert.m.js'; -// #import {Command} from './command.m.js'; -// #import {define as crUiDefine, decorate, swallowDoubleClick} from '../ui.m.js'; -// #import {getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; +import {loadTimeData} from '../../load_time_data.m.js'; +import {assert} from '../../assert.m.js'; +import {Command} from './command.js'; +import {define as crUiDefine, decorate, swallowDoubleClick} from '../ui.m.js'; +import {getPropertyDescriptor, PropertyKind} from '../../cr.m.js'; // clang-format on -cr.define('cr.ui', function() { - /* #ignore */ const Command = cr.ui.Command; /** * Creates a new menu item element. @@ -25,14 +23,14 @@ * @extends {HTMLElement} * @implements {EventListener} */ - /* #export */ const MenuItem = cr.ui.define('cr-menu-item'); + export const MenuItem = crUiDefine('cr-menu-item'); /** * Creates a new menu separator element. - * @return {!cr.ui.MenuItem} The new separator element. + * @return {!MenuItem} The new separator element. */ MenuItem.createSeparator = function() { - const el = /** @type {!cr.ui.MenuItem} */ (document.createElement('hr')); + const el = /** @type {!MenuItem} */ (document.createElement('hr')); if (MenuItem.decorate) { MenuItem.decorate(el); } @@ -74,7 +72,7 @@ * The command associated with this menu item. If this is set to a string * of the form "#element-id" then the element is looked up in the document * of the command. - * @type {cr.ui.Command} + * @type {Command} */ command_: null, get command() { @@ -90,7 +88,7 @@ if (typeof command === 'string' && command[0] === '#') { command = assert(this.ownerDocument.body.querySelector(command)); - cr.ui.decorate(command, Command); + decorate(command, Command); } this.command_ = command; @@ -229,7 +227,7 @@ const command = this.command; if (command) { command.execute(contextElement); - cr.ui.swallowDoubleClick(e); + swallowDoubleClick(e); } } } @@ -273,14 +271,14 @@ MenuItem.prototype.disabled; Object.defineProperty( MenuItem.prototype, 'disabled', - cr.getPropertyDescriptor('disabled', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('disabled', PropertyKind.BOOL_ATTR)); /** * Whether the menu item is hidden or not. */ Object.defineProperty( MenuItem.prototype, 'hidden', - cr.getPropertyDescriptor('hidden', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('hidden', PropertyKind.BOOL_ATTR)); /** * Whether the menu item is selected or not. @@ -289,7 +287,7 @@ MenuItem.prototype.selected; Object.defineProperty( MenuItem.prototype, 'selected', - cr.getPropertyDescriptor('selected', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('selected', PropertyKind.BOOL_ATTR)); /** * Whether the menu item is checked or not. @@ -298,7 +296,7 @@ MenuItem.prototype.checked; Object.defineProperty( MenuItem.prototype, 'checked', - cr.getPropertyDescriptor('checked', cr.PropertyKind.BOOL_ATTR)); + getPropertyDescriptor('checked', PropertyKind.BOOL_ATTR)); /** * Whether the menu item is checkable or not. @@ -307,9 +305,4 @@ MenuItem.prototype.checkable; Object.defineProperty( MenuItem.prototype, 'checkable', - cr.getPropertyDescriptor('checkable', cr.PropertyKind.BOOL_ATTR)); - - // Export - // #cr_define_end - return {MenuItem: MenuItem}; -}); + getPropertyDescriptor('checkable', PropertyKind.BOOL_ATTR));
diff --git a/ui/webui/resources/js/cr/ui/position_util.js b/ui/webui/resources/js/cr/ui/position_util.js index 453944b5..66ca87fc 100644 --- a/ui/webui/resources/js/cr/ui/position_util.js +++ b/ui/webui/resources/js/cr/ui/position_util.js
@@ -6,7 +6,6 @@ * @fileoverview This file provides utility functions for position popups. */ -cr.define('cr.ui', function() { /** * Type def for rects as returned by getBoundingClientRect. * @typedef {{left: number, top: number, width: number, height: number, @@ -18,7 +17,7 @@ * Enum for defining how to anchor a popup to an anchor element. * @enum {number} */ - /* #export */ const AnchorType = { + export const AnchorType = { /** * The popup's right edge is aligned with the left edge of the anchor. * The popup's top edge is aligned with the top edge of the anchor. @@ -48,7 +47,7 @@ * Helper function for positionPopupAroundElement and positionPopupAroundRect. * @param {!Rect} anchorRect The rect for the anchor. * @param {!HTMLElement} popupElement The element used for the popup. - * @param {cr.ui.AnchorType} type The type of anchoring to do. + * @param {AnchorType} type The type of anchoring to do. * @param {boolean=} opt_invertLeftRight Whether to invert the right/left * alignment. */ @@ -211,11 +210,11 @@ * @param {!HTMLElement} anchorElement The element that the popup is anchored * to. * @param {!HTMLElement} popupElement The popup element we are positioning. - * @param {cr.ui.AnchorType} type The type of anchoring we want. + * @param {AnchorType} type The type of anchoring we want. * @param {boolean=} opt_invertLeftRight Whether to invert the right/left * alignment. */ - /* #export */ function positionPopupAroundElement( + export function positionPopupAroundElement( anchorElement, popupElement, type, opt_invertLeftRight) { const anchorRect = anchorElement.getBoundingClientRect(); positionPopupAroundRect( @@ -227,22 +226,12 @@ * @param {number} x The client x position. * @param {number} y The client y position. * @param {!HTMLElement} popupElement The popup element we are positioning. - * @param {cr.ui.AnchorType=} opt_anchorType The type of anchoring we want. + * @param {AnchorType=} opt_anchorType The type of anchoring we want. */ - /* #export */ function positionPopupAtPoint( + export function positionPopupAtPoint( x, y, popupElement, opt_anchorType) { const rect = {left: x, top: y, width: 0, height: 0, right: x, bottom: y}; const anchorType = opt_anchorType || AnchorType.BELOW; positionPopupAroundRect(rect, popupElement, anchorType); } - - // Export - // #cr_define_end - console.warn('crbug/1173575, non-JS module files deprecated.'); - return { - AnchorType: AnchorType, - positionPopupAroundElement: positionPopupAroundElement, - positionPopupAtPoint: positionPopupAtPoint, - }; -});
diff --git a/ui/wm/core/capture_controller.cc b/ui/wm/core/capture_controller.cc index 3fab8e17..560912a 100644 --- a/ui/wm/core/capture_controller.cc +++ b/ui/wm/core/capture_controller.cc
@@ -5,7 +5,6 @@ #include "ui/wm/core/capture_controller.h" #include "base/observer_list.h" -#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/client/capture_client_observer.h" #include "ui/aura/env.h" #include "ui/aura/window.h"