diff --git a/AUTHORS b/AUTHORS index a99ab18..cbf51039 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -473,6 +473,7 @@ Heeyoun Lee <heeyoun.lee@samsung.com> Henrique de Carvalho <decarv.henrique@gmail.com> Henrique Limas <henrique.ramos.limas@gmail.com> +Henry Lim <henry@limhenry.xyz> Hikari Fujimoto <hikari.p.fujimoto@gmail.com> Himanshu Joshi <h.joshi@samsung.com> Himanshu Nayak <himanshu.nayak@amd.corp-partner.google.com>
diff --git a/DEPS b/DEPS index 2961665..2617b100 100644 --- a/DEPS +++ b/DEPS
@@ -314,15 +314,15 @@ # 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': 'f4e98fb9738ebfdbfb4cac532874264a23f49127', + 'skia_revision': '475f07f5ca1493c431dcb393cbb4cdb452cc1b31', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '97f0f0b35eb6990e07572e81ae82451ac615f87c', + 'v8_revision': 'f68349e4ca20071b5d3f6c8b131067a036c1ce47', # 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': '3479f4a1807b5ec34c705e5a4d59aa475577c24e', + 'angle_revision': 'ee0df29eaea3c5758cc7671b805d939e8b6312c0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -445,7 +445,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': '8edcef493739e8aa15ce2bf6bde479d8adc727fe', + 'dawn_revision': '3bf448244be3cc0329e55111668643cd52183494', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -485,7 +485,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. - 'cros_components_revision': 'd604de81aaf62bcb6e34047b040b3ae984d0069d', + 'cros_components_revision': '9fbbe7b609dcd6d702e8fb0884fdc3f7391343e7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -837,7 +837,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - '20839833f78aae4f6cbdcd8c5834b4b6f0763f45', + 'a36d8452a8634c96605397c104a0ff2b12364e3c', 'condition': 'checkout_android and checkout_src_internal', }, @@ -1032,7 +1032,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'QhmFBViaQStJmS7n0QkXytrQaPXncS01RrtkmnE99s0C', + 'version': '1FLxEJSOELZwZp7jdC7zBwVTH4kmYsGarXs-0ai8DlEC', }, ], 'condition': 'checkout_android', @@ -1751,7 +1751,7 @@ Var('pdfium_git') + '/pdfium.git' + '@' + Var('pdfium_revision'), 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '7f196bdc6e5ebe2bca86482fa245aefaeb0cb862', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '05046ffbfb82eacaac4da0cf46e26720399d2a57', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1791,7 +1791,7 @@ 'packages': [ { 'package': 'chromium/third_party/r8', - 'version': 'crtFbDFNOQ4YZT_MQmz65TmbaQo5-URl1at11okEGTUC', + 'version': 'yzMcbNWqwcCFz7jyW-IO5GOVOZJ22lULFzqt12-T2fEC', }, ], 'condition': 'checkout_android', @@ -1936,7 +1936,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '0369f5dc081b75a1c94d31259aff37244f527e92', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '952e0b75f9d5d0b54c8e75ea44b0a1920003ee51', + Var('webrtc_git') + '/src.git' + '@' + 'f263e1eb038e195d16b7c1b15cdfb6db82b32e4d', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file. @@ -2103,7 +2103,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/projector_app/app', - 'version': 'rAK6WkE4AdUGKjim_DGwMhjhLOOn6rTdgR7vbKYf2TQC', + 'version': 'h0N0CseUHPELiooNMD7vJeMs5JrM0Lxhe0RKYSTY4T4C', }, ], 'condition': 'checkout_chromeos and checkout_src_internal', @@ -4163,7 +4163,7 @@ 'src/components/autofill/core/browser/form_parsing/internal_resources': { 'url': Var('chrome_git') + '/chrome/components/autofill_regex_patterns.git' + '@' + - '927feef20b72218d2afb2deaa3ec7dd972c7e116', + '8d5b9c6b4200e59297bb32f8cca01d7564eb259b', 'condition': 'checkout_src_internal', }, @@ -4234,7 +4234,7 @@ 'src/ios_internal': { 'url': Var('chrome_git') + '/chrome/ios_internal.git' + '@' + - '532d047d3298bf68a15b5f898ebb05cb974dbc47', + 'f561745958bd66b26eca4207503d95b5f7e85609', 'condition': 'checkout_ios and checkout_src_internal', },
diff --git a/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.cc b/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.cc index 3d48126..cf95fb68 100644 --- a/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.cc +++ b/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.cc
@@ -33,9 +33,10 @@ return base::FeatureList::IsEnabled(features::kV8PerFrameMemoryMonitoring); } -KeyedService* AwPageLoadMetricsMemoryTrackerFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +AwPageLoadMetricsMemoryTrackerFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { - return new page_load_metrics::PageLoadMetricsMemoryTracker(); + return std::make_unique<page_load_metrics::PageLoadMetricsMemoryTracker>(); } content::BrowserContext*
diff --git a/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.h b/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.h index ce3cc97..c7d5b689 100644 --- a/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.h +++ b/android_webview/browser/page_load_metrics/aw_page_load_metrics_memory_tracker_factory.h
@@ -27,7 +27,7 @@ // BrowserContextKeyedServiceFactory: bool ServiceIsCreatedWithBrowserContext() const override; - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; content::BrowserContext* GetBrowserContextToUse(
diff --git a/ash/app_list/views/pagination_model_transition_waiter.h b/ash/app_list/views/pagination_model_transition_waiter.h index 1c8f4fd..78a0f60e 100644 --- a/ash/app_list/views/pagination_model_transition_waiter.h +++ b/ash/app_list/views/pagination_model_transition_waiter.h
@@ -9,7 +9,7 @@ #include "ash/public/cpp/pagination/pagination_model.h" #include "ash/public/cpp/pagination/pagination_model_observer.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" namespace base {
diff --git a/ash/curtain/remote_maintenance_curtain_view.h b/ash/curtain/remote_maintenance_curtain_view.h index 971050e..333f5b5 100644 --- a/ash/curtain/remote_maintenance_curtain_view.h +++ b/ash/curtain/remote_maintenance_curtain_view.h
@@ -6,7 +6,7 @@ #define ASH_CURTAIN_REMOTE_MAINTENANCE_CURTAIN_VIEW_H_ #include "ash/ash_export.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/views/view.h" namespace ash {
diff --git a/ash/glanceables/common/glanceables_list_footer_view.h b/ash/glanceables/common/glanceables_list_footer_view.h index 90b20f3..170e5eb3 100644 --- a/ash/glanceables/common/glanceables_list_footer_view.h +++ b/ash/glanceables/common/glanceables_list_footer_view.h
@@ -8,8 +8,8 @@ #include <string> #include "ash/ash_export.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/layout/flex_layout_view.h"
diff --git a/ash/glanceables/common/glanceables_progress_bar_view.h b/ash/glanceables/common/glanceables_progress_bar_view.h index 09c1035..db708da8b8 100644 --- a/ash/glanceables/common/glanceables_progress_bar_view.h +++ b/ash/glanceables/common/glanceables_progress_bar_view.h
@@ -6,7 +6,7 @@ #define ASH_GLANCEABLES_COMMON_GLANCEABLES_PROGRESS_BAR_VIEW_H_ #include "ash/ash_export.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/views/layout/flex_layout_view.h" namespace views {
diff --git a/ash/shelf/desk_button_widget.h b/ash/shelf/desk_button_widget.h index 2e589d3f..f57d9e0 100644 --- a/ash/shelf/desk_button_widget.h +++ b/ash/shelf/desk_button_widget.h
@@ -7,7 +7,7 @@ #include "ash/ash_export.h" #include "ash/shelf/shelf_component.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/views/widget/widget.h" namespace ash {
diff --git a/ash/system/accessibility/accessibility_detailed_view.h b/ash/system/accessibility/accessibility_detailed_view.h index 9c7098d0..e640988 100644 --- a/ash/system/accessibility/accessibility_detailed_view.h +++ b/ash/system/accessibility/accessibility_detailed_view.h
@@ -11,7 +11,6 @@ #include "ash/accessibility/accessibility_observer.h" #include "ash/public/cpp/session/session_observer.h" #include "ash/system/tray/tray_detailed_view.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/memory/raw_ptr.h" #include "components/soda/soda_installer.h" #include "ui/gfx/font.h"
diff --git a/ash/system/accessibility/accessibility_feature_pod_controller.h b/ash/system/accessibility/accessibility_feature_pod_controller.h index 624291b..40441ac 100644 --- a/ash/system/accessibility/accessibility_feature_pod_controller.h +++ b/ash/system/accessibility/accessibility_feature_pod_controller.h
@@ -11,7 +11,6 @@ #include "ash/ash_export.h" #include "ash/constants/quick_settings_catalogs.h" #include "ash/system/unified/feature_pod_controller_base.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h"
diff --git a/ash/system/holding_space/holding_space_item_chip_view.cc b/ash/system/holding_space/holding_space_item_chip_view.cc index e64e9fb..9cb0583f 100644 --- a/ash/system/holding_space/holding_space_item_chip_view.cc +++ b/ash/system/holding_space/holding_space_item_chip_view.cc
@@ -26,8 +26,8 @@ #include "ash/system/progress_indicator/progress_indicator.h" #include "ash/system/progress_indicator/progress_indicator_animation_registry.h" #include "ash/system/progress_indicator/progress_ring_animation.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" +#include "base/memory/raw_ptr.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/models/image_model.h"
diff --git a/ash/system/power/power_button_menu_curtain_view.h b/ash/system/power/power_button_menu_curtain_view.h index a6c4e5e..cfa7f94 100644 --- a/ash/system/power/power_button_menu_curtain_view.h +++ b/ash/system/power/power_button_menu_curtain_view.h
@@ -7,8 +7,8 @@ #include "ash/ash_export.h" #include "ash/style/system_shadow.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/check_deref.h" +#include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/views/controls/image_view.h"
diff --git a/ash/system/unified/classroom_bubble_view_unittest.cc b/ash/system/unified/classroom_bubble_view_unittest.cc index e125db7..fca24232 100644 --- a/ash/system/unified/classroom_bubble_view_unittest.cc +++ b/ash/system/unified/classroom_bubble_view_unittest.cc
@@ -18,7 +18,7 @@ #include "ash/system/unified/classroom_bubble_student_view.h" #include "ash/system/unified/classroom_bubble_teacher_view.h" #include "ash/test/ash_test_base.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" #include "base/types/cxx23_to_underlying.h"
diff --git a/ash/system/unified/tasks_bubble_view_unittest.cc b/ash/system/unified/tasks_bubble_view_unittest.cc index d1836d7..3ed3c6e 100644 --- a/ash/system/unified/tasks_bubble_view_unittest.cc +++ b/ash/system/unified/tasks_bubble_view_unittest.cc
@@ -15,7 +15,7 @@ #include "ash/system/tray/detailed_view_delegate.h" #include "ash/system/unified/tasks_bubble_view.h" #include "ash/test/ash_test_base.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "base/types/cxx23_to_underlying.h"
diff --git a/ash/system/unified/unified_slider_view_pixeltest.cc b/ash/system/unified/unified_slider_view_pixeltest.cc index 25a32d9b..794c761 100644 --- a/ash/system/unified/unified_slider_view_pixeltest.cc +++ b/ash/system/unified/unified_slider_view_pixeltest.cc
@@ -10,7 +10,7 @@ #include "ash/test/ash_test_base.h" #include "ash/test/pixel/ash_pixel_differ.h" #include "ash/test/pixel/ash_pixel_test_init_params.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "chromeos/constants/chromeos_features.h" #include "ui/views/widget/widget.h"
diff --git a/ash/system/video_conference/bubble/toggle_effects_view.h b/ash/system/video_conference/bubble/toggle_effects_view.h index 90b0955b..a09ac20 100644 --- a/ash/system/video_conference/bubble/toggle_effects_view.h +++ b/ash/system/video_conference/bubble/toggle_effects_view.h
@@ -5,7 +5,7 @@ #ifndef ASH_SYSTEM_VIDEO_CONFERENCE_BUBBLE_TOGGLE_EFFECTS_VIEW_H_ #define ASH_SYSTEM_VIDEO_CONFERENCE_BUBBLE_TOGGLE_EFFECTS_VIEW_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h"
diff --git a/ash/wm/desks/desk_bar_controller.h b/ash/wm/desks/desk_bar_controller.h index 38ab16d..607f9e4 100644 --- a/ash/wm/desks/desk_bar_controller.h +++ b/ash/wm/desks/desk_bar_controller.h
@@ -15,7 +15,7 @@ #include "ash/wm/desks/desk_button/desk_button.h" #include "ash/wm/desks/desks_controller.h" #include "ash/wm/overview/overview_observer.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/display/display_observer.h" #include "ui/events/event_handler.h" #include "ui/gfx/geometry/rect.h"
diff --git a/ash/wm/desks/desk_bar_view_base.h b/ash/wm/desks/desk_bar_view_base.h index 19f496a7..96516f4 100644 --- a/ash/wm/desks/desk_bar_view_base.h +++ b/ash/wm/desks/desk_bar_view_base.h
@@ -17,7 +17,6 @@ #include "ash/wm/desks/scroll_arrow_button.h" #include "ash/wm/desks/zero_state_button.h" #include "ash/wm/overview/overview_grid.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/events/event.h"
diff --git a/ash/wm/overview/overview_item_base.h b/ash/wm/overview/overview_item_base.h index c6297f7e..4913cbf2 100644 --- a/ash/wm/overview/overview_item_base.h +++ b/ash/wm/overview/overview_item_base.h
@@ -9,7 +9,7 @@ #include <vector> #include "ash/wm/overview/overview_types.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" namespace aura { class Window;
diff --git a/ash/wm/window_cycle/window_cycle_item_view.h b/ash/wm/window_cycle/window_cycle_item_view.h index f8d08dd..62055bb2 100644 --- a/ash/wm/window_cycle/window_cycle_item_view.h +++ b/ash/wm/window_cycle/window_cycle_item_view.h
@@ -7,7 +7,7 @@ #include "ash/ash_export.h" #include "ash/wm/window_mini_view.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/events/event.h" #include "ui/gfx/geometry/size.h"
diff --git a/base/allocator/partition_allocator/partition_root.cc b/base/allocator/partition_allocator/partition_root.cc index a82210c..b805706 100644 --- a/base/allocator/partition_allocator/partition_root.cc +++ b/base/allocator/partition_allocator/partition_root.cc
@@ -1313,7 +1313,7 @@ const bool hooks_enabled = PartitionAllocHooks::AreHooksEnabled(); bool overridden = false; size_t old_usable_size; - if (PA_UNLIKELY(!no_hooks && hooks_enabled)) { + if (!no_hooks && hooks_enabled) { overridden = PartitionAllocHooks::ReallocOverrideHookIfEnabled( &old_usable_size, ptr); }
diff --git a/base/allocator/partition_allocator/partition_root.h b/base/allocator/partition_allocator/partition_root.h index 446b5bcb0..5409199 100644 --- a/base/allocator/partition_allocator/partition_root.h +++ b/base/allocator/partition_allocator/partition_root.h
@@ -1901,7 +1901,7 @@ #endif // defined(MEMORY_TOOL_REPLACES_ALLOCATOR) void* object = nullptr; const bool hooks_enabled = PartitionAllocHooks::AreHooksEnabled(); - if (PA_UNLIKELY(hooks_enabled)) { + if (hooks_enabled) { unsigned int additional_flags = 0; #if PA_CONFIG(HAS_MEMORY_TAGGING) if (IsMemoryTaggingEnabled()) {
diff --git a/base/tracing/BUILD.gn b/base/tracing/BUILD.gn index 183eab0..624cc28 100644 --- a/base/tracing/BUILD.gn +++ b/base/tracing/BUILD.gn
@@ -24,7 +24,7 @@ _rebased_all_chrome_metrics_descriptor = rebase_path(_all_chrome_metrics_descriptor, root_build_dir) _chrome_track_event_descriptor = - "$_protos_path/third_party/chromium/chrome_track_event.descriptor" + "$root_gen_dir/base/tracing/protos/chrome_track_event.descriptor" _rebased_chrome_track_event_descriptor = rebase_path(_chrome_track_event_descriptor, root_build_dir) @@ -59,11 +59,11 @@ ] data_deps = [ + "//base/tracing/protos:chrome_track_event", "//third_party/perfetto/protos/perfetto/metrics:descriptor", "//third_party/perfetto/protos/perfetto/metrics/chrome:descriptor", "//third_party/perfetto/protos/perfetto/trace:descriptor", "//third_party/perfetto/protos/perfetto/trace:test_extensions_descriptor", - "//third_party/perfetto/protos/third_party/chromium:descriptor", "//third_party/perfetto/src/trace_processor:trace_processor_shell", ]
diff --git a/base/tracing/PRESUBMIT.py b/base/tracing/PRESUBMIT.py index 188dc0d..2b69e74 100644 --- a/base/tracing/PRESUBMIT.py +++ b/base/tracing/PRESUBMIT.py
@@ -27,6 +27,7 @@ _STDLIB_PATHS = ( r"^base/tracing/stdlib/", r"^base/tracing/test/", + r"^base/tracing/protos/" ) def CheckPerfettoTestsTag(input_api, output_api):
diff --git a/chrome/browser/accessibility/accessibility_extension_api_chromeos.cc b/chrome/browser/accessibility/accessibility_extension_api_chromeos.cc index f36dd45c..f01cbd4 100644 --- a/chrome/browser/accessibility/accessibility_extension_api_chromeos.cc +++ b/chrome/browser/accessibility/accessibility_extension_api_chromeos.cc
@@ -270,6 +270,10 @@ enabled = ::features::IsAccessibilityChromeVoxPageMigrationEnabled(); break; case accessibility_private::AccessibilityFeature:: + ACCESSIBILITY_FEATURE_GAMEFACEINTEGRATION: + enabled = ::features::IsAccessibilityGameFaceIntegrationEnabled(); + break; + case accessibility_private::AccessibilityFeature:: ACCESSIBILITY_FEATURE_NONE: return RespondNow(Error("Unrecognized feature")); }
diff --git a/chrome/browser/apps/app_service/metrics/website_metrics_browsertest.cc b/chrome/browser/apps/app_service/metrics/website_metrics_browsertest.cc index b54a2aca..0707b49 100644 --- a/chrome/browser/apps/app_service/metrics/website_metrics_browsertest.cc +++ b/chrome/browser/apps/app_service/metrics/website_metrics_browsertest.cc
@@ -5,7 +5,6 @@ #include <memory> #include <set> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/containers/contains.h" #include "base/json/values_util.h" #include "base/memory/raw_ptr.h"
diff --git a/chrome/browser/ash/BUILD.gn b/chrome/browser/ash/BUILD.gn index 80a803cc..6097afe0 100644 --- a/chrome/browser/ash/BUILD.gn +++ b/chrome/browser/ash/BUILD.gn
@@ -4241,6 +4241,7 @@ ] deps += [ "//chromeos/ash/components/chromebox_for_meetings", + "//components/media_device_salt", "//components/variations/field_trial_config", "//extensions/buildflags", ]
diff --git a/chrome/browser/ash/chromebox_for_meetings/xu_camera/DEPS b/chrome/browser/ash/chromebox_for_meetings/xu_camera/DEPS new file mode 100644 index 0000000..0d17b3db --- /dev/null +++ b/chrome/browser/ash/chromebox_for_meetings/xu_camera/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+components/media_device_salt", +]
diff --git a/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.cc b/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.cc index c83f0a17..443ef41 100644 --- a/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.cc +++ b/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.cc
@@ -16,8 +16,16 @@ #include <cstdint> #include <utility> +#include "chrome/browser/media/webrtc/media_device_salt_service_factory.h" #include "chromeos/ash/components/dbus/chromebox_for_meetings/cfm_hotline_client.h" +#include "chromeos/ash/services/chromebox_for_meetings/public/cpp/service_connection.h" +#include "components/media_device_salt/media_device_salt_service.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/device_service.h" +#include "content/public/browser/global_routing_id.h" +#include "content/public/browser/media_device_id.h" +#include "content/public/browser/render_frame_host.h" #include "services/device/public/mojom/usb_device.mojom.h" #include "services/device/public/mojom/usb_enumeration_options.mojom.h" @@ -64,6 +72,27 @@ } }; +void TranslateDeviceId( + const std::string& hashed_device_id, + base::OnceCallback<void(const absl::optional<std::string>&)> callback, + const url::Origin& security_origin, + const std::string& salt) { + auto translate_device_id_callback = base::BindOnce( + [](const std::string& hashed_device_id, + base::OnceCallback<void(const absl::optional<std::string>&)> callback, + const url::Origin& security_origin, const std::string& salt) { + content::GetMediaDeviceIDForHMAC( + blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, salt, + security_origin, hashed_device_id, + content::GetUIThreadTaskRunner({}), std::move(callback)); + }, + std::move(hashed_device_id), std::move(callback), + std::move(security_origin), std::move(salt)); + + content::GetIOThreadTaskRunner({})->PostTask( + FROM_HERE, std::move(translate_device_id_callback)); +} + XuCameraService* g_xu_camera_service = nullptr; } // namespace @@ -77,26 +106,31 @@ CfmHotlineClient::Get()->RemoveObserver(this); } +// static void XuCameraService::Initialize() { CHECK(!g_xu_camera_service); g_xu_camera_service = new XuCameraService(new RealDelegate()); } +// static void XuCameraService::InitializeForTesting(Delegate* delegate) { CHECK(!g_xu_camera_service); g_xu_camera_service = new XuCameraService(delegate); } +// static void XuCameraService::Shutdown() { CHECK(g_xu_camera_service); delete g_xu_camera_service; g_xu_camera_service = nullptr; } +// static XuCameraService* XuCameraService::Get() { return g_xu_camera_service; } +// static bool XuCameraService::IsInitialized() { return g_xu_camera_service; } @@ -132,10 +166,22 @@ return true; } +void XuCameraService::BindServiceContext( + mojo::PendingReceiver<mojom::XuCamera> receiver, + const content::GlobalRenderFrameHostId& id) { + receivers_.Add(this, std::move(receiver), std::move(id)); +} + void XuCameraService::OnBindService( mojo::ScopedMessagePipeHandle receiver_pipe) { - receivers_.Add( - this, mojo::PendingReceiver<mojom::XuCamera>(std::move(receiver_pipe))); + // The Render Frame Host Id is used to identify the peripheral's device path + // given a hased device id. If the origin of the client is not from within a + // chromium renderer then the device paths would not be hashed. + // We give a default RFH ID here for these cases that will fail if mistakenly + // passed a HMAC ID. + BindServiceContext( + mojo::PendingReceiver<mojom::XuCamera>(std::move(receiver_pipe)), + content::GlobalRenderFrameHostId()); } void XuCameraService::OnAdaptorDisconnect() { @@ -146,9 +192,23 @@ delegate_ = delegate; } -void XuCameraService::GetUnitId(const mojom::WebcamIdPtr id, +void XuCameraService::GetUnitId(mojom::WebcamIdPtr id, const std::vector<uint8_t>& guid_le, GetUnitIdCallback callback) { + auto host_id = receivers_.current_context(); + + auto get_unit_id_callback = base::BindOnce( + &XuCameraService::GetUnitIdWithDevicePath, weak_factory_.GetWeakPtr(), + std::move(guid_le), std::move(callback)); + + GetDevicePath(std::move(id), std::move(host_id), + std::move(get_unit_id_callback)); +} + +void XuCameraService::GetUnitIdWithDevicePath( + const std::vector<uint8_t>& guid_le, + GetUnitIdCallback callback, + const absl::optional<std::string>& dev_path) { // TODO(b/260593636): Leverage WebRTC and GetDevicePath() once implemented auto unitId = guid_unitid_map_.find(guid_le); if (unitId != guid_unitid_map_.end()) { @@ -215,15 +275,35 @@ std::move(callback).Run(ENOSYS, '0'); } -void XuCameraService::MapCtrl(const mojom::WebcamIdPtr id, - const mojom::ControlMappingPtr mapping_ctrl, +void XuCameraService::MapCtrl(mojom::WebcamIdPtr id, + mojom::ControlMappingPtr mapping_ctrl, MapCtrlCallback callback) { + auto host_id = receivers_.current_context(); + + auto map_ctrl_callback = base::BindOnce( + &XuCameraService::MapCtrlWithDevicePath, weak_factory_.GetWeakPtr(), + std::move(mapping_ctrl), std::move(callback)); + + GetDevicePath(std::move(id), std::move(host_id), + std::move(map_ctrl_callback)); +} + +void XuCameraService::MapCtrlWithDevicePath( + const mojom::ControlMappingPtr mapping_ctrl, + MapCtrlCallback callback, + const absl::optional<std::string>& dev_path) { uint8_t error_code = 0; - std::string dev_path = id->is_device_id() ? GetDevicePath(id->get_device_id()) - : id->get_dev_path(); - VLOG(4) << __func__ << ": dev_path - " << dev_path; base::ScopedFD file_descriptor; - if (!delegate_->OpenFile(file_descriptor, dev_path)) { + + if (!dev_path) { + LOG(ERROR) << __func__ << ": Unable to determine device path"; + std::move(callback).Run(ENOENT); + return; + } + + VLOG(4) << __func__ << ": dev_path - " << *dev_path; + + if (!delegate_->OpenFile(file_descriptor, *dev_path)) { LOG(ERROR) << __func__ << ": File is invalid"; std::move(callback).Run(ENOENT); return; @@ -262,18 +342,38 @@ std::move(callback).Run(error_code); } -void XuCameraService::GetCtrl(const mojom::WebcamIdPtr id, - const mojom::CtrlTypePtr ctrl, - const mojom::GetFn fn, +void XuCameraService::GetCtrl(mojom::WebcamIdPtr id, + mojom::CtrlTypePtr ctrl, + mojom::GetFn fn, GetCtrlCallback callback) { + auto host_id = receivers_.current_context(); + + auto get_ctrl_callback = base::BindOnce( + &XuCameraService::GetCtrlWithDevicePath, weak_factory_.GetWeakPtr(), + std::move(ctrl), std::move(fn), std::move(callback)); + + GetDevicePath(std::move(id), std::move(host_id), + std::move(get_ctrl_callback)); +} + +void XuCameraService::GetCtrlWithDevicePath( + const mojom::CtrlTypePtr ctrl, + const mojom::GetFn fn, + GetCtrlCallback callback, + const absl::optional<std::string>& dev_path) { uint8_t error_code = 0; std::vector<uint8_t> data; - std::string dev_path = id->is_device_id() ? GetDevicePath(id->get_device_id()) - : id->get_dev_path(); - - VLOG(4) << __func__ << ": dev_path - " << dev_path; base::ScopedFD file_descriptor; - if (!delegate_->OpenFile(file_descriptor, dev_path)) { + + if (!dev_path) { + LOG(ERROR) << __func__ << ": Unable to determine device path"; + std::move(callback).Run(ENOENT, data); + return; + } + + VLOG(4) << __func__ << ": dev_path - " << *dev_path; + + if (!delegate_->OpenFile(file_descriptor, *dev_path)) { LOG(ERROR) << __func__ << ": File is invalid"; std::move(callback).Run(ENOENT, data); return; @@ -297,16 +397,37 @@ std::move(callback).Run(error_code, data); } -void XuCameraService::SetCtrl(const mojom::WebcamIdPtr id, - const mojom::CtrlTypePtr ctrl, +void XuCameraService::SetCtrl(mojom::WebcamIdPtr id, + mojom::CtrlTypePtr ctrl, const std::vector<uint8_t>& data, SetCtrlCallback callback) { + auto host_id = receivers_.current_context(); + + auto set_ctrl_callback = base::BindOnce( + &XuCameraService::SetCtrlWithDevicePath, weak_factory_.GetWeakPtr(), + std::move(ctrl), std::move(data), std::move(callback)); + + GetDevicePath(std::move(id), std::move(host_id), + std::move(set_ctrl_callback)); +} + +void XuCameraService::SetCtrlWithDevicePath( + const mojom::CtrlTypePtr ctrl, + const std::vector<uint8_t>& data, + SetCtrlCallback callback, + const absl::optional<std::string>& dev_path) { uint8_t error_code = 0; - std::string dev_path = id->is_device_id() ? GetDevicePath(id->get_device_id()) - : id->get_dev_path(); - VLOG(4) << __func__ << ": dev_path - " << dev_path; + + if (!dev_path) { + LOG(ERROR) << __func__ << ": Unable to determine device path"; + std::move(callback).Run(ENOENT); + return; + } + + VLOG(4) << __func__ << ": dev_path - " << *dev_path; + base::ScopedFD file_descriptor; - if (!delegate_->OpenFile(file_descriptor, dev_path)) { + if (!delegate_->OpenFile(file_descriptor, *dev_path)) { LOG(ERROR) << __func__ << ": File is invalid"; std::move(callback).Run(ENOENT); return; @@ -362,10 +483,44 @@ return error; } -std::string XuCameraService::GetDevicePath(const std::string& device_id) { - // Not implemented - NOTIMPLEMENTED(); - return ""; +void XuCameraService::GetDevicePath( + mojom::WebcamIdPtr id, + const content::GlobalRenderFrameHostId& host_id, + base::OnceCallback<void(const absl::optional<std::string>&)> callback) + const { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + if (id->is_dev_path()) { + std::move(callback).Run(id->get_dev_path()); + return; + } + + // TODO(b/295912291): Check get_device_id is in a map + auto hashed_device_id = id->get_device_id(); + + if (!host_id || hashed_device_id.empty()) { + std::move(callback).Run(absl::nullopt); + return; + } + + content::RenderFrameHost* frame_host = + content::RenderFrameHost::FromID(host_id); + content::BrowserContext* browser_context = frame_host->GetBrowserContext(); + url::Origin security_origin = frame_host->GetLastCommittedOrigin(); + + if (media_device_salt::MediaDeviceSaltService* salt_service = + MediaDeviceSaltServiceFactory::GetInstance()->GetForBrowserContext( + browser_context)) { + salt_service->GetSalt( + frame_host->GetStorageKey(), + base::BindOnce(&TranslateDeviceId, hashed_device_id, + std::move(callback), std::move(security_origin))); + } else { + // If the embedder does not provide a salt service, use the browser + // context's unique ID as salt. + TranslateDeviceId(hashed_device_id, std::move(callback), + std::move(security_origin), browser_context->UniqueId()); + } } uint8_t XuCameraService::CtrlThroughQuery(const base::ScopedFD& file_descriptor,
diff --git a/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.h b/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.h index 36443c0..7116b196 100644 --- a/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.h +++ b/chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.h
@@ -19,12 +19,15 @@ #include "chrome/browser/ash/chromebox_for_meetings/service_adaptor.h" #include "chromeos/ash/components/dbus/chromebox_for_meetings/cfm_observer.h" #include "chromeos/ash/services/chromebox_for_meetings/public/mojom/xu_camera.mojom.h" -#include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_manager.mojom.h" #include "services/device/public/mojom/usb_manager_client.mojom.h" +namespace content { +struct GlobalRenderFrameHostId; +} // namespace content + namespace ash::cfm { // Implementation of the XuCamera Service @@ -60,6 +63,14 @@ static bool IsInitialized(); static uint8_t GetRequest(const mojom::GetFn& fn); + // Called when attempting to Bind a mojom using using a message pipe of the + // given types PendingReceiver |receiver_pipe|. + // |content::GlobalRenderFrameHostId| used to dereference hashed device id. + // Note: Only the user facing usecases requires this value; other uses + // of this service will not require a valid |content::GlobalRenderFrameHostId| + void BindServiceContext(mojo::PendingReceiver<mojom::XuCamera> receiver, + const content::GlobalRenderFrameHostId& id); + protected: // If nullptr is passed the default Delegate will be used explicit XuCameraService(Delegate* delegate_); @@ -72,18 +83,18 @@ void OnAdaptorDisconnect() override; // mojom:XuCamera implementation - void GetUnitId(const mojom::WebcamIdPtr id, + void GetUnitId(mojom::WebcamIdPtr id, const std::vector<uint8_t>& guid_le, GetUnitIdCallback callback) override; - void MapCtrl(const mojom::WebcamIdPtr id, - const mojom::ControlMappingPtr mapping_ctrl, + void MapCtrl(mojom::WebcamIdPtr id, + mojom::ControlMappingPtr mapping_ctrl, MapCtrlCallback callback) override; - void GetCtrl(const mojom::WebcamIdPtr id, - const mojom::CtrlTypePtr ctrl, - const mojom::GetFn fn, + void GetCtrl(mojom::WebcamIdPtr id, + mojom::CtrlTypePtr ctrl, + mojom::GetFn fn, GetCtrlCallback callback) override; - void SetCtrl(const mojom::WebcamIdPtr id, - const mojom::CtrlTypePtr ctrl, + void SetCtrl(mojom::WebcamIdPtr id, + mojom::CtrlTypePtr ctrl, const std::vector<uint8_t>& data, SetCtrlCallback callback) override; @@ -91,13 +102,31 @@ void SetDelegate(Delegate* delegate); private: + void GetUnitIdWithDevicePath(const std::vector<uint8_t>& guid_le, + GetUnitIdCallback callback, + const absl::optional<std::string>& dev_path); + void MapCtrlWithDevicePath(mojom::ControlMappingPtr mapping_ctrl, + MapCtrlCallback callback, + const absl::optional<std::string>& dev_path); + void GetCtrlWithDevicePath(mojom::CtrlTypePtr ctrl, + mojom::GetFn fn, + GetCtrlCallback callback, + const absl::optional<std::string>& dev_path); + void SetCtrlWithDevicePath(mojom::CtrlTypePtr ctrl, + const std::vector<uint8_t>& data, + SetCtrlCallback callback, + const absl::optional<std::string>& dev_path); uint8_t QueryXuControl(const base::ScopedFD& file_descriptor, uint8_t unit_id, uint8_t selector, uint8_t* data, uint8_t query_request, uint16_t size); - std::string GetDevicePath(const std::string& device_id); + void GetDevicePath( + mojom::WebcamIdPtr id, + const content::GlobalRenderFrameHostId& host_id, + base::OnceCallback<void(const absl::optional<std::string>&)> callback) + const; uint8_t CtrlThroughQuery(const base::ScopedFD& file_descriptor, const mojom::ControlQueryPtr& query, std::vector<uint8_t>& data, @@ -120,7 +149,7 @@ std::vector<device::mojom::UsbDeviceInfoPtr> devices); raw_ptr<Delegate, ExperimentalAsh> delegate_; ServiceAdaptor service_adaptor_; - mojo::ReceiverSet<XuCamera> receivers_; + mojo::ReceiverSet<XuCamera, content::GlobalRenderFrameHostId> receivers_; mojo::Remote<device::mojom::UsbDeviceManager> usb_manager_; std::map<std::vector<uint8_t>, uint8_t> guid_unitid_map_ = {}; base::WeakPtrFactory<XuCameraService> weak_factory_{this};
diff --git a/chrome/browser/ash/crosapi/test_crosapi_environment.h b/chrome/browser/ash/crosapi/test_crosapi_environment.h index fa8d8b56..c1d79f9 100644 --- a/chrome/browser/ash/crosapi/test_crosapi_environment.h +++ b/chrome/browser/ash/crosapi/test_crosapi_environment.h
@@ -7,7 +7,7 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h"
diff --git a/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc b/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc index 714b347..cd38c8cf 100644 --- a/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc +++ b/chrome/browser/ash/dbus/dlp_files_policy_service_provider.cc
@@ -33,9 +33,9 @@ case dlp::FileAction::MOVE: return policy::dlp::FileAction::kMove; case dlp::FileAction::OPEN: - // TODO(crbug.com/1378653): Return open FileAction. + return policy::dlp::FileAction::kOpen; case dlp::FileAction::SHARE: - // TODO(crbug.com/1378653): Return share FileAction. + return policy::dlp::FileAction::kShare; case dlp::FileAction::TRANSFER: return policy::dlp::FileAction::kTransfer; } @@ -157,7 +157,6 @@ policy::DlpFilesControllerAsh* files_controller = policy::DlpFilesControllerAsh::GetForPrimaryProfile(); - // TODO(crbug.com/1360005): Add actual file path. bool restricted = files_controller ? files_controller->IsDlpPolicyMatched(
diff --git a/chrome/browser/ash/dbus/dlp_files_policy_service_provider_unittest.cc b/chrome/browser/ash/dbus/dlp_files_policy_service_provider_unittest.cc index 513f9fe..a0b5e56 100644 --- a/chrome/browser/ash/dbus/dlp_files_policy_service_provider_unittest.cc +++ b/chrome/browser/ash/dbus/dlp_files_policy_service_provider_unittest.cc
@@ -4,19 +4,18 @@ #include <memory> -#include "base/memory/raw_ptr.h" +#include "base/test/gmock_callback_support.h" #include "chrome/browser/ash/dbus/dlp_files_policy_service_provider.h" -#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h" #include "chrome/browser/ash/policy/dlp/dlp_files_controller_ash.h" -#include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" -#include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_factory.h" +#include "chrome/browser/ash/policy/dlp/test/mock_dlp_files_controller_ash.h" +#include "chrome/browser/chromeos/policy/dlp/dlp_files_controller.h" +#include "chrome/browser/chromeos/policy/dlp/dlp_files_utils.h" +#include "chrome/browser/chromeos/policy/dlp/test/dlp_files_test_base.h" #include "chrome/browser/chromeos/policy/dlp/test/mock_dlp_rules_manager.h" -#include "chrome/test/base/testing_profile.h" #include "chromeos/ash/components/dbus/services/service_provider_test_helper.h" #include "chromeos/dbus/dlp/dlp_service.pb.h" -#include "components/user_manager/scoped_user_manager.h" -#include "content/public/test/browser_task_environment.h" #include "dbus/object_path.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/dlp/dbus-constants.h" @@ -24,24 +23,21 @@ namespace { -constexpr char kEmailId[] = "test@example.com"; -constexpr char kGaiaId[] = "12345"; - constexpr char kExampleUrl[] = "https://example.com"; constexpr char kExampleUrl2[] = "https://example2.com"; constexpr ino_t kInode = 0; constexpr char kFilePath[] = "test.txt"; +using FileDaemonInfo = policy::DlpFilesController::FileDaemonInfo; + } // namespace class DlpFilesPolicyServiceProviderTest - : public testing::TestWithParam<policy::DlpRulesManager::Level> { + : public policy::DlpFilesTestBase, + public ::testing::WithParamInterface<policy::DlpRulesManager::Level> { protected: DlpFilesPolicyServiceProviderTest() - : profile_(std::make_unique<TestingProfile>()), - user_manager_(new FakeChromeUserManager()), - scoped_user_manager_(base::WrapUnique(user_manager_.get())), - dlp_policy_service_(std::make_unique<DlpFilesPolicyServiceProvider>()) { + : dlp_policy_service_(std::make_unique<DlpFilesPolicyServiceProvider>()) { } DlpFilesPolicyServiceProviderTest(const DlpFilesPolicyServiceProviderTest&) = @@ -54,24 +50,17 @@ } void SetUp() override { - AccountId account_id = AccountId::FromUserEmailGaiaId(kEmailId, kGaiaId); - profile_->SetIsNewProfile(true); - user_manager::User* user = - user_manager_->AddUserWithAffiliationAndTypeAndProfile( - account_id, /*is_affiliated=*/false, - user_manager::USER_TYPE_REGULAR, profile_.get()); - user_manager_->UserLoggedIn(account_id, user->username_hash(), - /*browser_restart=*/false, - /*is_child=*/false); - user_manager_->SimulateUserProfileLoad(account_id); + DlpFilesTestBase::SetUp(); - policy::DlpRulesManagerFactory::GetInstance()->SetTestingFactory( - profile_.get(), - base::BindRepeating( - &DlpFilesPolicyServiceProviderTest::SetDlpRulesManager, - base::Unretained(this))); - ASSERT_TRUE(policy::DlpRulesManagerFactory::GetForPrimaryProfile()); - ASSERT_TRUE(mock_rules_manager_); + EXPECT_CALL(*rules_manager_, IsFilesPolicyEnabled) + .WillRepeatedly(testing::Return(true)); + EXPECT_CALL(*rules_manager_, GetReportingManager()) + .WillRepeatedly(::testing::Return(nullptr)); + files_controller_ = std::make_unique< + testing::StrictMock<policy::MockDlpFilesControllerAsh>>( + *rules_manager_); + EXPECT_CALL(*rules_manager_, GetDlpFilesController()) + .WillRepeatedly(::testing::Return(files_controller_.get())); } template <class ResponseProtoType> @@ -101,34 +90,12 @@ return response; } - std::unique_ptr<KeyedService> SetDlpRulesManager( - content::BrowserContext* context) { - auto dlp_rules_manager = - std::make_unique<testing::StrictMock<policy::MockDlpRulesManager>>(); - mock_rules_manager_ = dlp_rules_manager.get(); - ON_CALL(*mock_rules_manager_, IsFilesPolicyEnabled) - .WillByDefault(testing::Return(true)); - - files_controller_ = - std::make_unique<policy::DlpFilesControllerAsh>(*mock_rules_manager_); - - return dlp_rules_manager; - } - - content::BrowserTaskEnvironment task_environment_; - - raw_ptr<policy::MockDlpRulesManager, DanglingUntriaged | ExperimentalAsh> - mock_rules_manager_ = nullptr; - - const std::unique_ptr<TestingProfile> profile_; - raw_ptr<FakeChromeUserManager, DanglingUntriaged | ExperimentalAsh> - user_manager_; - user_manager::ScopedUserManager scoped_user_manager_; std::unique_ptr<DlpFilesPolicyServiceProvider> dlp_policy_service_; ServiceProviderTestHelper dbus_service_test_helper_; - std::unique_ptr<policy::DlpFilesController> files_controller_; + std::unique_ptr<testing::StrictMock<policy::MockDlpFilesControllerAsh>> + files_controller_; }; INSTANTIATE_TEST_SUITE_P( @@ -144,23 +111,23 @@ request.mutable_file_metadata()->set_source_url(kExampleUrl); policy::DlpRulesManager::Level level = GetParam(); - EXPECT_CALL(*mock_rules_manager_, IsRestrictedByAnyRule) - .WillOnce(testing::DoAll(testing::SetArgPointee<2>(kExampleUrl), - testing::Return(level))); + bool is_restricted = + (level == policy::DlpRulesManager::Level::kBlock) ? true : false; - EXPECT_CALL(*mock_rules_manager_, GetDlpFilesController()) - .WillRepeatedly(::testing::Return(files_controller_.get())); - - EXPECT_CALL(*mock_rules_manager_, GetReportingManager()) - .WillRepeatedly(::testing::Return(nullptr)); - + FileDaemonInfo file_info( + /*inode=*/kInode, + /*crtime=*/0, + /*path=*/base::FilePath(), + /*source_url=*/kExampleUrl, + /*referrer_url=*/""); + EXPECT_CALL(*files_controller_.get(), IsDlpPolicyMatched(file_info)) + .WillOnce(testing::Return(is_restricted)); auto response = CallDlpFilesPolicyServiceMethod<dlp::IsDlpPolicyMatchedResponse>( dlp::kDlpFilesPolicyServiceIsDlpPolicyMatchedMethod, request); ASSERT_TRUE(response.has_value()); ASSERT_TRUE(response->has_restricted()); - EXPECT_EQ(response->restricted(), - (level == policy::DlpRulesManager::Level::kBlock)); + EXPECT_EQ(response->restricted(), (is_restricted)); } TEST_P(DlpFilesPolicyServiceProviderTest, IsFilesTransferRestricted) { @@ -170,28 +137,43 @@ file->set_source_url(kExampleUrl2); file->set_inode(kInode); file->set_path(kFilePath); - request.set_file_action(::dlp::FileAction::COPY); + request.set_file_action(::dlp::FileAction::OPEN); request.set_io_task_id(1234); policy::DlpRulesManager::Level level = GetParam(); + auto restriction_level = (level == policy::DlpRulesManager::Level::kBlock) + ? ::dlp::RestrictionLevel::LEVEL_BLOCK + : ::dlp::RestrictionLevel::LEVEL_ALLOW; + FileDaemonInfo file_info( + /*inode=*/kInode, + /*crtime=*/0, + /*path=*/base::FilePath(kFilePath), + /*source_url=*/kExampleUrl2, + /*referrer_url=*/""); EXPECT_CALL( - *mock_rules_manager_, - IsRestrictedDestination(GURL(kExampleUrl2), GURL(kExampleUrl), - policy::DlpRulesManager::Restriction::kFiles, - testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(level)); - - EXPECT_CALL(*mock_rules_manager_, GetDlpFilesController()) - .WillRepeatedly(::testing::Return(files_controller_.get())); - - EXPECT_CALL(*mock_rules_manager_, GetReportingManager()) - .WillRepeatedly(::testing::Return(nullptr)); + *files_controller_.get(), + IsFilesTransferRestricted( + absl::optional<file_manager::io_task::IOTaskId>(1234), + std::vector<FileDaemonInfo>{file_info}, + policy::DlpFileDestination(GURL(kExampleUrl)), + policy::dlp::FileAction::kOpen, base::test::IsNotNullCallback())) + .WillOnce(testing::WithArg<4>( + [&restriction_level, &file_info]( + policy::DlpFilesControllerAsh::IsFilesTransferRestrictedCallback + result_callback) { + std::vector<std::pair<FileDaemonInfo, ::dlp::RestrictionLevel>> + result; + result.push_back(std::make_pair(file_info, restriction_level)); + std::move(result_callback).Run(std::move(result)); + })); auto response = CallDlpFilesPolicyServiceMethod<dlp::IsFilesTransferRestrictedResponse>( dlp::kDlpFilesPolicyServiceIsFilesTransferRestrictedMethod, request); ASSERT_TRUE(response.has_value()); ASSERT_EQ(response->files_restrictions().size(), 1); + EXPECT_EQ(response->files_restrictions()[0].restriction_level(), + restriction_level); } TEST_P(DlpFilesPolicyServiceProviderTest, IsFilesTransferRestrictedSystem) { @@ -204,13 +186,6 @@ request.set_file_action(::dlp::FileAction::COPY); request.set_io_task_id(1234); - EXPECT_CALL(*mock_rules_manager_, IsRestrictedDestination).Times(0); - - EXPECT_CALL(*mock_rules_manager_, GetDlpFilesController()).Times(0); - - EXPECT_CALL(*mock_rules_manager_, GetReportingManager()) - .WillRepeatedly(::testing::Return(nullptr)); - auto response = CallDlpFilesPolicyServiceMethod<dlp::IsFilesTransferRestrictedResponse>( dlp::kDlpFilesPolicyServiceIsFilesTransferRestrictedMethod, request);
diff --git a/chrome/browser/ash/drive/file_system_util.cc b/chrome/browser/ash/drive/file_system_util.cc index 4546f89..77da20aa 100644 --- a/chrome/browser/ash/drive/file_system_util.cc +++ b/chrome/browser/ash/drive/file_system_util.cc
@@ -28,7 +28,6 @@ #include "chromeos/ash/components/login/login_state/login_state.h" #include "components/drive/drive_pref_names.h" #include "components/prefs/pref_service.h" -#include "components/sync/base/command_line_switches.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "components/version_info/version_info.h"
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc index db97341f..19ab344a 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc
@@ -186,11 +186,15 @@ } void CopyOrMoveIOTaskPolicyImpl::MaybeSendConnectorsBlockedFilesNotification() { - bool connectors_new_ui_enabled = base::FeatureList::IsEnabled( - features::kFileTransferEnterpriseConnectorUI); - if (!connectors_new_ui_enabled || connectors_blocked_files_.empty()) { + if (connectors_blocked_files_.empty()) { return; } + + // Blocked files are only added if kFileTransferEnterpriseConnectorUI is + // enabled. + CHECK(base::FeatureList::IsEnabled( + features::kFileTransferEnterpriseConnectorUI)); + auto* files_policy_manager = policy::FilesPolicyNotificationManagerFactory::GetForBrowserContext( profile_); @@ -206,12 +210,11 @@ } void CopyOrMoveIOTaskPolicyImpl::Complete(State state) { - if (blocked_files_ > 0) { - // It doesn't matter here which policy error we set because the panel - // strings in the files app are the same for all of them. - + if (blocked_files_ > 0 && + base::FeatureList::IsEnabled(features::kNewFilesPolicyUX)) { bool has_dlp_errors = connectors_blocked_files_.size() < blocked_files_; bool has_connector_errors = !connectors_blocked_files_.empty(); + CHECK(has_dlp_errors || has_connector_errors); // TODO(b/293425493): Support combined error type (if both dlp and connector // errors exist). @@ -429,8 +432,12 @@ result == enterprise_connectors::FileTransferAnalysisDelegate::RESULT_BLOCKED); - blocked_files_++; - connectors_blocked_files_.push_back(source_url.path()); + if (base::FeatureList::IsEnabled( + features::kFileTransferEnterpriseConnectorUI)) { + blocked_files_++; + connectors_blocked_files_.push_back(source_url.path()); + } + std::move(callback).Run(base::File::FILE_ERROR_SECURITY); }
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc index 033360d0..047cf58 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc
@@ -133,21 +133,29 @@ } // namespace class CopyOrMoveIOTaskWithScansTest - : public testing::TestWithParam< - std::tuple<OperationType, /*use_new_ui*/ bool>> { + : public testing::TestWithParam<std::tuple<OperationType, + /*new_policy_ux*/ bool, + /*new_file_transfer_ux*/ bool>> { public: static std::string ParamToString( const ::testing::TestParamInfo<ParamType>& info) { - auto [operation_type, use_new_ui] = info.param; + auto [operation_type, new_policy_ux, new_file_transfer_ux] = info.param; std::string name; name += operation_type == OperationType::kCopy ? "Copy" : "Move"; - name += use_new_ui ? "NewUI" : ""; + if (new_policy_ux) { + name += "PolicyUX"; + } + if (new_file_transfer_ux) { + name += "ConnectorsUX"; + } return name; } protected: OperationType GetOperationType() { return std::get<0>(GetParam()); } - bool UseNewUI() { return std::get<1>(GetParam()); } + + bool UseNewPolicyUI() { return std::get<1>(GetParam()); } + bool UseNewConnectorsUI() { return std::get<2>(GetParam()); } void SetUp() override { profile_manager_ = std::make_unique<TestingProfileManager>( @@ -155,17 +163,24 @@ ASSERT_TRUE(profile_manager_->SetUp()); profile_ = profile_manager_->CreateTestingProfile("test-profile"); - if (UseNewUI()) { - scoped_feature_list_.InitWithFeatures( - {features::kFileTransferEnterpriseConnector, - features::kFileTransferEnterpriseConnectorUI}, - {}); + std::vector<base::test::FeatureRef> enabled_features{ + features::kFileTransferEnterpriseConnector}; + std::vector<base::test::FeatureRef> disabled_features; + + if (UseNewPolicyUI()) { + enabled_features.push_back(features::kNewFilesPolicyUX); } else { - scoped_feature_list_.InitWithFeatures( - {features::kFileTransferEnterpriseConnector}, - {features::kFileTransferEnterpriseConnectorUI}); + disabled_features.push_back(features::kNewFilesPolicyUX); } + if (UseNewConnectorsUI()) { + enabled_features.push_back(features::kFileTransferEnterpriseConnectorUI); + } else { + disabled_features.push_back(features::kFileTransferEnterpriseConnectorUI); + } + + scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); + // Set a device management token. It is required to enable scanning. // Without it, FileTransferAnalysisDelegate::IsEnabled() always // returns absl::nullopt. @@ -210,7 +225,7 @@ base::BindRepeating(&CopyOrMoveIOTaskWithScansTest::SetupMock, base::Unretained(this)))); - if (UseNewUI()) { + if (UseNewConnectorsUI() || UseNewPolicyUI()) { // Set FilesPolicyNotificationManager. policy::FilesPolicyNotificationManagerFactory::GetInstance() ->SetTestingFactory( @@ -253,7 +268,7 @@ .WillOnce( [](base::OnceClosure callback) { std::move(callback).Run(); }); - if (UseNewUI()) { + if (UseNewConnectorsUI()) { if (warned_files_.count(source_url) != 0) { EXPECT_CALL(*delegate, GetWarnedFiles()) .WillOnce( @@ -279,7 +294,7 @@ [](base::OnceClosure callback) { std::move(callback).Run(); }); // Setup warned files call if the new UI is used. - if (UseNewUI()) { + if (UseNewConnectorsUI()) { std::vector<storage::FileSystemURL> warned_files; for (auto&& warned_file : warned_files_) { // Note: We're using IsParent here, so this doesn't support recursive @@ -675,21 +690,25 @@ policy::OnDlpRestrictionCheckedCallback warning_callback_; }; -INSTANTIATE_TEST_SUITE_P(CopyOrMove, - CopyOrMoveIOTaskWithScansTest, - testing::Combine(testing::Values(OperationType::kCopy, - OperationType::kMove), - testing::Bool()), - &CopyOrMoveIOTaskWithScansTest::ParamToString); +INSTANTIATE_TEST_SUITE_P( + CopyOrMove, + CopyOrMoveIOTaskWithScansTest, + testing::Combine(testing::Values(OperationType::kCopy, + OperationType::kMove), + /*new_policy_ux*/ testing::Bool(), + /*new_file_transfer_ux*/ testing::Bool()), + &CopyOrMoveIOTaskWithScansTest::ParamToString); using CopyOrMoveIOTaskWithScansWarnTest = CopyOrMoveIOTaskWithScansTest; -INSTANTIATE_TEST_SUITE_P(CopyOrMove, - CopyOrMoveIOTaskWithScansWarnTest, - testing::Combine(testing::Values(OperationType::kCopy, - OperationType::kMove), - /*use_new_ui=*/testing::Values(true)), - &CopyOrMoveIOTaskWithScansTest::ParamToString); +INSTANTIATE_TEST_SUITE_P( + CopyOrMove, + CopyOrMoveIOTaskWithScansWarnTest, + testing::Combine(testing::Values(OperationType::kCopy, + OperationType::kMove), + /*new_policy_ux*/ testing::Bool(), + /*new_file_transfer_ux*/ testing::Values(true)), + &CopyOrMoveIOTaskWithScansTest::ParamToString); TEST_P(CopyOrMoveIOTaskWithScansTest, BlockSingleFileUsingResultBlocked) { // Create file. @@ -714,9 +733,12 @@ complete_callback, {file}, dest, {base::File::FILE_ERROR_SECURITY}, run_loop.QuitClosure(), /*maybe_total_num_files=*/absl::nullopt, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)); + UseNewPolicyUI() && UseNewConnectorsUI() + ? absl::make_optional( + PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)) + : absl::nullopt); - if (UseNewUI()) { + if (UseNewPolicyUI() && UseNewConnectorsUI()) { ExpectFPNMBlockedFiles({file}); } @@ -754,9 +776,12 @@ complete_callback, {file}, dest, {base::File::FILE_ERROR_SECURITY}, run_loop.QuitClosure(), /*maybe_total_num_files=*/absl::nullopt, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)); + UseNewPolicyUI() && UseNewConnectorsUI() + ? absl::make_optional( + PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)) + : absl::nullopt); - if (UseNewUI()) { + if (UseNewPolicyUI() && UseNewConnectorsUI()) { ExpectFPNMBlockedFiles({file}); } @@ -942,9 +967,12 @@ {base::File::FILE_ERROR_SECURITY, base::File::FILE_OK}, run_loop.QuitClosure(), /*maybe_total_num_files=*/absl::nullopt, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)); + UseNewPolicyUI() && UseNewConnectorsUI() + ? absl::make_optional( + PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)) + : absl::nullopt); - if (UseNewUI()) { + if (UseNewPolicyUI() && UseNewConnectorsUI()) { ExpectFPNMBlockedFiles({enabled_file}); } @@ -1006,9 +1034,12 @@ run_loop.QuitClosure(), /*maybe_total_num_files=*/2, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 2)); + UseNewPolicyUI() && UseNewConnectorsUI() + ? absl::make_optional( + PolicyError(PolicyErrorType::kEnterpriseConnectors, 2)) + : absl::nullopt); - if (UseNewUI()) { + if (UseNewPolicyUI() && UseNewConnectorsUI()) { ExpectFPNMBlockedFiles({file1, file0}); } @@ -1070,9 +1101,12 @@ run_loop.QuitClosure(), /*maybe_total_num_files=*/2, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)); + UseNewPolicyUI() && UseNewConnectorsUI() + ? absl::make_optional( + PolicyError(PolicyErrorType::kEnterpriseConnectors, 1)) + : absl::nullopt); - if (UseNewUI()) { + if (UseNewPolicyUI() && UseNewConnectorsUI()) { ExpectFPNMBlockedFiles({file0}); } @@ -1093,6 +1127,9 @@ TEST_P(CopyOrMoveIOTaskWithScansWarnTest, DirectoryTransferBlockSomeWarnSomeProceed) { + // This test can only work for UseNewConnectorsUI() == true. + ASSERT_TRUE(UseNewConnectorsUI()); + // Create directory. FileInfo directory{"", GetSourceFileSystemURLForEnabledVolume("folder"), GetDestinationFileSystemURL("folder")}; @@ -1163,7 +1200,9 @@ run_loop.QuitClosure(), /*maybe_total_num_files=*/6, /*maybe_policy_error=*/ - PolicyError(PolicyErrorType::kEnterpriseConnectors, 2)); + UseNewPolicyUI() ? absl::make_optional(PolicyError( + PolicyErrorType::kEnterpriseConnectors, 2)) + : absl::nullopt); // Start the copy/move. CopyOrMoveIOTask task(GetOperationType(), @@ -1173,7 +1212,10 @@ // Expect a warning dialog and error dialog about the blocked files ExpectFPNMFilesWarningDialogAndProceed(task); - ExpectFPNMBlockedFiles({blocked_file_0, blocked_file_1}); + + if (UseNewPolicyUI()) { + ExpectFPNMBlockedFiles({blocked_file_0, blocked_file_1}); + } task.Execute(progress_callback.Get(), complete_callback.Get()); // Wait for the copy/move to be completed.
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest.cc b/chrome/browser/ash/file_manager/file_manager_browsertest.cc index 1d6031bf..983c2bf 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/ash/file_manager/file_manager_browsertest.cc
@@ -1468,7 +1468,10 @@ TestCase("checkGoToFileLocationEnabledInRecents"), TestCase("checkGoToFileLocationDisabledInMultipleSelection"), TestCase("checkDefaultTask"), - TestCase("checkPolicyAssignedDefaultHasManagedIcon"))); + TestCase("checkPolicyAssignedDefaultHasManagedIcon"), + TestCase("checkEncryptedCopyDisabled"), + TestCase("checkEncryptedCrossVolumeMoveDisabled"), + TestCase("checkEncryptedMoveEnabled"))); WRAPPED_INSTANTIATE_TEST_SUITE_P( Toolbar, /* toolbar.js */ @@ -1879,7 +1882,10 @@ TestCase("fileTasksDlpRestricted").EnableDlp(), TestCase("zipExtractRestrictedArchiveCheckContent").EnableDlp(), TestCase("blockShowsPanelItem").EnableDlp().EnableFilesPolicyNewUX(), - TestCase("warnShowsPanelItem").EnableDlp().EnableFilesPolicyNewUX())); + TestCase("warnShowsPanelItem").EnableDlp().EnableFilesPolicyNewUX(), + TestCase("mixedSummaryDisplayPanel") + .EnableDlp() + .EnableFilesPolicyNewUX())); WRAPPED_INSTANTIATE_TEST_SUITE_P( DriveSpecific, /* drive_specific.js */
diff --git a/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc b/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc index 7102623..42af07c5 100644 --- a/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc +++ b/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc
@@ -14,16 +14,24 @@ #include "base/strings/strcat.h" #include "base/test/gmock_callback_support.h" #include "base/test/mock_callback.h" +#include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "base/time/time_to_iso8601.h" #include "chrome/browser/ash/file_manager/io_task.h" #include "chrome/browser/ash/file_manager/trash_common_util.h" #include "chrome/browser/ash/file_manager/trash_unittest_base.h" +#include "chrome/browser/ash/file_manager/volume_manager.h" +#include "chrome/browser/ash/policy/dlp/files_policy_notification_manager.h" +#include "chrome/browser/ash/policy/dlp/test/mock_dlp_files_controller_ash.h" +#include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_factory.h" +#include "chrome/browser/chromeos/policy/dlp/test/mock_dlp_rules_manager.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/common/chrome_features.h" #include "chromeos/ash/components/trash_service/public/cpp/trash_service.h" #include "chromeos/ash/components/trash_service/public/mojom/trash_service.mojom-forward.h" #include "chromeos/ash/components/trash_service/trash_service_impl.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "storage/browser/file_system/file_system_url.h" #include "storage/common/file_system/file_system_types.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -54,8 +62,53 @@ base::BindRepeating( &RestoreToDestinationIOTaskTest::CreateInProcessTrashService, base::Unretained(this))); + + // Setup the destination directory where the files will be restored to. + destination_path_ = temp_dir_.GetPath().Append("dest_folder"); + ASSERT_TRUE(base::CreateDirectory(destination_path_)); } + // Writes `contents` to `file` in the trash directory and sets up required + // trash info based on `restore_file_name`. Returns the FilePath of the + // .trashinfo file. + base::FilePath WriteFileInTrash(const std::string& file_name, + const std::string& restore_file_name, + const std::string& contents) { + std::string foo_metadata_contents = + GenerateTrashInfoContents(restore_file_name); + const base::FilePath trash_path = + downloads_dir_.Append(trash::kTrashFolderName); + const base::FilePath info_file_path = + trash_path.Append(trash::kInfoFolderName) + .Append(base::StrCat({file_name, ".trashinfo"})); + CHECK(base::WriteFile(info_file_path, foo_metadata_contents)); + + const base::FilePath files_path = + trash_path.Append(trash::kFilesFolderName).Append(file_name); + CHECK(base::WriteFile(files_path, contents)); + + return files_path; + } + + // Returns the restore destination URL. + storage::FileSystemURL GetDestination() { + return file_system_context_->CreateCrackedFileSystemURL( + kTestStorageKey, storage::kFileSystemTypeTest, + destination_path_.BaseName()); + } + + // Verifies that the `file` is restored to the `destination_path_` and that + // its contents match `expected_contents`. + void VerifyRestoredFile(const std::string& file, + const std::string& expected_contents) { + auto file_path = destination_path_.Append(file); + EXPECT_TRUE(base::PathExists(file_path)); + std::string contents; + EXPECT_TRUE(base::ReadFileToString(file_path, &contents)); + EXPECT_EQ(expected_contents, contents); + } + + private: mojo::PendingRemote<ash::trash_service::mojom::TrashService> CreateInProcessTrashService() { mojo::PendingRemote<ash::trash_service::mojom::TrashService> remote; @@ -65,47 +118,34 @@ return remote; } - std::string GenerateTrashInfoContents(const std::string& restore_path) { - return base::StrCat({"[Trash Info]\nPath=", restore_path, "\nDeletionDate=", - base::TimeToISO8601(base::Time::UnixEpoch())}); + std::string GenerateTrashInfoContents(const std::string& restore_file) { + return base::StrCat( + {"[Trash Info]\nPath=", "/Downloads/bar/", restore_file, + "\nDeletionDate=", base::TimeToISO8601(base::Time::UnixEpoch())}); } - private: // Maintains ownership of the in-process parsing service. std::unique_ptr<ash::trash_service::TrashServiceImpl> trash_service_impl_; + // Directory where the files will be restored to. + base::FilePath destination_path_; }; TEST_F(RestoreToDestinationIOTaskTest, RestorePathWithDifferentNameInTrashInfoSucceeds) { EnsureTrashDirectorySetup(downloads_dir_); - // Setup the destination directory where the file will be restored to. - base::FilePath destination_path = temp_dir_.GetPath().Append("dest_folder"); - ASSERT_TRUE(base::CreateDirectory(destination_path)); - + const std::string file_name = "foo.txt"; + const std::string restore_file_name = "baz.txt"; // Setup the contents for files in the Trash directory. - std::string foo_contents = base::RandBytesAsString(kTestFileSize); - std::string foo_metadata_contents = - GenerateTrashInfoContents("/Downloads/bar/baz.txt"); - - // Write contents to the files in the trash directory. - const base::FilePath trash_path = - downloads_dir_.Append(trash::kTrashFolderName); + const std::string foo_contents = base::RandBytesAsString(kTestFileSize); const base::FilePath info_file_path = - trash_path.Append(trash::kInfoFolderName).Append("foo.txt.trashinfo"); - ASSERT_TRUE(base::WriteFile(info_file_path, foo_metadata_contents)); - const base::FilePath files_path = - trash_path.Append(trash::kFilesFolderName).Append("foo.txt"); - ASSERT_TRUE(base::WriteFile(files_path, foo_contents)); + WriteFileInTrash(file_name, restore_file_name, foo_contents); // Setup source and destination locations. base::RunLoop run_loop; std::vector<storage::FileSystemURL> source_urls = { CreateFileSystemURL(info_file_path), }; - auto dest = file_system_context_->CreateCrackedFileSystemURL( - kTestStorageKey, storage::kFileSystemTypeTest, - destination_path.BaseName()); base::MockRepeatingCallback<void(const ProgressStatus&)> progress_callback; base::MockOnceCallback<void(ProgressStatus)> complete_callback; @@ -115,7 +155,7 @@ Run(Field(&ProgressStatus::state, State::kSuccess))) .WillOnce(RunClosure(run_loop.QuitClosure())); - RestoreToDestinationIOTask task(source_urls, dest, profile_.get(), + RestoreToDestinationIOTask task(source_urls, GetDestination(), profile_.get(), file_system_context_, temp_dir_.GetPath(), /*show_notification=*/true); task.Execute(progress_callback.Get(), complete_callback.Get()); @@ -126,58 +166,34 @@ EXPECT_EQ(task.progress().task_id, task.GetMoveTaskForTesting()->progress().task_id); - EXPECT_TRUE(base::PathExists(destination_path.Append("baz.txt"))); - std::string contents; - ASSERT_TRUE( - base::ReadFileToString(destination_path.Append("baz.txt"), &contents)); - EXPECT_EQ(foo_contents, contents); + VerifyRestoredFile(restore_file_name, foo_contents); } TEST_F(RestoreToDestinationIOTaskTest, PauseAndResume) { EnsureTrashDirectorySetup(downloads_dir_); - // Setup the destination directory where the file will be restored to. - base::FilePath destination_path = temp_dir_.GetPath().Append("dest_folder"); - ASSERT_TRUE(base::CreateDirectory(destination_path)); - + const std::string file_name_1 = "foo1.txt"; + const std::string file_name_2 = "foo2.txt"; + const std::string restore_file_name_1 = "baz1.txt"; + const std::string restore_file_name_2 = "baz2.txt"; // Setup the contents for files in the Trash directory. std::string foo_contents = base::RandBytesAsString(kTestFileSize); - std::string foo_metadata_contents_1 = - GenerateTrashInfoContents("/Downloads/bar/baz1.txt"); - std::string foo_metadata_contents_2 = - GenerateTrashInfoContents("/Downloads/bar/baz2.txt"); - - // Write contents to the files in the trash directory. - const base::FilePath trash_path = - downloads_dir_.Append(trash::kTrashFolderName); - const base::FilePath file_1 = - trash_path.Append(trash::kInfoFolderName).Append("foo1.txt.trashinfo"); - ASSERT_TRUE(base::WriteFile(file_1, foo_metadata_contents_1)); - const base::FilePath path_1 = - trash_path.Append(trash::kFilesFolderName).Append("foo1.txt"); - ASSERT_TRUE(base::WriteFile(path_1, foo_contents)); - - const base::FilePath file_2 = - trash_path.Append(trash::kInfoFolderName).Append("foo2.txt.trashinfo"); - ASSERT_TRUE(base::WriteFile(file_2, foo_metadata_contents_2)); - const base::FilePath path_2 = - trash_path.Append(trash::kFilesFolderName).Append("foo2.txt"); - ASSERT_TRUE(base::WriteFile(path_2, foo_contents)); + const base::FilePath info_file_path_1 = + WriteFileInTrash(file_name_1, restore_file_name_1, foo_contents); + const base::FilePath info_file_path_2 = + WriteFileInTrash(file_name_2, restore_file_name_2, foo_contents); // Setup source and destination locations. base::RunLoop run_loop; std::vector<storage::FileSystemURL> source_urls = { - CreateFileSystemURL(file_1), - CreateFileSystemURL(file_2), + CreateFileSystemURL(info_file_path_1), + CreateFileSystemURL(info_file_path_2), }; - auto dest = file_system_context_->CreateCrackedFileSystemURL( - kTestStorageKey, storage::kFileSystemTypeTest, - destination_path.BaseName()); base::MockRepeatingCallback<void(const ProgressStatus&)> progress_callback; base::MockOnceCallback<void(ProgressStatus)> complete_callback; - RestoreToDestinationIOTask task(source_urls, dest, profile_.get(), + RestoreToDestinationIOTask task(source_urls, GetDestination(), profile_.get(), file_system_context_, temp_dir_.GetPath(), /*show_notification=*/true); @@ -209,17 +225,151 @@ task.Execute(progress_callback.Get(), complete_callback.Get()); run_loop.Run(); - EXPECT_TRUE(base::PathExists(destination_path.Append("baz1.txt"))); - std::string contents; - ASSERT_TRUE( - base::ReadFileToString(destination_path.Append("baz1.txt"), &contents)); - EXPECT_EQ(foo_contents, contents); + VerifyRestoredFile(restore_file_name_1, foo_contents); + VerifyRestoredFile(restore_file_name_2, foo_contents); +} - EXPECT_TRUE(base::PathExists(destination_path.Append("baz2.txt"))); - std::string contents2; - ASSERT_TRUE( - base::ReadFileToString(destination_path.Append("baz2.txt"), &contents2)); - EXPECT_EQ(foo_contents, contents2); +// Tests RestoreToDestinationIOTasks with DLP enabled. +class RestoreToDestinationIOTaskWithDLPTest + : public RestoreToDestinationIOTaskTest { + public: + RestoreToDestinationIOTaskWithDLPTest() = default; + + RestoreToDestinationIOTaskWithDLPTest( + const RestoreToDestinationIOTaskWithDLPTest&) = delete; + RestoreToDestinationIOTaskWithDLPTest& operator=( + const RestoreToDestinationIOTaskWithDLPTest&) = delete; + + void SetUp() override { + RestoreToDestinationIOTaskTest::SetUp(); + + // Setup IOTaskController. Needed for FPNM to control the IO tasks. + file_manager::VolumeManager* const volume_manager = + file_manager::VolumeManager::Get(profile_.get()); + ASSERT_TRUE(volume_manager); + io_task_controller_ = volume_manager->io_task_controller(); + ASSERT_TRUE(io_task_controller_); + + // Setup DLP. + scoped_feature_list_.InitAndEnableFeature(features::kNewFilesPolicyUX); + policy::DlpRulesManagerFactory::GetInstance()->SetTestingFactory( + profile_.get(), + base::BindRepeating( + &RestoreToDestinationIOTaskWithDLPTest::SetDlpRulesManager, + base::Unretained(this))); + ASSERT_TRUE(policy::DlpRulesManagerFactory::GetForPrimaryProfile()); + ASSERT_TRUE(mock_rules_manager_); + ASSERT_NE(policy::DlpRulesManagerFactory::GetForPrimaryProfile() + ->GetDlpFilesController(), + nullptr); + + fpnm_ = std::make_unique<policy::FilesPolicyNotificationManager>( + profile_.get()); + } + + void TearDown() override { + io_task_controller_ = nullptr; + mock_rules_manager_ = nullptr; + RestoreToDestinationIOTaskTest::TearDown(); + } + + protected: + std::unique_ptr<policy::MockDlpFilesControllerAsh> files_controller_; + std::unique_ptr<policy::FilesPolicyNotificationManager> fpnm_; + raw_ptr<file_manager::io_task::IOTaskController, DanglingUntriaged> + io_task_controller_ = nullptr; + + private: + std::unique_ptr<KeyedService> SetDlpRulesManager( + content::BrowserContext* context) { + auto dlp_rules_manager = std::make_unique<policy::MockDlpRulesManager>(); + mock_rules_manager_ = dlp_rules_manager.get(); + EXPECT_CALL(*mock_rules_manager_, IsFilesPolicyEnabled) + .WillRepeatedly(testing::Return(true)); + + files_controller_ = std::make_unique<policy::MockDlpFilesControllerAsh>( + *mock_rules_manager_); + EXPECT_CALL(*mock_rules_manager_, GetDlpFilesController()) + .WillRepeatedly(::testing::Return(files_controller_.get())); + + return dlp_rules_manager; + } + + base::test::ScopedFeatureList scoped_feature_list_; + raw_ptr<policy::MockDlpRulesManager, ExperimentalAsh> mock_rules_manager_ = + nullptr; +}; + +TEST_F(RestoreToDestinationIOTaskWithDLPTest, PauseResume) { + EnsureTrashDirectorySetup(downloads_dir_); + + const std::string file_name = "foo.txt"; + const std::string restore_file_name = "baz.txt"; + // Setup the contents for files in the Trash directory. + const std::string foo_contents = base::RandBytesAsString(kTestFileSize); + const base::FilePath info_file_path = + WriteFileInTrash(file_name, restore_file_name, foo_contents); + + // Setup source and destination locations. + base::RunLoop run_loop; + std::vector<storage::FileSystemURL> source_urls = { + CreateFileSystemURL(info_file_path), + }; + + base::MockRepeatingCallback<void(const ProgressStatus&)> progress_callback; + base::MockOnceCallback<void(ProgressStatus)> complete_callback; + + EXPECT_CALL(progress_callback, + Run(Field(&ProgressStatus::state, State::kPaused))); + // // TODO(b/295887686): Uncomment when fixed. + // EXPECT_CALL(progress_callback, + // Run(Field(&ProgressStatus::state, State::kInProgress))); + EXPECT_CALL(complete_callback, + Run(Field(&ProgressStatus::state, State::kSuccess))) + .WillOnce(RunClosure(run_loop.QuitClosure())); + + auto task_ptr = std::make_unique<RestoreToDestinationIOTask>( + source_urls, GetDestination(), profile_.get(), file_system_context_, + temp_dir_.GetPath(), + /*show_notification=*/true); + auto* task = task_ptr.get(); + + io_task_controller_->Add(std::move(task_ptr)); + ASSERT_TRUE(fpnm_->HasIOTask(task->progress().task_id)); + + // Set the DLP to warn, which pauses the task, and then resume. + EXPECT_CALL(*files_controller_, CheckIfTransferAllowed) + .WillOnce( + ([=](absl::optional<file_manager::io_task::IOTaskId> task_id, + const std::vector<storage::FileSystemURL>& transferred_files, + storage::FileSystemURL destination, bool is_move, + policy::DlpFilesControllerAsh::CheckIfTransferAllowedCallback + result_callback) { + std::vector<base::FilePath> warning_files; + for (const auto& file : transferred_files) { + warning_files.emplace_back(file.path()); + } + fpnm_->ShowDlpWarning( + base::DoNothing(), task_id, std::move(warning_files), + policy::DlpFileDestination(), policy::dlp::FileAction::kMove); + + EXPECT_TRUE(task->progress().IsPaused()); + // Resume. + ResumeParams params; + params.policy_params.emplace(policy::Policy::kDlp); + io_task_controller_->Resume(task_id.value(), std::move(params)); + // Also run the callback with no blocked files, which will actually + // start the transfer and set the correct state. + std::move(result_callback).Run({}); + + // TODO(b/295887686): Uncomment when fixed. + // EXPECT_FALSE(task->progress().IsPaused()); + })); + + task->Execute(progress_callback.Get(), complete_callback.Get()); + run_loop.Run(); + + VerifyRestoredFile(restore_file_name, foo_contents); } } // namespace
diff --git a/chrome/browser/ash/floating_workspace/floating_workspace_service_unittest.cc b/chrome/browser/ash/floating_workspace/floating_workspace_service_unittest.cc index 15340fd4..0b94943 100644 --- a/chrome/browser/ash/floating_workspace/floating_workspace_service_unittest.cc +++ b/chrome/browser/ash/floating_workspace/floating_workspace_service_unittest.cc
@@ -7,7 +7,6 @@ #include "ash/public/cpp/desk_template.h" #include "ash/wm/desks/desk.h" #include "ash/wm/desks/templates/saved_desk_metrics_util.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/raw_ptr.h" #include "base/ranges/algorithm.h"
diff --git a/chrome/browser/ash/input_method/editor_mediator.cc b/chrome/browser/ash/input_method/editor_mediator.cc index f5127fcc..2f586e2 100644 --- a/chrome/browser/ash/input_method/editor_mediator.cc +++ b/chrome/browser/ash/input_method/editor_mediator.cc
@@ -7,6 +7,7 @@ #include "base/check_op.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/ui/webui/ash/mako/mako_ui.h" +#include "ui/base/ime/ash/ime_bridge.h" namespace ash { namespace input_method { @@ -42,6 +43,10 @@ } void EditorMediator::OnFocus(int context_id) { + GetTextFieldContextualInfo( + base::BindOnce(&EditorMediator::OnTextFieldContextualInfoChanged, + weak_ptr_factory_.GetWeakPtr())); + text_actuator_.OnFocus(context_id); } @@ -66,5 +71,11 @@ } } +void EditorMediator::OnTextFieldContextualInfoChanged( + const TextFieldContextualInfo& info) { + editor_switch_.OnInputContextUpdated( + IMEBridge::Get()->GetCurrentInputContext(), info); +} + } // namespace input_method } // namespace ash
diff --git a/chrome/browser/ash/input_method/editor_mediator.h b/chrome/browser/ash/input_method/editor_mediator.h index f500d2b..246e8b3 100644 --- a/chrome/browser/ash/input_method/editor_mediator.h +++ b/chrome/browser/ash/input_method/editor_mediator.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_ASH_INPUT_METHOD_EDITOR_MEDIATOR_H_ #define CHROME_BROWSER_ASH_INPUT_METHOD_EDITOR_MEDIATOR_H_ +#include "base/memory/weak_ptr.h" #include "chrome/browser/ash/input_method/editor_event_sink.h" #include "chrome/browser/ash/input_method/editor_instance_impl.h" #include "chrome/browser/ash/input_method/editor_switch.h" @@ -47,6 +48,8 @@ void CommitEditorResult(std::string_view text) override; private: + void OnTextFieldContextualInfoChanged(const TextFieldContextualInfo& info); + EditorInstanceImpl editor_instance_impl_; EditorTextActuator text_actuator_; EditorSwitch editor_switch_; @@ -54,6 +57,8 @@ // May contain an instance of MakoPageHandler. This is used to control the // lifetime of the Mako WebUI. std::unique_ptr<ash::MakoPageHandler> mako_page_handler_; + + base::WeakPtrFactory<EditorMediator> weak_ptr_factory_{this}; }; } // namespace input_method
diff --git a/chrome/browser/ash/input_method/editor_switch.cc b/chrome/browser/ash/input_method/editor_switch.cc index 3e733ce8..e7f0d95f 100644 --- a/chrome/browser/ash/input_method/editor_switch.cc +++ b/chrome/browser/ash/input_method/editor_switch.cc
@@ -31,6 +31,11 @@ "xkb:us::eng", // US }; +constexpr AppType kAppTypeAllowlist[] = { + AppType::BROWSER, + AppType::LACROS, +}; + bool IsInputTypeAllowed(ui::TextInputType type) { return base::Contains(kTextInputTypeAllowlist, type); } @@ -39,6 +44,10 @@ return base::Contains(kInputMethodEngineAllowlist, engine_id); } +bool IsAppTypeAllowed(AppType app_type) { + return base::Contains(kAppTypeAllowlist, app_type); +} + } // namespace EditorSwitch::EditorSwitch(bool is_managed) { @@ -58,8 +67,10 @@ } void EditorSwitch::OnInputContextUpdated( - const TextInputMethod::InputContext& input_context) { + const TextInputMethod::InputContext& input_context, + const TextFieldContextualInfo& text_field_contextual_info) { input_type_ = input_context.type; + app_type_ = text_field_contextual_info.app_type; UpdateTriggerableCache(); } @@ -69,9 +80,9 @@ } void EditorSwitch::UpdateTriggerableCache() { - can_be_triggered_ = is_allowed_for_use_ && - IsInputMethodEngineAllowed(active_engine_id_) && - IsInputTypeAllowed(input_type_); + can_be_triggered_ = + is_allowed_for_use_ && IsInputMethodEngineAllowed(active_engine_id_) && + IsInputTypeAllowed(input_type_) && IsAppTypeAllowed(app_type_); } } // namespace ash::input_method
diff --git a/chrome/browser/ash/input_method/editor_switch.h b/chrome/browser/ash/input_method/editor_switch.h index 319f6822..5115367 100644 --- a/chrome/browser/ash/input_method/editor_switch.h +++ b/chrome/browser/ash/input_method/editor_switch.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_ASH_INPUT_METHOD_EDITOR_SWITCH_H_ #define CHROME_BROWSER_ASH_INPUT_METHOD_EDITOR_SWITCH_H_ +#include "ash/constants/app_types.h" +#include "chrome/browser/ash/input_method/text_field_contextual_info_fetcher.h" #include "ui/base/ime/ash/text_input_method.h" namespace ash::input_method { @@ -28,7 +30,8 @@ // Handles the change in input context. void OnInputContextUpdated( - const TextInputMethod::InputContext& input_context); + const TextInputMethod::InputContext& input_context, + const TextFieldContextualInfo& text_field_contextual_info); void OnActivateIme(std::string_view engine_id); @@ -40,6 +43,7 @@ std::string active_engine_id_; ui::TextInputType input_type_ = ui::TEXT_INPUT_TYPE_NONE; + ash::AppType app_type_ = ash::AppType::NON_APP; }; } // namespace ash::input_method
diff --git a/chrome/browser/ash/input_method/editor_switch_unittest.cc b/chrome/browser/ash/input_method/editor_switch_unittest.cc index f930748..ba596f98 100644 --- a/chrome/browser/ash/input_method/editor_switch_unittest.cc +++ b/chrome/browser/ash/input_method/editor_switch_unittest.cc
@@ -15,6 +15,13 @@ namespace ash::input_method { namespace { +TextFieldContextualInfo CreateFakeTextFieldContextualInfo( + ash::AppType app_type) { + auto text_field_contextual_info = TextFieldContextualInfo(); + text_field_contextual_info.app_type = app_type; + return text_field_contextual_info; +} + class EditorSwitchTest : public ::testing::Test { public: EditorSwitchTest() = default; @@ -61,7 +68,8 @@ editor_switch.OnActivateIme("nacl_mozc_jp"); editor_switch.OnInputContextUpdated( - TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_PASSWORD)); + TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_PASSWORD), + CreateFakeTextFieldContextualInfo(AppType::BROWSER)); EXPECT_TRUE(editor_switch.IsAllowedForUse()); EXPECT_FALSE(editor_switch.CanBeTriggered()); @@ -76,14 +84,14 @@ editorSwitch.OnActivateIme("nacl_mozc_jp"); editorSwitch.OnInputContextUpdated( - TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_TEXT)); + TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_TEXT), + CreateFakeTextFieldContextualInfo(AppType::BROWSER)); EXPECT_TRUE(editorSwitch.IsAllowedForUse()); EXPECT_FALSE(editorSwitch.CanBeTriggered()); } -TEST_F(EditorSwitchTest, - FeatureCanBeTriggeredOnANormalTextFieldAndWithEnglishInputMethod) { +TEST_F(EditorSwitchTest, FeatureCanNotBeTriggeredOnArcApps) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{chromeos::features::kOrca}, @@ -92,7 +100,26 @@ EditorSwitch editorSwitch(/*is_managed=*/false); editorSwitch.OnActivateIme("xkb:us::eng"); editorSwitch.OnInputContextUpdated( - TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_TEXT)); + TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_TEXT), + CreateFakeTextFieldContextualInfo(AppType::ARC_APP)); + + EXPECT_TRUE(editorSwitch.IsAllowedForUse()); + EXPECT_FALSE(editorSwitch.CanBeTriggered()); +} + +TEST_F( + EditorSwitchTest, + FeatureCanBeTriggeredOnANormalTextFieldOnABrowserWindowAndWithEnglishInputMethod) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + /*enabled_features=*/{chromeos::features::kOrca}, + /*disabled_features=*/{}); + + EditorSwitch editorSwitch(/*is_managed=*/false); + editorSwitch.OnActivateIme("xkb:us::eng"); + editorSwitch.OnInputContextUpdated( + TextInputMethod::InputContext(ui::TEXT_INPUT_TYPE_TEXT), + CreateFakeTextFieldContextualInfo(AppType::BROWSER)); EXPECT_TRUE(editorSwitch.IsAllowedForUse()); EXPECT_TRUE(editorSwitch.CanBeTriggered());
diff --git a/chrome/browser/ash/login/screens/gaia_screen.cc b/chrome/browser/ash/login/screens/gaia_screen.cc index 4ce776c7..81765a0d 100644 --- a/chrome/browser/ash/login/screens/gaia_screen.cc +++ b/chrome/browser/ash/login/screens/gaia_screen.cc
@@ -63,7 +63,7 @@ } bool ShouldUseReauthEndpoint(const AccountId& account_id) { - if (account_id.empty()) { + if (!account_id.is_valid()) { return false; } auto* user = user_manager::UserManager::Get()->FindUser(account_id); @@ -72,13 +72,16 @@ if (user && user->IsChild()) { return true; } - // Use reauth endpoint for potential recovery use cases (exclude cases where - // reauth enforced by policy). - if (features::IsGaiaReauthEndpointEnabled() && - ShouldPrepareForRecovery(account_id)) { - return true; + + // Do not use the reauth endpoint when non-Gaia authentication (SAML) is used. + // This is to ensure the "Enter Google Account Info" button on the SAML screen + // uses an endpoint that allows changing of email address. + if (GaiaScreenHandler::GetGaiaScreenMode(account_id.GetUserEmail()) != + GaiaScreenHandler::GaiaScreenMode::GAIA_SCREEN_MODE_DEFAULT) { + return false; } - return false; + + return features::IsGaiaReauthEndpointEnabled(); } } // namespace
diff --git a/chrome/browser/ash/policy/core/device_local_account_browsertest.cc b/chrome/browser/ash/policy/core/device_local_account_browsertest.cc index 7ec1c8c..e092e4d 100644 --- a/chrome/browser/ash/policy/core/device_local_account_browsertest.cc +++ b/chrome/browser/ash/policy/core/device_local_account_browsertest.cc
@@ -22,7 +22,6 @@ #include "ash/shell.h" #include "ash/system/session/logout_confirmation_controller.h" #include "ash/system/session/logout_confirmation_dialog.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h"
diff --git a/chrome/browser/ash/policy/dlp/files_policy_notification_manager.cc b/chrome/browser/ash/policy/dlp/files_policy_notification_manager.cc index 0fb923a..b3deed8 100644 --- a/chrome/browser/ash/policy/dlp/files_policy_notification_manager.cc +++ b/chrome/browser/ash/policy/dlp/files_policy_notification_manager.cc
@@ -904,12 +904,15 @@ void FilesPolicyNotificationManager::OnIOTaskStatus( const file_manager::io_task::ProgressStatus& status) { - // Observe only Copy and Move tasks. + // Observe only Copy, Move, and RestoreToDestination tasks. if (status.type != file_manager::io_task::OperationType::kCopy && - status.type != file_manager::io_task::OperationType::kMove) { + status.type != file_manager::io_task::OperationType::kMove && + status.type != + file_manager::io_task::OperationType::kRestoreToDestination) { return; } - + // RestoreToDestination have an underlying Move task, so we show the same UI + // as for Move. dlp::FileAction action = status.type == file_manager::io_task::OperationType::kCopy ? dlp::FileAction::kCopy
diff --git a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_periodic_collector.h b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_periodic_collector.h index 0aefa40..a1da12f 100644 --- a/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_periodic_collector.h +++ b/chrome/browser/ash/policy/reporting/metrics_reporting/apps/app_usage_telemetry_periodic_collector.h
@@ -7,7 +7,7 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/sequence_checker.h" #include "base/thread_annotations.h" #include "chromeos/ash/components/login/session/session_termination_manager.h"
diff --git a/chrome/browser/ash/policy/test_support/remote_commands_service_mixin.h b/chrome/browser/ash/policy/test_support/remote_commands_service_mixin.h index fca614c6..32df39f 100644 --- a/chrome/browser/ash/policy/test_support/remote_commands_service_mixin.h +++ b/chrome/browser/ash/policy/test_support/remote_commands_service_mixin.h
@@ -7,8 +7,8 @@ #include <cstdint> -#include "base/allocator/partition_allocator/pointers/raw_ref.h" #include "base/check_deref.h" +#include "base/memory/raw_ref.h" #include "chrome/test/base/mixin_based_in_process_browser_test.h" #include "components/policy/proto/device_management_backend.pb.h"
diff --git a/chrome/browser/ash/sync/DIR_METADATA b/chrome/browser/ash/sync/DIR_METADATA new file mode 100644 index 0000000..4a58e65 --- /dev/null +++ b/chrome/browser/ash/sync/DIR_METADATA
@@ -0,0 +1 @@ +mixins: "//components/sync/COMMON_METADATA"
diff --git a/chrome/browser/ash/telemetry_extension/routines/self_owned_mojo_proxy.h b/chrome/browser/ash/telemetry_extension/routines/self_owned_mojo_proxy.h index 9939ebc..0e22a65 100644 --- a/chrome/browser/ash/telemetry_extension/routines/self_owned_mojo_proxy.h +++ b/chrome/browser/ash/telemetry_extension/routines/self_owned_mojo_proxy.h
@@ -10,9 +10,9 @@ #include <string> #include <utility> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/memory/raw_ptr.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h"
diff --git a/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.cc b/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.cc index 2dd2808b..022eca30 100644 --- a/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.cc +++ b/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.cc
@@ -7,8 +7,8 @@ #include <memory> #include <utility> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" +#include "base/memory/raw_ptr.h" #include "chrome/browser/ash/telemetry_extension/common/telemetry_extension_converters.h" #include "chrome/browser/ash/telemetry_extension/routines/routine_control.h" #include "chrome/browser/ash/telemetry_extension/routines/routine_converters.h"
diff --git a/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.h b/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.h index b98ee34..1aa06bf 100644 --- a/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.h +++ b/chrome/browser/ash/telemetry_extension/routines/telemetry_diagnostic_routine_service_ash.h
@@ -7,8 +7,8 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/containers/flat_set.h" +#include "base/memory/raw_ptr.h" #include "chrome/browser/ash/telemetry_extension/routines/self_owned_mojo_proxy.h" #include "chromeos/crosapi/mojom/telemetry_diagnostic_routine_service.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h"
diff --git a/chrome/browser/autofill/autofill_autocomplete_browsertest.cc b/chrome/browser/autofill/autofill_autocomplete_browsertest.cc index 6d9d170..41ad3ec6 100644 --- a/chrome/browser/autofill/autofill_autocomplete_browsertest.cc +++ b/chrome/browser/autofill/autofill_autocomplete_browsertest.cc
@@ -206,16 +206,14 @@ void GetAutocompleteSuggestions(const std::string& input_name, const std::string& prefix, MockSuggestionsHandler& handler) { - FormFieldData field; AutofillClient& autofill_client = ContentAutofillDriverFactory::FromWebContents(web_contents()) ->DriverForFrame(web_contents()->GetPrimaryMainFrame()) ->autofill_manager() ->client(); - test::CreateTestFormField(/*label=*/"", input_name.c_str(), prefix.c_str(), - "input", &field); EXPECT_TRUE(autocomplete_history_manager()->OnGetSingleFieldSuggestions( - AutofillSuggestionTriggerSource::kFormControlElementClicked, field, + AutofillSuggestionTriggerSource::kFormControlElementClicked, + test::CreateTestFormField(/*label=*/"", input_name, prefix, "input"), autofill_client, handler.GetWeakPtr(), SuggestionsContext())); // Make sure the DB task gets executed.
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/events/events_api_browsertest.cc b/chrome/browser/chromeos/extensions/telemetry/api/events/events_api_browsertest.cc index ee4229e..f7949da 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/events/events_api_browsertest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/events/events_api_browsertest.cc
@@ -6,8 +6,8 @@ #include <memory> #include <utility> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/location.h" +#include "base/memory/raw_ptr.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_future.h"
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.cc b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.cc index 4035947a..4a24b17 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/notreached.h" #include "base/uuid.h" #include "chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_converters.h"
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.h b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.h index c9931fcc..63c65f083 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.h +++ b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_TELEMETRY_API_ROUTINES_DIAGNOSTIC_ROUTINE_OBSERVATION_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_TELEMETRY_API_ROUTINES_DIAGNOSTIC_ROUTINE_OBSERVATION_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/uuid.h" #include "chromeos/crosapi/mojom/telemetry_diagnostic_routine_service.mojom.h" #include "content/public/browser/browser_context.h"
diff --git a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation_browsertest.cc b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation_browsertest.cc index b8a6856..6d9ff231 100644 --- a/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation_browsertest.cc +++ b/chrome/browser/chromeos/extensions/telemetry/api/routines/diagnostic_routine_observation_browsertest.cc
@@ -7,9 +7,9 @@ #include <memory> #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback.h" #include "base/location.h" +#include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "base/task/single_thread_task_runner.h" #include "base/test/bind.h"
diff --git a/chrome/browser/dips/dips_bounce_detector.cc b/chrome/browser/dips/dips_bounce_detector.cc index 790515cd..8603746 100644 --- a/chrome/browser/dips/dips_bounce_detector.cc +++ b/chrome/browser/dips/dips_bounce_detector.cc
@@ -10,10 +10,10 @@ #include <memory> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/check.h" #include "base/functional/bind.h" #include "base/functional/overloaded.h" +#include "base/memory/raw_ptr.h" #include "base/metrics/histogram_functions.h" #include "base/rand_util.h" #include "base/task/task_traits.h"
diff --git a/chrome/browser/dips/dips_bounce_detector.h b/chrome/browser/dips/dips_bounce_detector.h index d2cea9a..3d2c1f4 100644 --- a/chrome/browser/dips/dips_bounce_detector.h +++ b/chrome/browser/dips/dips_bounce_detector.h
@@ -9,7 +9,6 @@ #include <string> #include <variant> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "base/timer/timer.h"
diff --git a/chrome/browser/dips/dips_browser_signin_detector_unittest.cc b/chrome/browser/dips/dips_browser_signin_detector_unittest.cc index 63bb747..b3ecee9 100644 --- a/chrome/browser/dips/dips_browser_signin_detector_unittest.cc +++ b/chrome/browser/dips/dips_browser_signin_detector_unittest.cc
@@ -9,7 +9,6 @@ #include <memory> #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/files/file_util.h" #include "base/memory/raw_ptr.h" #include "base/strings/strcat.h"
diff --git a/chrome/browser/drive/drive_notification_manager_factory.cc b/chrome/browser/drive/drive_notification_manager_factory.cc index c82bc81c..8e1649b 100644 --- a/chrome/browser/drive/drive_notification_manager_factory.cc +++ b/chrome/browser/drive/drive_notification_manager_factory.cc
@@ -6,7 +6,6 @@ #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/sync_service_factory.h" #include "components/drive/drive_notification_manager.h" #include "components/invalidation/impl/profile_invalidation_provider.h" #include "components/sync/base/command_line_switches.h" @@ -68,7 +67,6 @@ // Guest mode. .WithGuest(ProfileSelection::kOriginalOnly) .Build()) { - DependsOn(SyncServiceFactory::GetInstance()); DependsOn(invalidation::ProfileInvalidationProviderFactory::GetInstance()); }
diff --git a/chrome/browser/enterprise/reporting/reporting_delegate_factory_desktop.h b/chrome/browser/enterprise/reporting/reporting_delegate_factory_desktop.h index 7f920dc..eb57ab3 100644 --- a/chrome/browser/enterprise/reporting/reporting_delegate_factory_desktop.h +++ b/chrome/browser/enterprise/reporting/reporting_delegate_factory_desktop.h
@@ -9,7 +9,7 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "components/enterprise/browser/reporting/browser_report_generator.h" #include "components/enterprise/browser/reporting/profile_report_generator.h" #include "components/enterprise/browser/reporting/real_time_report_controller.h"
diff --git a/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc b/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc index c4cd91c..8aaeda2 100644 --- a/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc +++ b/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc
@@ -6,8 +6,8 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/command_line.h" +#include "base/memory/raw_ptr.h" #include "base/test/metrics/user_action_tester.h" #include "base/values.h" #include "build/build_config.h"
diff --git a/chrome/browser/extensions/chrome_extensions_browser_interface_binders.cc b/chrome/browser/extensions/chrome_extensions_browser_interface_binders.cc index db754a5..852c438d 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_interface_binders.cc +++ b/chrome/browser/extensions/chrome_extensions_browser_interface_binders.cc
@@ -33,6 +33,7 @@ #include "chromeos/ash/components/language_packs/public/mojom/language_packs.mojom.h" #include "chromeos/ash/services/chromebox_for_meetings/public/cpp/appid_util.h" #include "chromeos/ash/services/chromebox_for_meetings/public/mojom/cfm_service_manager.mojom.h" +#include "chromeos/ash/services/chromebox_for_meetings/public/mojom/xu_camera.mojom.h" #include "chromeos/components/remote_apps/mojom/remote_apps.mojom.h" #include "chromeos/services/media_perception/public/mojom/media_perception.mojom.h" #include "chromeos/services/tts/public/mojom/tts_service.mojom.h" @@ -50,6 +51,7 @@ #endif #if BUILDFLAG(PLATFORM_CFM) +#include "chrome/browser/ash/chromebox_for_meetings/xu_camera/xu_camera_service.h" #include "chromeos/ash/components/chromebox_for_meetings/features.h" #include "chromeos/ash/services/chromebox_for_meetings/public/cpp/service_connection.h" #endif @@ -164,42 +166,71 @@ #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) if (ash::cfm::IsChromeboxForMeetingsAppId(extension->id())) { +// The experimentation framework used to manage the +// `ash::cfm::features::kMojoServices` feature flag requires +// Chrome to restart before updates are applied. Meet Devices have +// a variable uptime ranging from a week or more and set by the +// admin. Additionally its kiosked process is not tied to a chromium +// release and can be dynamically updated during Chrome runtime. +// Unfortunately this makes it difficult to fully predict when the +// flag will be applied to all devices across the fleet. +// As such we proactively support the case for devices that may be +// in a different state than expected from the kiosked process. +#if BUILDFLAG(PLATFORM_CFM) binder_map->Add< chromeos::cfm::mojom::CfmServiceContext>(base::BindRepeating( [](content::RenderFrameHost* frame_host, mojo::PendingReceiver<chromeos::cfm::mojom::CfmServiceContext> receiver) { -#if BUILDFLAG(PLATFORM_CFM) if (base::FeatureList::IsEnabled(ash::cfm::features::kMojoServices)) { ash::cfm::ServiceConnection::GetInstance()->BindServiceContext( std::move(receiver)); } else { - // The experimentation framework used to manage the - // `ash::cfm::features::kMojoServices` feature flag requires - // Chrome to restart before updates are applied. Meet Devices have - // a variable uptime ranging from a week or more and set by the - // admin. Additionally its kiosked process is not tied to a chromium - // release and can be dynamically updated during Chrome runtime. - // Unfortunately this makes it difficult to fully predict when the - // flag will be applied to all devices across the fleet. - // As such we proactively support the case for devices that may be - // in a different state than expected from the kiosked process. receiver.ResetWithReason( static_cast<uint32_t>( chromeos::cfm::mojom::DisconnectReason::kFinchDisabledCode), chromeos::cfm::mojom::DisconnectReason::kFinchDisabledMessage); } + })); + binder_map->Add<ash::cfm::mojom::XuCamera>(base::BindRepeating( + [](content::RenderFrameHost* frame_host, + mojo::PendingReceiver<ash::cfm::mojom::XuCamera> receiver) { + if (base::FeatureList::IsEnabled(ash::cfm::features::kXuControls)) { + ash::cfm::XuCameraService::Get()->BindServiceContext( + std::move(receiver), frame_host->GetGlobalId()); + } else { + receiver.ResetWithReason( + static_cast<uint32_t>( + chromeos::cfm::mojom::DisconnectReason::kFinchDisabledCode), + chromeos::cfm::mojom::DisconnectReason::kFinchDisabledMessage); + } + })); + +// On first launch some older devices may be running on none-CfM +// images. For those devices reject all requests until they are +// rebooted to the CfM image variant for their device. #else - // On first launch some older devices may be running on none-CfM - // images. For those devices reject all requests until they are - // rebooted to the CfM image variant for their device. + binder_map->Add< + chromeos::cfm::mojom::CfmServiceContext>(base::BindRepeating( + [](content::RenderFrameHost* frame_host, + mojo::PendingReceiver<chromeos::cfm::mojom::CfmServiceContext> + receiver) { receiver.ResetWithReason( static_cast<uint32_t>(chromeos::cfm::mojom::DisconnectReason:: kServiceUnavailableCode), chromeos::cfm::mojom::DisconnectReason:: kServiceUnavailableMessage); -#endif // BUILDFLAG(PLATFORM_CFM) })); + binder_map->Add<ash::cfm::mojom::XuCamera>(base::BindRepeating( + [](content::RenderFrameHost* frame_host, + mojo::PendingReceiver<ash::cfm::mojom::XuCamera> receiver) { + receiver.ResetWithReason( + static_cast<uint32_t>(chromeos::cfm::mojom::DisconnectReason:: + kServiceUnavailableCode), + chromeos::cfm::mojom::DisconnectReason:: + kServiceUnavailableMessage); + })); +#endif // BUILDFLAG(PLATFORM_CFM) } if (extension->permissions_data()->HasAPIPermission(
diff --git a/chrome/browser/fast_checkout/fast_checkout_delegate_impl_unittest.cc b/chrome/browser/fast_checkout/fast_checkout_delegate_impl_unittest.cc index 1c59909..4e63d3b 100644 --- a/chrome/browser/fast_checkout/fast_checkout_delegate_impl_unittest.cc +++ b/chrome/browser/fast_checkout/fast_checkout_delegate_impl_unittest.cc
@@ -21,6 +21,7 @@ #include "testing/gtest/include/gtest/gtest.h" using ::autofill::FastCheckoutTriggerOutcome; +using ::autofill::test::CreateTestAddressFormData; class FastCheckoutDelegateImplTest : public ChromeRenderViewHostTestHarness { protected: @@ -83,12 +84,10 @@ } TEST_F(FastCheckoutDelegateImplTest, IntendsToShowFastCheckout) { - autofill::FormData form; - autofill::test::CreateTestAddressFormData(&form); - autofill::FormFieldData field = form.fields[0]; - autofill::FormFieldData non_seen_field; - autofill::test::CreateTestFormField("First Name", "firstname", "", "text", - &non_seen_field); + autofill::FormData form = CreateTestAddressFormData(); + autofill::FormFieldData& field = form.fields[0]; + autofill::FormFieldData non_seen_field = autofill::test::CreateTestFormField( + "First Name", "firstname", "", "text"); autofill_manager()->OnFormsSeen( /*updated_forms=*/{form}, /*removed_forms=*/{}); @@ -106,9 +105,8 @@ TEST_F(FastCheckoutDelegateImplTest, RecordsFastCheckoutTriggerOutcomeMetricIfNotSupported) { - autofill::FormData form; - autofill::test::CreateTestAddressFormData(&form); - autofill::FormFieldData field = form.fields[0]; + autofill::FormData form = CreateTestAddressFormData(); + autofill::FormFieldData& field = form.fields[0]; autofill_manager()->OnFormsSeen( /*updated_forms=*/{form}, /*removed_forms=*/{});
diff --git a/chrome/browser/lacros/cros_apps/api/BUILD.gn b/chrome/browser/lacros/cros_apps/api/BUILD.gn index fe18e4c..216407046 100644 --- a/chrome/browser/lacros/cros_apps/api/BUILD.gn +++ b/chrome/browser/lacros/cros_apps/api/BUILD.gn
@@ -16,6 +16,7 @@ deps = [ "//chrome/browser/ui", "//chrome/test:test_support_ui", + "//chromeos/constants", "//content/test:test_support", "//testing/gtest", ]
diff --git a/chrome/browser/lacros/cros_apps/api/cros_apps_api_browsertest.cc b/chrome/browser/lacros/cros_apps/api/cros_apps_api_browsertest.cc index 4148355..a7e0bd10 100644 --- a/chrome/browser/lacros/cros_apps/api/cros_apps_api_browsertest.cc +++ b/chrome/browser/lacros/cros_apps/api/cros_apps_api_browsertest.cc
@@ -2,8 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/system/sys_info.h" +#include "base/test/scoped_feature_list.h" +#include "base/threading/thread_restrictions.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/constants/chromeos_features.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" @@ -11,7 +15,11 @@ class CrosAppsApiBrowserTest : public InProcessBrowserTest { public: - CrosAppsApiBrowserTest() = default; + CrosAppsApiBrowserTest() { + scoped_feature_list_.InitAndEnableFeature( + chromeos::features::kCrosAppsApis); + } + CrosAppsApiBrowserTest(const CrosAppsApiBrowserTest&) = delete; CrosAppsApiBrowserTest& operator=(const CrosAppsApiBrowserTest&) = delete; ~CrosAppsApiBrowserTest() override = default; @@ -22,6 +30,9 @@ command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "BlinkExtensionChromeOS"); } + + private: + base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_F(CrosAppsApiBrowserTest, ChromeOsExistsTest) { @@ -29,24 +40,56 @@ browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(true, content::EvalJs(web_contents, - "typeof window.chromeos !== 'undefined'")); + "typeof window.chromeos !== 'undefined';")); } -class DiagnosticsApiBrowserTest : public CrosAppsApiBrowserTest { +class CrosDiagnosticsApiBrowserTest : public CrosAppsApiBrowserTest { public: + CrosDiagnosticsApiBrowserTest() : CrosAppsApiBrowserTest() { + scoped_feature_list_.InitAndEnableFeature( + chromeos::features::kCrosDiagnosticsApi); + } + // CrosAppsApiBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { CrosAppsApiBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "BlinkExtensionChromeOSDiagnostics"); } + + private: + base::test::ScopedFeatureList scoped_feature_list_; }; -IN_PROC_BROWSER_TEST_F(DiagnosticsApiBrowserTest, DiagnosticsExistsTest) { +IN_PROC_BROWSER_TEST_F(CrosDiagnosticsApiBrowserTest, DiagnosticsExistsTest) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(true, content::EvalJs( web_contents, - "typeof window.chromeos.diagnostics !== 'undefined'")); + "typeof window.chromeos.diagnostics !== 'undefined';")); +} + +IN_PROC_BROWSER_TEST_F(CrosDiagnosticsApiBrowserTest, GetCpuInfoTest) { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + EXPECT_TRUE( + content::ExecJs(web_contents, + "(async () => { window.cpuInfoResult = await " + "window.chromeos.diagnostics.getCpuInfo(); })();")); + + { + // Some base::SysInfo calls are blocking. + base::ScopedAllowBlockingForTesting allow_blocking; + + EXPECT_EQ(base::SysInfo::ProcessCPUArchitecture(), + content::EvalJs(web_contents, + "window.cpuInfoResult.architectureName;")); + EXPECT_EQ(base::SysInfo::CPUModelName(), + content::EvalJs(web_contents, "window.cpuInfoResult.modelName;")); + EXPECT_EQ( + base::SysInfo::NumberOfProcessors(), + content::EvalJs(web_contents, "window.cpuInfoResult.numOfProcessors;")); + } }
diff --git a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.cc b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.cc index 2683cb2..3aaf8c5 100644 --- a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.cc +++ b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.cc
@@ -4,8 +4,28 @@ #include "chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.h" +#include "base/functional/bind.h" +#include "base/system/sys_info.h" +#include "base/task/thread_pool.h" #include "content/public/browser/render_frame_host.h" +namespace { + +blink::mojom::CrosCpuInfoPtr GetCpuInfoPostTask() { + blink::mojom::CrosCpuInfoPtr cpu_info_mojom = + blink::mojom::CrosCpuInfo::New(); + + cpu_info_mojom->architecture_name = base::SysInfo::ProcessCPUArchitecture(); + cpu_info_mojom->num_of_processors = base::SysInfo::NumberOfProcessors(); + + // Calls that may be thread-blocking. + cpu_info_mojom->model_name = base::SysInfo::CPUModelName(); + + return cpu_info_mojom; +} + +} // namespace + CrosDiagnosticsImpl::~CrosDiagnosticsImpl() = default; // static @@ -23,4 +43,17 @@ : content::DocumentUserData<CrosDiagnosticsImpl>(render_frame_host), receiver_(this, std::move(receiver)) {} +void CrosDiagnosticsImpl::GetCpuInfo(GetCpuInfoCallback callback) { + base::ThreadPool::PostTaskAndReplyWithResult( + FROM_HERE, {base::MayBlock()}, base::BindOnce(&GetCpuInfoPostTask), + base::BindOnce(&CrosDiagnosticsImpl::GetCpuInfoPostTaskCallback, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); +} + +void CrosDiagnosticsImpl::GetCpuInfoPostTaskCallback( + GetCpuInfoCallback callback, + blink::mojom::CrosCpuInfoPtr cpu_info_mojom) { + std::move(callback).Run(std::move(cpu_info_mojom)); +} + DOCUMENT_USER_DATA_KEY_IMPL(CrosDiagnosticsImpl);
diff --git a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.h b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.h index 1dc6c26..f0e41e3 100644 --- a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.h +++ b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_diagnostics_impl.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_LACROS_CROS_APPS_API_DIAGNOSTICS_CROS_DIAGNOSTICS_IMPL_H_ #define CHROME_BROWSER_LACROS_CROS_APPS_API_DIAGNOSTICS_CROS_DIAGNOSTICS_IMPL_H_ +#include "base/memory/weak_ptr.h" #include "content/public/browser/document_user_data.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -24,6 +25,9 @@ content::RenderFrameHost* render_frame_host, mojo::PendingReceiver<blink::mojom::CrosDiagnostics> receiver); + // blink::mojom::CrosDiagnostics + void GetCpuInfo(GetCpuInfoCallback callback) override; + private: friend class content::DocumentUserData<CrosDiagnosticsImpl>; @@ -31,9 +35,17 @@ content::RenderFrameHost* render_frame_host, mojo::PendingReceiver<blink::mojom::CrosDiagnostics> receiver); + void GetCpuInfoPostTaskCallback(GetCpuInfoCallback callback, + blink::mojom::CrosCpuInfoPtr cpu_info_mojom); + DOCUMENT_USER_DATA_KEY_DECL(); mojo::Receiver<blink::mojom::CrosDiagnostics> receiver_; + + // Last member definition. Needed here because WeakPtrFactory members which + // refer to their outer class must be the last member in the outer class + // definition. + base::WeakPtrFactory<CrosDiagnosticsImpl> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_LACROS_CROS_APPS_API_DIAGNOSTICS_CROS_DIAGNOSTICS_IMPL_H_
diff --git a/chrome/browser/lacros/sync/DIR_METADATA b/chrome/browser/lacros/sync/DIR_METADATA new file mode 100644 index 0000000..4a58e65 --- /dev/null +++ b/chrome/browser/lacros/sync/DIR_METADATA
@@ -0,0 +1 @@ +mixins: "//components/sync/COMMON_METADATA"
diff --git a/chrome/browser/media/chrome_media_session_client.cc b/chrome/browser/media/chrome_media_session_client.cc index 3a88605..25411851 100644 --- a/chrome/browser/media/chrome_media_session_client.cc +++ b/chrome/browser/media/chrome_media_session_client.cc
@@ -32,12 +32,16 @@ IDS_MEDIA_CONTROLS_TITLE_PLACEHOLDER_INCOGNITO); } +std::u16string ChromeMediaSessionClient::GetSourceTitlePlaceholder() const { + return std::u16string(); +} + std::u16string ChromeMediaSessionClient::GetArtistPlaceholder() const { - return u""; + return std::u16string(); } std::u16string ChromeMediaSessionClient::GetAlbumPlaceholder() const { - return u""; + return std::u16string(); } SkBitmap ChromeMediaSessionClient::GetThumbnailPlaceholder() const {
diff --git a/chrome/browser/media/chrome_media_session_client.h b/chrome/browser/media/chrome_media_session_client.h index cc77746..bd48b09 100644 --- a/chrome/browser/media/chrome_media_session_client.h +++ b/chrome/browser/media/chrome_media_session_client.h
@@ -19,6 +19,7 @@ content::BrowserContext* browser_context) const override; std::u16string GetTitlePlaceholder() const override; + std::u16string GetSourceTitlePlaceholder() const override; std::u16string GetArtistPlaceholder() const override; std::u16string GetAlbumPlaceholder() const override; SkBitmap GetThumbnailPlaceholder() const override;
diff --git a/chrome/browser/media/effects/video_effects_manager_impl.h b/chrome/browser/media/effects/video_effects_manager_impl.h index 18edac2..84f3008 100644 --- a/chrome/browser/media/effects/video_effects_manager_impl.h +++ b/chrome/browser/media/effects/video_effects_manager_impl.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_MEDIA_EFFECTS_VIDEO_EFFECTS_MANAGER_IMPL_H_ #define CHROME_BROWSER_MEDIA_EFFECTS_VIDEO_EFFECTS_MANAGER_IMPL_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "services/video_capture/public/mojom/video_effects_manager.mojom.h"
diff --git a/chrome/browser/media/media_session_browsertest.cc b/chrome/browser/media/media_session_browsertest.cc index 3cc5e9e0..1bba70b 100644 --- a/chrome/browser/media/media_session_browsertest.cc +++ b/chrome/browser/media/media_session_browsertest.cc
@@ -5,9 +5,12 @@ #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/media_session.h" +#include "content/public/browser/media_session_client.h" #include "content/public/browser/media_session_service.h" #include "content/public/test/browser_test.h" #include "media/base/media_switches.h" +#include "services/media_session/public/cpp/test/mock_media_session.h" class MediaSessionBrowserTest : public InProcessBrowserTest { public: @@ -22,21 +25,7 @@ ~MediaSessionBrowserTest() override = default; - void PlayVideoAndCheckHideMediaMetadataValue(Browser* browser, - bool expected_hide_metadata) { - MediaControlsObserver media_controls_observer; - mojo::Receiver<media_session::mojom::MediaControllerObserver> - observer_receiver_(&media_controls_observer); - mojo::Remote<media_session::mojom::MediaControllerManager> - controller_manager_remote; - mojo::Remote<media_session::mojom::MediaController> media_controller_remote; - content::GetMediaSessionService().BindMediaControllerManager( - controller_manager_remote.BindNewPipeAndPassReceiver()); - controller_manager_remote->CreateActiveMediaController( - media_controller_remote.BindNewPipeAndPassReceiver()); - media_controller_remote->AddObserver( - observer_receiver_.BindNewPipeAndPassRemote()); - + void PlayVideoWithMetadata(Browser* browser) { ASSERT_TRUE(embedded_test_server()->Start()); // Navigate to a test page with some media on it. @@ -48,49 +37,94 @@ // Start playback. ASSERT_EQ(nullptr, content::EvalJs(web_contents, "play()")); - - media_controls_observer.run_loop.Run(); - - EXPECT_EQ(media_controls_observer.hide_metadata, expected_hide_metadata); } - class MediaControlsObserver - : public media_session::mojom::MediaControllerObserver { - public: - void MediaSessionInfoChanged( - media_session::mojom::MediaSessionInfoPtr info) override { - if (info) { - hide_metadata = info->hide_metadata; - if (run_loop.IsRunningOnCurrentThread()) { - run_loop.Quit(); - } - } - } - void MediaSessionMetadataChanged( - const absl::optional<media_session::MediaMetadata>& metadata) override { - } - void MediaSessionActionsChanged( - const std::vector<media_session::mojom::MediaSessionAction>& action) - override {} - void MediaSessionChanged( - const absl::optional<base::UnguessableToken>& request_id) override {} - void MediaSessionPositionChanged( - const absl::optional<media_session::MediaPosition>& position) override { - } + media_session::MediaMetadata GetExpectedMetadata() { + media_session::MediaMetadata expected_metadata; - bool hide_metadata; - base::RunLoop run_loop; - }; + expected_metadata.title = u"Big Buck Bunny"; + expected_metadata.source_title = base::ASCIIToUTF16(base::StringPrintf( + "%s:%u", embedded_test_server()->GetIPLiteralString().c_str(), + embedded_test_server()->port())); + + expected_metadata.album = u""; + expected_metadata.artist = u"Blender Foundation"; + + return expected_metadata; + } + + media_session::MediaMetadata GetExpectedHiddenMetadata() { + media_session::MediaMetadata expected_metadata; + + content::MediaSessionClient* media_session_client = + content::MediaSessionClient::Get(); + + expected_metadata.title = media_session_client->GetTitlePlaceholder(); + expected_metadata.source_title = + media_session_client->GetSourceTitlePlaceholder(); + expected_metadata.album = media_session_client->GetAlbumPlaceholder(); + expected_metadata.artist = media_session_client->GetArtistPlaceholder(); + + return expected_metadata; + } base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, MediaSessionInfoDontHideMetadataByDefault) { - PlayVideoAndCheckHideMediaMetadataValue(browser(), false); + Browser* test_browser = browser(); + + media_session::test::MockMediaSessionMojoObserver observer( + *content::MediaSession::Get( + test_browser->tab_strip_model()->GetActiveWebContents())); + + PlayVideoWithMetadata(test_browser); + + observer.WaitForExpectedHideMetadata(false); } IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, MediaSessionInfoHideMetadataIfInIncognito) { - PlayVideoAndCheckHideMediaMetadataValue(CreateIncognitoBrowser(), true); + Browser* browser = CreateIncognitoBrowser(); + + media_session::test::MockMediaSessionMojoObserver observer( + *content::MediaSession::Get( + browser->tab_strip_model()->GetActiveWebContents())); + + PlayVideoWithMetadata(browser); + + observer.WaitForExpectedHideMetadata(true); } + +// We hide the media metadata from CrOS' media controls by replacing the +// metadata in the MediaSessionImpl with some placeholder metadata. These +// changes are gated to only affect ChromeOS, hence why the testing for this is +// also ChromeOS only. +#if BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, + MediaSessionInfoIsHiddenInCrOSIncognito) { + Browser* browser = CreateIncognitoBrowser(); + + media_session::test::MockMediaSessionMojoObserver observer( + *content::MediaSession::Get( + browser->tab_strip_model()->GetActiveWebContents())); + + PlayVideoWithMetadata(browser); + + observer.WaitForExpectedMetadata(GetExpectedHiddenMetadata()); +} +#else // !BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, + MediaSessionInfoIsNotHiddenInNonCrOSIncognito) { + Browser* browser = CreateIncognitoBrowser(); + + media_session::test::MockMediaSessionMojoObserver observer( + *content::MediaSession::Get( + browser->tab_strip_model()->GetActiveWebContents())); + + PlayVideoWithMetadata(browser); + + observer.WaitForExpectedMetadata(GetExpectedMetadata()); +} +#endif
diff --git a/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc b/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc index 8fccd44..defbccb 100644 --- a/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/password_manager/android/password_generation_controller_impl.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" +#include "base/memory/raw_ptr.h" #include <map> #include <memory>
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 73309f5..b8e2cf4d 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1961,14 +1961,12 @@ prefs::kGoogleSearchSidePanelEnabled, base::Value::Type::BOOLEAN }, #endif // BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) - { key::kBeforeunloadEventCancelByPreventDefaultEnabled, - policy_prefs::kBeforeunloadEventCancelByPreventDefaultEnabled, - base::Value::Type::BOOLEAN}, -#if !BUILDFLAG(IS_FUCHSIA) { key::kAllowBackForwardCacheForCacheControlNoStorePageEnabled, policy_prefs::kAllowBackForwardCacheForCacheControlNoStorePageEnabled, base::Value::Type::BOOLEAN}, -#endif // !BUILDFLAG(IS_FUCHSIA) + { key::kBeforeunloadEventCancelByPreventDefaultEnabled, + policy_prefs::kBeforeunloadEventCancelByPreventDefaultEnabled, + base::Value::Type::BOOLEAN}, { key::kDefaultMidiSetting, prefs::kManagedDefaultMidi, base::Value::Type::INTEGER },
diff --git a/chrome/browser/privacy_guide/android/BUILD.gn b/chrome/browser/privacy_guide/android/BUILD.gn index 062ed41..b48a6ca0 100644 --- a/chrome/browser/privacy_guide/android/BUILD.gn +++ b/chrome/browser/privacy_guide/android/BUILD.gn
@@ -20,6 +20,7 @@ "java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuidePagerAdapter.java", "java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideUtils.java", "java/src/org/chromium/chrome/browser/privacy_guide/SafeBrowsingFragment.java", + "java/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragment.java", "java/src/org/chromium/chrome/browser/privacy_guide/StepDisplayHandler.java", "java/src/org/chromium/chrome/browser/privacy_guide/StepDisplayHandlerImpl.java", "java/src/org/chromium/chrome/browser/privacy_guide/WelcomeFragment.java", @@ -29,6 +30,7 @@ "//base:base_java", "//chrome/browser/back_press/android:java", "//chrome/browser/flags:java", + "//chrome/browser/preferences:java", "//chrome/browser/privacy_sandbox/android:java", "//chrome/browser/profiles/android:java", "//chrome/browser/safe_browsing/android:java", @@ -69,6 +71,7 @@ "junit/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideMetricsDelegateTest.java", "junit/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuidePagerAdapterTest.java", "junit/src/org/chromium/chrome/browser/privacy_guide/SafeBrowsingFragmentTest.java", + "junit/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragmentTest.java", "junit/src/org/chromium/chrome/browser/privacy_guide/StepDisplayHandlerImplTest.java", ] deps = [ @@ -79,6 +82,7 @@ "//base:base_junit_test_support", "//base:jni_java", "//chrome/browser/flags:java", + "//chrome/browser/preferences:java", "//chrome/browser/privacy_sandbox/android:java", "//chrome/browser/profiles/android:java", "//chrome/browser/safe_browsing/android:java", @@ -151,6 +155,7 @@ "java/res/drawable-night/privacy_guide_history_sync_image.xml", "java/res/drawable-night/privacy_guide_msbb_image.xml", "java/res/drawable-night/privacy_guide_sb_image.xml", + "java/res/drawable-night/privacy_guide_search_suggestions_image.xml", "java/res/drawable-night/privacy_guide_welcome_image.xml", "java/res/drawable/active_tab_circle.xml", "java/res/drawable/inactive_tab_circle.xml", @@ -159,6 +164,7 @@ "java/res/drawable/privacy_guide_history_sync_image.xml", "java/res/drawable/privacy_guide_msbb_image.xml", "java/res/drawable/privacy_guide_sb_image.xml", + "java/res/drawable/privacy_guide_search_suggestions_image.xml", "java/res/drawable/privacy_guide_welcome_image.xml", "java/res/drawable/tab_selector.xml", "java/res/layout/privacy_guide_cookies_step.xml", @@ -167,9 +173,11 @@ "java/res/layout/privacy_guide_explanation_item.xml", "java/res/layout/privacy_guide_history_sync_step.xml", "java/res/layout/privacy_guide_msbb_step.xml", + "java/res/layout/privacy_guide_msbb_v3_step.xml", "java/res/layout/privacy_guide_sb_enhanced_explanation.xml", "java/res/layout/privacy_guide_sb_standard_explanation.xml", "java/res/layout/privacy_guide_sb_step.xml", + "java/res/layout/privacy_guide_search_suggestions_step.xml", "java/res/layout/privacy_guide_steps.xml", "java/res/layout/privacy_guide_welcome.xml", "java/res/menu/privacy_guide_toolbar_menu.xml",
diff --git a/chrome/browser/privacy_guide/android/java/res/drawable-night/privacy_guide_search_suggestions_image.xml b/chrome/browser/privacy_guide/android/java/res/drawable-night/privacy_guide_search_suggestions_image.xml new file mode 100644 index 0000000..fd9a0498 --- /dev/null +++ b/chrome/browser/privacy_guide/android/java/res/drawable-night/privacy_guide_search_suggestions_image.xml
@@ -0,0 +1,93 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2023 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + tools:ignore="VectorRaster" + android:width="300dp" + android:height="131dp" + android:viewportWidth="300" + android:viewportHeight="131"> + <path + android:pathData="M245,100L56,100" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#5F6368"/> + <path + android:pathData="M69.56,90.42C70.76,88.74 73.24,88.74 74.44,90.42L82,101H62L69.56,90.42Z" + android:fillColor="#5F6368"/> + <path + android:pathData="M85.91,85.73C86.71,84.68 88.29,84.68 89.09,85.73L99.98,100H75.02L85.91,85.73Z" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#5F6368"/> + <path + android:pathData="M94.37,91L102,101H73L80.63,91H94.37Z" + android:fillColor="#5F6368" + android:fillType="evenOdd"/> + <path + android:pathData="M273,44H252C253.7,39.89 257.76,37 262.5,37C267.24,37 271.3,39.89 273,44Z" + android:fillColor="#1967D2"/> + <path + android:pathData="M54,52H69C67.79,49.07 64.89,47 61.5,47C58.11,47 55.21,49.07 54,52Z" + android:fillColor="#1967D2"/> + <path + android:pathData="M239,26C229.06,26 221,34.06 221,44H257C257,34.06 248.94,26 239,26Z" + android:fillColor="#1967D2"/> + <path + android:pathData="M48,39C55.18,39 61,44.82 61,52H35C35,44.82 40.82,39 48,39Z" + android:fillColor="#1967D2"/> + <path + android:pathData="M223.5,33C217.15,33 212,37.92 212,44H235C235,37.92 229.85,33 223.5,33Z" + android:fillColor="#1967D2"/> + <path + android:pathData="M226,83L221,101H231L226,83Z" + android:fillColor="#5F6368"/> + <path + android:pathData="M233,89L229,101H237L233,89Z" + android:fillColor="#5F6368"/> + <path + android:pathData="M115,51L193,51A5,5 0,0 1,198 56L198,68A5,5 0,0 1,193 73L115,73A5,5 0,0 1,110 68L110,56A5,5 0,0 1,115 51z" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#BDC1C6"/> + <path + android:pathData="M129,79m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" + android:fillColor="#34A853"/> + <path + android:pathData="M183,44m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" + android:fillColor="#34A853"/> + <path + android:pathData="M115,42L118.72,47.59" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FDD663"/> + <path + android:pathData="M168.63,35L167,41.51" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FDD663"/> + <path + android:pathData="M185,77L190.26,81.16" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FDD663"/> + <path + android:pathData="M146.5,41.5m-2.5,0a2.5,2.5 0,1 1,5 0a2.5,2.5 0,1 1,-5 0" + android:fillColor="#5F6368"/> + <path + android:pathData="M159.5,82.5m-2.5,0a2.5,2.5 0,1 1,5 0a2.5,2.5 0,1 1,-5 0" + android:fillColor="#5F6368"/> + <path + android:pathData="M120,58L170,58A3,3 0,0 1,173 61L173,63A3,3 0,0 1,170 66L120,66A3,3 0,0 1,117 63L117,61A3,3 0,0 1,120 58z" + android:fillColor="#5F6368"/> + <path + android:pathData="M179,62L183,66L192,57" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#4285F4"/> +</vector>
diff --git a/chrome/browser/privacy_guide/android/java/res/drawable/privacy_guide_search_suggestions_image.xml b/chrome/browser/privacy_guide/android/java/res/drawable/privacy_guide_search_suggestions_image.xml new file mode 100644 index 0000000..d6661b2 --- /dev/null +++ b/chrome/browser/privacy_guide/android/java/res/drawable/privacy_guide_search_suggestions_image.xml
@@ -0,0 +1,93 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2023 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + tools:ignore="VectorRaster" + android:width="300dp" + android:height="131dp" + android:viewportWidth="300" + android:viewportHeight="131"> + <path + android:pathData="M245,100L56,100" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#E8EAED"/> + <path + android:pathData="M69.56,90.42C70.76,88.74 73.24,88.74 74.44,90.42L82,101H62L69.56,90.42Z" + android:fillColor="#E8EAED"/> + <path + android:pathData="M85.91,85.73C86.71,84.68 88.29,84.68 89.09,85.73L99.98,100H75.02L85.91,85.73Z" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#E8EAED"/> + <path + android:pathData="M94.37,91L102,101H73L80.63,91H94.37Z" + android:fillColor="#E8EAED" + android:fillType="evenOdd"/> + <path + android:pathData="M273,44H252C253.7,39.89 257.76,37 262.5,37C267.24,37 271.3,39.89 273,44Z" + android:fillColor="#AECBFA"/> + <path + android:pathData="M54,52H69C67.79,49.07 64.89,47 61.5,47C58.11,47 55.21,49.07 54,52Z" + android:fillColor="#AECBFA"/> + <path + android:pathData="M239,26C229.06,26 221,34.06 221,44H257C257,34.06 248.94,26 239,26Z" + android:fillColor="#AECBFA"/> + <path + android:pathData="M48,39C55.18,39 61,44.82 61,52H35C35,44.82 40.82,39 48,39Z" + android:fillColor="#AECBFA"/> + <path + android:pathData="M223.5,33C217.15,33 212,37.92 212,44H235C235,37.92 229.85,33 223.5,33Z" + android:fillColor="#AECBFA"/> + <path + android:pathData="M226,83L221,101H231L226,83Z" + android:fillColor="#E8EAED"/> + <path + android:pathData="M233,89L229,101H237L233,89Z" + android:fillColor="#E8EAED"/> + <path + android:pathData="M115,51L193,51A5,5 0,0 1,198 56L198,68A5,5 0,0 1,193 73L115,73A5,5 0,0 1,110 68L110,56A5,5 0,0 1,115 51z" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#BDC1C6"/> + <path + android:pathData="M129,79m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" + android:fillColor="#34A853"/> + <path + android:pathData="M183,44m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" + android:fillColor="#34A853"/> + <path + android:pathData="M115,42L118.72,47.59" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FBBC04"/> + <path + android:pathData="M168.63,35L167,41.51" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FBBC04"/> + <path + android:pathData="M185,77L190.26,81.16" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#FBBC04"/> + <path + android:pathData="M146.5,41.5m-2.5,0a2.5,2.5 0,1 1,5 0a2.5,2.5 0,1 1,-5 0" + android:fillColor="#E8EAED"/> + <path + android:pathData="M159.5,82.5m-2.5,0a2.5,2.5 0,1 1,5 0a2.5,2.5 0,1 1,-5 0" + android:fillColor="#E8EAED"/> + <path + android:pathData="M120,58L170,58A3,3 0,0 1,173 61L173,63A3,3 0,0 1,170 66L120,66A3,3 0,0 1,117 63L117,61A3,3 0,0 1,120 58z" + android:fillColor="#E8EAED"/> + <path + android:pathData="M179,62L183,66L192,57" + android:strokeWidth="2" + android:fillColor="#00000000" + android:strokeColor="#4285F4"/> +</vector>
diff --git a/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_msbb_v3_step.xml b/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_msbb_v3_step.xml new file mode 100644 index 0000000..cc27110 --- /dev/null +++ b/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_msbb_v3_step.xml
@@ -0,0 +1,92 @@ +<?xml version="1.0" encoding="utf-8"?><!-- +Copyright 2021 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" + android:id="@+id/msbb_v3_view" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout + android:id="@+id/msbb_v3_main_layout" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:animateLayoutChanges="true" + android:gravity="center_horizontal" + android:orientation="vertical"> + + <ImageView + android:id="@+id/image" + android:layout_marginHorizontal="@dimen/standard_illustration_marginHorizontal" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:maxHeight="@dimen/illustration_maxHeight" + android:adjustViewBounds="true" + android:src="@drawable/privacy_guide_msbb_image" + android:importantForAccessibility="no" /> + + <com.google.android.material.switchmaterial.SwitchMaterial + android:id="@+id/msbb_switch" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingHorizontal="@dimen/all_content_marginHorizontal" + android:showText="false" + android:text="@string/url_keyed_anonymized_data_title" + android:textAppearance="@style/TextAppearance.TextLarge.Primary" + android:foreground="?attr/selectableItemBackground" + android:background="@null" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginHorizontal="@dimen/all_content_marginHorizontal" + android:orientation="vertical"> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationHeading + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:titleText="@string/privacy_guide_when_on" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_flash_on_24dp" + app:summaryText="@string/privacy_guide_msbb_item_one" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_lightbulb_24dp" + app:summaryText="@string/privacy_guide_msbb_item_two_v3" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_notification_add_24dp" + app:summaryText="@string/privacy_guide_msbb_item_three_v3" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationHeading + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:titleText="@string/privacy_guide_things_to_consider" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_link_24dp" + app:summaryText="@string/privacy_guide_msbb_item_four_v3" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_bar_chart_24dp" + app:summaryText="@string/privacy_guide_msbb_item_five_v3" /> + + </LinearLayout> + + </LinearLayout> + +</ScrollView>
diff --git a/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_search_suggestions_step.xml b/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_search_suggestions_step.xml new file mode 100644 index 0000000..4b782935 --- /dev/null +++ b/chrome/browser/privacy_guide/android/java/res/layout/privacy_guide_search_suggestions_step.xml
@@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="utf-8"?><!-- +Copyright 2023 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" + android:id="@+id/search_suggestions_view" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout + android:id="@+id/search_suggestions_main_layout" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:animateLayoutChanges="true" + android:gravity="center_horizontal" + android:orientation="vertical"> + + <ImageView + android:layout_marginHorizontal="@dimen/standard_illustration_marginHorizontal" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:maxHeight="@dimen/illustration_maxHeight" + android:adjustViewBounds="true" + android:src="@drawable/privacy_guide_search_suggestions_image" + android:importantForAccessibility="no" /> + + <com.google.android.material.switchmaterial.SwitchMaterial + android:id="@+id/search_suggestions_switch" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingHorizontal="@dimen/all_content_marginHorizontal" + android:showText="false" + android:text="@string/improve_search_suggestions_title" + android:textAppearance="@style/TextAppearance.TextLarge.Primary" + android:foreground="?attr/selectableItemBackground" + android:background="@null" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginHorizontal="@dimen/all_content_marginHorizontal" + android:orientation="vertical"> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationHeading + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:titleText="@string/privacy_guide_when_on" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_manage_search_24dp" + app:summaryText="@string/privacy_guide_search_suggestions_item_one" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationHeading + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:titleText="@string/privacy_guide_things_to_consider" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_youtube_searched_for_24dp" + app:summaryText="@string/privacy_guide_search_suggestions_item_two" /> + + <org.chromium.chrome.browser.privacy_guide.PrivacyGuideExplanationItem + android:layout_width="match_parent" + android:layout_height="wrap_content" + app:iconImage="@drawable/ic_link_24dp" + app:summaryText="@string/privacy_guide_search_suggestions_item_three" /> + + </LinearLayout> + + </LinearLayout> + +</ScrollView>
diff --git a/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/MSBBFragment.java b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/MSBBFragment.java index 3d0bc64..e2598a45 100644 --- a/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/MSBBFragment.java +++ b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/MSBBFragment.java
@@ -12,6 +12,7 @@ import androidx.appcompat.widget.SwitchCompat; import androidx.fragment.app.Fragment; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridge; @@ -22,7 +23,9 @@ @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return inflater.inflate(R.layout.privacy_guide_msbb_step, container, false); + return ChromeFeatureList.sPrivacyGuideAndroid3.isEnabled() + ? inflater.inflate(R.layout.privacy_guide_msbb_v3_step, container, false) + : inflater.inflate(R.layout.privacy_guide_msbb_step, container, false); } @Override
diff --git a/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideUtils.java b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideUtils.java index 5542f01e..9657969f 100644 --- a/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideUtils.java +++ b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideUtils.java
@@ -7,6 +7,7 @@ import android.content.Context; import android.content.Intent; +import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.safe_browsing.SafeBrowsingBridge; import org.chromium.chrome.browser.safe_browsing.SafeBrowsingState; @@ -43,6 +44,11 @@ return identityManager.hasPrimaryAccount(ConsentLevel.SIGNIN); } + static boolean isSearchSuggestionsEnabled() { + return UserPrefs.get(Profile.getLastUsedRegularProfile()) + .getBoolean(Pref.SEARCH_SUGGEST_ENABLED); + } + static @SafeBrowsingState int getSafeBrowsingState() { return SafeBrowsingBridge.getSafeBrowsingState(); }
diff --git a/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragment.java b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragment.java new file mode 100644 index 0000000..d7d90b1 --- /dev/null +++ b/chrome/browser/privacy_guide/android/java/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragment.java
@@ -0,0 +1,39 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.privacy_guide; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import androidx.appcompat.widget.SwitchCompat; +import androidx.fragment.app.Fragment; + +import org.chromium.chrome.browser.preferences.Pref; +import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.components.user_prefs.UserPrefs; + +/** + * Controls the behaviour of the search suggestions privacy guide page. + */ +public class SearchSuggestionsFragment extends Fragment { + @Override + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return inflater.inflate(R.layout.privacy_guide_search_suggestions_step, container, false); + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + SwitchCompat searchSuggestionsSwitch = view.findViewById(R.id.search_suggestions_switch); + searchSuggestionsSwitch.setChecked(PrivacyGuideUtils.isSearchSuggestionsEnabled()); + + searchSuggestionsSwitch.setOnCheckedChangeListener((button, isChecked) -> { + UserPrefs.get(Profile.getLastUsedRegularProfile()) + .setBoolean(Pref.SEARCH_SUGGEST_ENABLED, isChecked); + }); + } +}
diff --git a/chrome/browser/privacy_guide/android/javatests/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideFragmentTest.java b/chrome/browser/privacy_guide/android/javatests/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideFragmentTest.java index 0a84288..c73b8b8 100644 --- a/chrome/browser/privacy_guide/android/javatests/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideFragmentTest.java +++ b/chrome/browser/privacy_guide/android/javatests/src/org/chromium/chrome/browser/privacy_guide/PrivacyGuideFragmentTest.java
@@ -285,6 +285,7 @@ @Test @LargeTest @Feature({"RenderTest"}) + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testRenderMSBBCard() throws IOException { launchPrivacyGuide(); navigateFromWelcomeToMSBBCard(); @@ -294,6 +295,16 @@ @Test @LargeTest @Feature({"RenderTest"}) + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testRenderMSBBCardPG3() throws IOException { + launchPrivacyGuide(); + navigateFromWelcomeToMSBBCard(); + mRenderTestRule.render(getRootView(), "privacy_guide_msbb_v3"); + } + + @Test + @LargeTest + @Feature({"RenderTest"}) public void testRenderHistorySyncCard() throws IOException { launchPrivacyGuide(); goToHistorySyncCard();
diff --git a/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/MSBBFragmentTest.java b/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/MSBBFragmentTest.java index 74fb0b6..b4beb370 100644 --- a/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/MSBBFragmentTest.java +++ b/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/MSBBFragmentTest.java
@@ -25,9 +25,12 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.base.test.util.UserActionTester; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridge; import org.chromium.chrome.browser.signin.services.UnifiedConsentServiceBridgeJni; +import org.chromium.chrome.test.util.browser.Features.DisableFeatures; +import org.chromium.chrome.test.util.browser.Features.EnableFeatures; /** * JUnit tests of the class {@link MSBBFragment}. @@ -72,18 +75,21 @@ } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testIsSwitchOffWhenMSBBOff() { initFragmentWithMSBBState(false); assertFalse(mMSBBButton.isChecked()); } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testIsSwitchOnWhenMSBBOn() { initFragmentWithMSBBState(true); assertTrue(mMSBBButton.isChecked()); } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testTurnMSBBOn() { initFragmentWithMSBBState(false); mMSBBButton.performClick(); @@ -91,6 +97,7 @@ } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testTurnMSBBOff() { initFragmentWithMSBBState(true); mMSBBButton.performClick(); @@ -98,6 +105,7 @@ } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testTurnMSBBOff_changeMSBBOffUserAction() { initFragmentWithMSBBState(true); mMSBBButton.performClick(); @@ -105,9 +113,56 @@ } @Test + @DisableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) public void testTurnMSBBOn_changeMSBBOnUserAction() { initFragmentWithMSBBState(false); mMSBBButton.performClick(); assertTrue(mActionTester.getActions().contains("Settings.PrivacyGuide.ChangeMSBBOn")); } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testIsSwitchOffWhenMSBBOffPG3() { + initFragmentWithMSBBState(false); + assertFalse(mMSBBButton.isChecked()); + } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testIsSwitchOnWhenMSBBOnPG3() { + initFragmentWithMSBBState(true); + assertTrue(mMSBBButton.isChecked()); + } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testTurnMSBBOnPG3() { + initFragmentWithMSBBState(false); + mMSBBButton.performClick(); + Mockito.verify(mNativeMock).setUrlKeyedAnonymizedDataCollectionEnabled(mProfile, true); + } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testTurnMSBBOffPG3() { + initFragmentWithMSBBState(true); + mMSBBButton.performClick(); + Mockito.verify(mNativeMock).setUrlKeyedAnonymizedDataCollectionEnabled(mProfile, false); + } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testTurnMSBBOff_changeMSBBOffUserActionPG3() { + initFragmentWithMSBBState(true); + mMSBBButton.performClick(); + assertTrue(mActionTester.getActions().contains("Settings.PrivacyGuide.ChangeMSBBOff")); + } + + @Test + @EnableFeatures(ChromeFeatureList.PRIVACY_GUIDE_ANDROID_3) + public void testTurnMSBBOn_changeMSBBOnUserActionPG3() { + initFragmentWithMSBBState(false); + mMSBBButton.performClick(); + assertTrue(mActionTester.getActions().contains("Settings.PrivacyGuide.ChangeMSBBOn")); + } }
diff --git a/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragmentTest.java b/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragmentTest.java new file mode 100644 index 0000000..a08edb3 --- /dev/null +++ b/chrome/browser/privacy_guide/android/junit/src/org/chromium/chrome/browser/privacy_guide/SearchSuggestionsFragmentTest.java
@@ -0,0 +1,106 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.privacy_guide; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.os.Bundle; + +import androidx.appcompat.widget.SwitchCompat; +import androidx.fragment.app.testing.FragmentScenario; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.base.test.util.JniMocker; +import org.chromium.base.test.util.UserActionTester; +import org.chromium.chrome.browser.preferences.Pref; +import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.components.prefs.PrefService; +import org.chromium.components.user_prefs.UserPrefs; +import org.chromium.components.user_prefs.UserPrefsJni; + +/** + * JUnit tests of the class {@link SearchSuggestionsFragment}. + */ +@RunWith(BaseRobolectricTestRunner.class) +public class SearchSuggestionsFragmentTest { + @Rule + public JniMocker mocker = new JniMocker(); + @Rule + public MockitoRule mMockitoRule = MockitoJUnit.rule(); + + @Mock + private Profile mProfile; + @Mock + private UserPrefs.Natives mUserPrefsJniMock; + @Mock + private PrefService mPrefService; + + private FragmentScenario mScenario; + private SwitchCompat mSearchSuggestionsButton; + private final UserActionTester mActionTester = new UserActionTester(); + + @Before + public void setUp() { + mocker.mock(UserPrefsJni.TEST_HOOKS, mUserPrefsJniMock); + Profile.setLastUsedProfileForTesting(mProfile); + when(mUserPrefsJniMock.get(mProfile)).thenReturn(mPrefService); + } + + @After + public void tearDown() { + if (mScenario != null) { + mScenario.close(); + } + mActionTester.tearDown(); + } + + private void initFragmentWithSearchSuggestionsState(boolean isSearchSuggestionsOn) { + when(mPrefService.getBoolean(Pref.SEARCH_SUGGEST_ENABLED)) + .thenReturn(isSearchSuggestionsOn); + mScenario = FragmentScenario.launchInContainer( + SearchSuggestionsFragment.class, Bundle.EMPTY, R.style.Theme_MaterialComponents); + mScenario.onFragment(fragment + -> mSearchSuggestionsButton = + fragment.getView().findViewById(R.id.search_suggestions_switch)); + } + + @Test + public void testIsSwitchOffWhenSearchSuggestionsOff() { + initFragmentWithSearchSuggestionsState(false); + assertFalse(mSearchSuggestionsButton.isChecked()); + } + + @Test + public void testIsSwitchOnWhenSearchSuggestionsOn() { + initFragmentWithSearchSuggestionsState(true); + assertTrue(mSearchSuggestionsButton.isChecked()); + } + + @Test + public void testTurnSearchSuggestionsOn() { + initFragmentWithSearchSuggestionsState(false); + mSearchSuggestionsButton.performClick(); + verify(mPrefService).setBoolean(Pref.SEARCH_SUGGEST_ENABLED, true); + } + + @Test + public void testTurnSearchSuggestionsOff() { + initFragmentWithSearchSuggestionsState(true); + mSearchSuggestionsButton.performClick(); + verify(mPrefService).setBoolean(Pref.SEARCH_SUGGEST_ENABLED, false); + } +}
diff --git a/chrome/browser/profiles/profile.h b/chrome/browser/profiles/profile.h index 4a461bde..ee1675aa 100644 --- a/chrome/browser/profiles/profile.h +++ b/chrome/browser/profiles/profile.h
@@ -11,7 +11,7 @@ #include <string> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h"
diff --git a/chrome/browser/profiles/profile_window.cc b/chrome/browser/profiles/profile_window.cc index 5c1591f..35028f7 100644 --- a/chrome/browser/profiles/profile_window.cc +++ b/chrome/browser/profiles/profile_window.cc
@@ -33,7 +33,6 @@ #include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/startup/launch_mode_recorder.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h"
diff --git a/chrome/browser/profiles/profile_window.h b/chrome/browser/profiles/profile_window.h index 79eb453..27d2628 100644 --- a/chrome/browser/profiles/profile_window.h +++ b/chrome/browser/profiles/profile_window.h
@@ -11,7 +11,6 @@ #include "build/build_config.h" #include "chrome/browser/ui/browser_list_observer.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/startup/startup_types.h" #if BUILDFLAG(IS_ANDROID)
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn index 7445b7f..a304dc19 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn
@@ -59,6 +59,7 @@ "dictation/parse/simple_parse_strategy.js", "dictation/parse/speech_parser.js", "dictation/ui_controller.js", + "gameface/gameface.js", "magnifier/magnifier.js", ] rewrite_rules = [ @@ -140,6 +141,7 @@ deps = [ ":autoclick", ":dictation", + ":gameface", ":magnifier", "../common:automation_predicate", "../common:chrome_event_handler", @@ -289,6 +291,10 @@ sources = [ "dictation/context_checker.js" ] } +js_library("gameface") { + sources = [ "gameface/gameface.js" ] +} + action("pumpkin_test_files") { testonly = true
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_loader.js b/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_loader.js index f080c7c..423ff6cb 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_loader.js +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_loader.js
@@ -7,6 +7,7 @@ import {Autoclick} from './autoclick/autoclick.js'; import {Dictation} from './dictation/dictation.js'; +import {GameFace} from './gameface/gameface.js'; import {Magnifier} from './magnifier/magnifier.js'; /** @@ -21,6 +22,8 @@ this.magnifier_ = null; /** @private {Dictation} */ this.dictation_ = null; + /** @private {GameFace} */ + this.gameFace_ = null; // For tests. /** @private {?function()} */ @@ -36,16 +39,17 @@ globalThis.accessibilityCommon = new AccessibilityCommon(); } - /** - * @return {Autoclick} - */ + /** @return {Autoclick} */ getAutoclickForTest() { return this.autoclick_; } - /** - * @return {Magnifier} - */ + /** @return {GameFace} */ + getGameFaceForTest() { + return this.gameFace_; + } + + /** @return {Magnifier} */ getMagnifierForTest() { return this.magnifier_; } @@ -79,6 +83,12 @@ chrome.accessibilityFeatures.dictation.onChange.addListener( details => this.onDictationUpdated_(details)); + const gameFaceFeature = + chrome.accessibilityPrivate.AccessibilityFeature.GAME_FACE_INTEGRATION; + chrome.accessibilityPrivate.isFeatureEnabled(gameFaceFeature, enabled => { + this.onGameFaceFetched_(enabled); + }); + // AccessibilityCommon is an IME so it shows in the input methods list // when it starts up. Remove from this list, Dictation will add it back // whenever needed. @@ -108,6 +118,21 @@ } /** + * Called when the GameFace feature status is fetched. + * @param {boolean} enabled + * @private + */ + onGameFaceFetched_(enabled) { + if (enabled) { + // Initialize the GameFace extension. + this.gameFace_ = new GameFace(); + } else if (!enabled && this.gameFace_) { + this.gameFace_.onGameFaceDisabled(); + this.gameFace_ = null; + } + } + + /** * @param {!Magnifier.Type} type * @param {*} details * @private
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_test.js b/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_test.js index 77c55aff..d4d0cf7 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_test.js +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/accessibility_common_test.js
@@ -8,6 +8,13 @@ * Accessibility common extension browser tests. */ AccessibilityCommonE2ETest = class extends CommonE2ETestBase { + async getFeature(name) { + return new Promise(resolve => { + chrome.accessibilityPrivate.isFeatureEnabled( + name, enabled => resolve(enabled)); + }); + } + async getPref(name) { return new Promise(resolve => { chrome.settingsPrivate.getPref(name, ret => { @@ -33,6 +40,12 @@ assertTrue(pref.value); assertTrue(Boolean(accessibilityCommon.getAutoclickForTest())); + // Then check that GameFace is disabled by default. + const enabled = await this.getFeature( + chrome.accessibilityPrivate.AccessibilityFeature.GAME_FACE_INTEGRATION); + assertFalse(enabled); + assertFalse(Boolean(accessibilityCommon.getGameFaceForTest())); + // Next, flip on screen magnifier and verify all prefs and internal state. await this.setPref('settings.a11y.screen_magnifier', true); pref = await this.getPref('settings.a11y.autoclick'); @@ -79,3 +92,29 @@ assertTrue(!accessibilityCommon.getMagnifierForTest()); })(); }); + +GEN('#include "ui/accessibility/accessibility_features.h"'); + +/** + * Accessibility common extension browser tests with enabled GameFace feature. + */ +AccessibilityCommonWithGameFaceEnabledE2ETest = + class extends AccessibilityCommonE2ETest { + /** @override */ + get featureList() { + return {enabled: ['features::kAccessibilityGameFaceIntegration']}; + } +}; + +TEST_F( + 'AccessibilityCommonWithGameFaceEnabledE2ETest', 'GameFaceEnabled', + function() { + this.newCallback(async () => { + // Then check that GameFace is enabled. + const enabled = await this.getFeature( + chrome.accessibilityPrivate.AccessibilityFeature + .GAME_FACE_INTEGRATION); + assertTrue(enabled); + assertTrue(Boolean(accessibilityCommon.getGameFaceForTest())); + })(); + });
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/COMMON_METADATA b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/COMMON_METADATA new file mode 100644 index 0000000..98f4b3c --- /dev/null +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/COMMON_METADATA
@@ -0,0 +1,7 @@ +team_email: "chromium-accessibility@chromium.org" +buganizer { + component_id: 1272890 +} +buganizer_public { + component_id: 1272577 +}
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/DIR_METADATA b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/DIR_METADATA new file mode 100644 index 0000000..1ab48f4 --- /dev/null +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/DIR_METADATA
@@ -0,0 +1 @@ +mixins: "//chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/COMMON_METADATA"
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/OWNERS b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/OWNERS new file mode 100644 index 0000000..70b73125 --- /dev/null +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/OWNERS
@@ -0,0 +1,2 @@ +bkersting@google.com +eariassoto@google.com
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/gameface.js b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/gameface.js new file mode 100644 index 0000000..b037d07 --- /dev/null +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/gameface/gameface.js
@@ -0,0 +1,15 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Main class for GameFace. + */ +export class GameFace { + constructor() {} + + /** + * Destructor to remove any listeners. + */ + onGameFaceDisabled() {} +}
diff --git a/chrome/browser/segmentation_platform/client_util/local_tab_handler.h b/chrome/browser/segmentation_platform/client_util/local_tab_handler.h index ae1532cb..57a2d0d8 100644 --- a/chrome/browser/segmentation_platform/client_util/local_tab_handler.h +++ b/chrome/browser/segmentation_platform/client_util/local_tab_handler.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SEGMENTATION_PLATFORM_CLIENT_UTIL_LOCAL_TAB_HANDLER_H_ #define CHROME_BROWSER_SEGMENTATION_PLATFORM_CLIENT_UTIL_LOCAL_TAB_HANDLER_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/supports_user_data.h" #include "components/segmentation_platform/embedder/input_delegate/tab_session_source.h" #include "components/segmentation_platform/embedder/tab_fetcher.h"
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc index 34182da..cd7bbfca 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/signin/bound_session_credentials/session_binding_helper.h" #include "chrome/browser/signin/wait_for_network_callback_helper_chrome.h" #include "content/public/browser/storage_partition.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" namespace { using Result = BoundSessionRefreshCookieFetcher::Result; @@ -62,6 +61,19 @@ resume_blocked_requests_.push_back(std::move(resume_blocked_request)); MaybeRefreshCookie(); + + if (!resume_blocked_requests_timer_.IsRunning() && + !resume_blocked_requests_.empty()) { + // Ensure all blocked requests are released after a timeout. + // `base::Unretained(this)` is safe because `this` owns + // `resume_blocked_requests_timer_`. + const base::TimeDelta kResumeBlockedRequestTimeout = base::Seconds(20); + resume_blocked_requests_timer_.Start( + FROM_HERE, kResumeBlockedRequestTimeout, + base::BindRepeating( + &BoundSessionCookieControllerImpl::ResumeBlockedRequests, + base::Unretained(this))); + } } void BoundSessionCookieControllerImpl::SetCookieExpirationTimeAndNotify( @@ -175,6 +187,7 @@ } void BoundSessionCookieControllerImpl::ResumeBlockedRequests() { + resume_blocked_requests_timer_.Stop(); std::vector<base::OnceClosure> callbacks; std::swap(callbacks, resume_blocked_requests_); for (auto& callback : callbacks) {
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.h b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.h index ae3b053..9a28daf 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.h +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.h
@@ -9,7 +9,6 @@ #include <memory> -#include "base/containers/span.h" #include "base/functional/callback_forward.h" #include "base/time/time.h" #include "base/timer/timer.h" @@ -39,11 +38,6 @@ const base::flat_set<std::string>& cookie_names, Delegate* delegate); - void Initialize() override; - - void OnRequestBlockedOnCookie( - base::OnceClosure resume_blocked_request) override; - ~BoundSessionCookieControllerImpl() override; BoundSessionCookieControllerImpl(const BoundSessionCookieControllerImpl&) = @@ -51,6 +45,12 @@ BoundSessionCookieControllerImpl& operator=( const BoundSessionCookieControllerImpl&) = delete; + // BoundSessionCookieController: + void Initialize() override; + + void OnRequestBlockedOnCookie( + base::OnceClosure resume_blocked_request) override; + private: friend class BoundSessionCookieControllerImplTest; @@ -94,6 +94,8 @@ std::vector<base::OnceClosure> resume_blocked_requests_; // Used to schedule preemptive cookie refresh. base::OneShotTimer cookie_refresh_timer_; + // Used to release blocked requests after a timeout. + base::OneShotTimer resume_blocked_requests_timer_; RefreshCookieFetcherFactoryForTesting refresh_cookie_fetcher_factory_for_testing_;
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc index 2ed6abfe..c8f823cd 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc
@@ -40,6 +40,7 @@ const base::TimeDelta kCookieExpirationThreshold = base::Seconds(15); const base::TimeDelta kCookieRefreshInterval = base::Minutes(2); +const base::TimeDelta kResumeBlockedRequestTimeout = base::Seconds(20); base::Time GetTimeInTenMinutes() { return base::Time::Now() + base::Minutes(10); @@ -202,6 +203,10 @@ return &bound_session_cookie_controller()->cookie_refresh_timer_; } + base::OneShotTimer* resume_blocked_requests_timer() { + return &bound_session_cookie_controller()->resume_blocked_requests_timer_; + } + unexportable_keys::UnexportableKeyLoader* key_loader() { return bound_session_cookie_controller() ->session_binding_helper_->key_loader_.get(); @@ -536,6 +541,62 @@ } } +TEST_F(BoundSessionCookieControllerImplTest, ResumeBlockedRequestsOnTimeout) { + base::test::TestFuture<void> future; + bound_session_cookie_controller()->OnRequestBlockedOnCookie( + future.GetCallback()); + EXPECT_FALSE(future.IsReady()); + + task_environment()->FastForwardBy(kResumeBlockedRequestTimeout); + // The fetch hasn't completed nor are the required cookies fresh, but the + // request is resumed due to timeout. + EXPECT_FALSE(AreAllCookiesFresh()); + EXPECT_TRUE(cookie_fetcher()); + EXPECT_TRUE(future.IsReady()); + EXPECT_FALSE(resume_blocked_requests_timer()->IsRunning()); +} + +TEST_F(BoundSessionCookieControllerImplTest, + BlockedRequestsCalculateTimeoutFromFirstRequest) { + constexpr int kBlockedRequestCount = 2; + constexpr base::TimeDelta kDeltaBetweenRequests = base::Seconds(1); + BoundSessionCookieController* controller = bound_session_cookie_controller(); + std::array<base::test::TestFuture<void>, kBlockedRequestCount> futures; + + for (auto& future : futures) { + controller->OnRequestBlockedOnCookie(future.GetCallback()); + EXPECT_FALSE(future.IsReady()); + task_environment()->FastForwardBy(kDeltaBetweenRequests); + } + + // We should release as soon as `kResumeBlockedRequestTimeout` has passed + // since the first blocked request. + task_environment()->FastForwardBy(kResumeBlockedRequestTimeout - + kDeltaBetweenRequests * + kBlockedRequestCount); + // The fetch hasn't completed nor are the required cookies fresh, but the + // requests are resumed due to timeout. + EXPECT_FALSE(AreAllCookiesFresh()); + EXPECT_TRUE(cookie_fetcher()); + for (auto& future : futures) { + EXPECT_TRUE(future.IsReady()); + } + EXPECT_FALSE(resume_blocked_requests_timer()->IsRunning()); +} + +TEST_F(BoundSessionCookieControllerImplTest, ResumeBlockedRequestsTimerReset) { + base::test::TestFuture<void> future; + bound_session_cookie_controller()->OnRequestBlockedOnCookie( + future.GetCallback()); + EXPECT_FALSE(future.IsReady()); + EXPECT_TRUE(resume_blocked_requests_timer()->IsRunning()); + SimulateCompleteRefreshRequest( + BoundSessionRefreshCookieFetcher::Result::kSuccess, + GetTimeInTenMinutes()); + EXPECT_TRUE(future.IsReady()); + EXPECT_FALSE(resume_blocked_requests_timer()->IsRunning()); +} + TEST_F(BoundSessionCookieControllerImplTest, NotNullCookieExpirationTimeIsReducedByThreshold) { EXPECT_TRUE(CompletePendingRefreshRequestIfAny());
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl_unittest.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl_unittest.cc index a262d6e..8457803 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_refresh_service_impl_unittest.cc
@@ -7,10 +7,10 @@ #include <memory> #include <utility> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/base64.h" #include "base/functional/bind.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h"
diff --git a/chrome/browser/signin/dice_browsertest.cc b/chrome/browser/signin/dice_browsertest.cc index d46e71d..33b6f5f 100644 --- a/chrome/browser/signin/dice_browsertest.cc +++ b/chrome/browser/signin/dice_browsertest.cc
@@ -39,7 +39,6 @@ #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/sync/user_event_service_factory.h" #include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/simple_message_box_internal.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" @@ -1020,7 +1019,6 @@ // Signin using the Chrome Sync endpoint. browser()->signin_view_controller()->ShowSignin( - profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); // Receive ENABLE_SYNC. @@ -1074,7 +1072,6 @@ CloseBrowserWhileInitializingSyncConfirmation) { // Signin using the Chrome Sync endpoint. browser()->signin_view_controller()->ShowSignin( - profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); content::TestNavigationObserver sync_confirmation_url_observer(
diff --git a/chrome/browser/supervised_user/chrome_supervised_user_web_content_handler_base.h b/chrome/browser/supervised_user/chrome_supervised_user_web_content_handler_base.h index fcc33df..8ee7fecb 100644 --- a/chrome/browser/supervised_user/chrome_supervised_user_web_content_handler_base.h +++ b/chrome/browser/supervised_user/chrome_supervised_user_web_content_handler_base.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SUPERVISED_USER_CHROME_SUPERVISED_USER_WEB_CONTENT_HANDLER_BASE_H_ #define CHROME_BROWSER_SUPERVISED_USER_CHROME_SUPERVISED_USER_WEB_CONTENT_HANDLER_BASE_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "components/supervised_user/core/browser/web_content_handler.h" namespace content {
diff --git a/chrome/browser/sync/chrome_sync_client.cc b/chrome/browser/sync/chrome_sync_client.cc index 714f080..f0a06ea 100644 --- a/chrome/browser/sync/chrome_sync_client.cc +++ b/chrome/browser/sync/chrome_sync_client.cc
@@ -99,8 +99,8 @@ #if BUILDFLAG(ENABLE_SUPERVISED_USERS) #include "chrome/browser/profiles/profile_key.h" #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" +#include "components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h" #include "components/supervised_user/core/browser/supervised_user_settings_service.h" -#include "components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h" #endif // BUILDFLAG(ENABLE_SUPERVISED_USERS) #if BUILDFLAG(ENABLE_SPELLCHECK)
diff --git a/chrome/browser/sync/sync_service_factory.cc b/chrome/browser/sync/sync_service_factory.cc index a62f5ac0..a8f5898 100644 --- a/chrome/browser/sync/sync_service_factory.cc +++ b/chrome/browser/sync/sync_service_factory.cc
@@ -73,6 +73,7 @@ #endif // BUILDFLAG(ENABLE_SUPERVISED_USERS) #if BUILDFLAG(IS_CHROMEOS_ASH) +#include "chrome/browser/ash/app_list/app_list_syncable_service_factory.h" #include "chrome/browser/ash/printing/oauth2/authorization_zones_manager_factory.h" #include "chrome/browser/ash/printing/synced_printers_manager_factory.h" #include "chrome/browser/ash/profiles/profile_helper.h" @@ -282,6 +283,7 @@ DependsOn(web_app::WebAppProviderFactory::GetInstance()); #endif // BUILDFLAG(ENABLE_EXTENSIONS) #if BUILDFLAG(IS_CHROMEOS_ASH) + DependsOn(app_list::AppListSyncableServiceFactory::GetInstance()); DependsOn(ash::SyncedPrintersManagerFactory::GetInstance()); DependsOn( ash::printing::oauth2::AuthorizationZonesManagerFactory::GetInstance());
diff --git a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc index 2d0a1b99..ef1f7fe 100644 --- a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc
@@ -547,6 +547,39 @@ ASSERT_EQ(GetPrefs(0)->GetList(kHistorySensitiveListPrefName), local_value); } +// Regression test for crbug.com/1456872. +IN_PROC_BROWSER_TEST_F(SingleClientPreferencesWithAccountStorageSyncTest, + ShouldHandleWalletSideEffectsWhenSyncDisabled) { + ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; + ASSERT_FALSE( + GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); + + InjectPreferenceToFakeServer(syncer::PREFERENCES, + autofill::prefs::kAutofillCreditCardEnabled, + base::Value(false)); + + // Enable Sync. + ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; + ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); + + // Fake server value is synced to the account store and overrides local value. + ASSERT_FALSE( + GetPrefs(0)->GetBoolean(autofill::prefs::kAutofillCreditCardEnabled)); + + // kAutofillCreditCardEnabled prevents AUTOFILL_WALLET from running. + ASSERT_FALSE(GetSyncService(0)->GetActiveDataTypes().Has( + syncer::AUTOFILL_WALLET_DATA)); + + // Disable sync, the data and metadata should be gone, without crashes. + GetClient(0)->StopSyncServiceAndClearData(); + + ASSERT_FALSE( + GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); + + // Enabling sync again should work, without crashes. + EXPECT_TRUE(SetupSync()); +} + // TODO(crbug.com/1416480): Consider making other fixtures parameterized with // `kSyncEnablePersistentStorageForAccountPreferences` flag enabled and disabled // both. @@ -1032,48 +1065,4 @@ updated_value); } -class SingleClientPreferencesWithAvoidReconfigurationFlagEnabledSyncTest - : public SingleClientPreferencesWithAccountStorageSyncTest { - public: - SingleClientPreferencesWithAvoidReconfigurationFlagEnabledSyncTest() - : feature_list_(syncer::kSyncAvoidReconfigurationIfAlreadyStopping) {} - - private: - base::test::ScopedFeatureList feature_list_; -}; - -// Regression test for crbug.com/1456872. -IN_PROC_BROWSER_TEST_F( - SingleClientPreferencesWithAvoidReconfigurationFlagEnabledSyncTest, - ShouldHandleWalletSideEffectsWhenSyncDisabled) { - ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; - ASSERT_FALSE( - GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); - - InjectPreferenceToFakeServer(syncer::PREFERENCES, - autofill::prefs::kAutofillCreditCardEnabled, - base::Value(false)); - - // Enable Sync. - ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); - - // Fake server value is synced to the account store and overrides local value. - ASSERT_FALSE( - GetPrefs(0)->GetBoolean(autofill::prefs::kAutofillCreditCardEnabled)); - - // kAutofillCreditCardEnabled prevents AUTOFILL_WALLET from running. - ASSERT_FALSE(GetSyncService(0)->GetActiveDataTypes().Has( - syncer::AUTOFILL_WALLET_DATA)); - - // Disable sync, the data and metadata should be gone, without crashes. - GetClient(0)->StopSyncServiceAndClearData(); - - ASSERT_FALSE( - GetSyncService(0)->GetActiveDataTypes().Has(syncer::PREFERENCES)); - - // Enabling sync again should work, without crashes. - EXPECT_TRUE(SetupSync()); -} - } // namespace
diff --git a/chrome/browser/sync_file_system/sync_file_system_service_factory.cc b/chrome/browser/sync_file_system/sync_file_system_service_factory.cc index 41c897eb..26c1fdc8 100644 --- a/chrome/browser/sync_file_system/sync_file_system_service_factory.cc +++ b/chrome/browser/sync_file_system/sync_file_system_service_factory.cc
@@ -10,6 +10,7 @@ #include "base/check_is_test.h" #include "base/command_line.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sync/sync_service_factory.h" #include "chrome/browser/sync_file_system/local/local_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" @@ -56,6 +57,7 @@ typedef std::set<BrowserContextKeyedServiceFactory*> FactorySet; FactorySet factories; factories.insert(extensions::ExtensionRegistryFactory::GetInstance()); + factories.insert(SyncServiceFactory::GetInstance()); RemoteFileSyncService::AppendDependsOnFactories(&factories); for (auto iter = factories.begin(); iter != factories.end(); ++iter) { DependsOn(*iter);
diff --git a/chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_controller.h b/chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_controller.h index 3decf8e..cfcfee1 100644 --- a/chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_controller.h +++ b/chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_controller.h
@@ -6,8 +6,8 @@ #define CHROME_BROWSER_TOUCH_TO_FILL_PASSWORD_GENERATION_ANDROID_TOUCH_TO_FILL_PASSWORD_GENERATION_CONTROLLER_H_ #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" #include "chrome/browser/password_manager/android/password_generation_element_data.h" #include "chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_bridge.h" #include "chrome/browser/touch_to_fill/password_generation/android/touch_to_fill_password_generation_delegate.h"
diff --git a/chrome/browser/touch_to_fill/payments/android/touch_to_fill_delegate_android_impl_unittest.cc b/chrome/browser/touch_to_fill/payments/android/touch_to_fill_delegate_android_impl_unittest.cc index 8b86200..1817d165 100644 --- a/chrome/browser/touch_to_fill/payments/android/touch_to_fill_delegate_android_impl_unittest.cc +++ b/chrome/browser/touch_to_fill/payments/android/touch_to_fill_delegate_android_impl_unittest.cc
@@ -17,22 +17,24 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" -using testing::_; -using testing::ElementsAre; -using testing::ElementsAreArray; -using testing::NiceMock; -using testing::Pointee; -using testing::Ref; -using testing::Return; - namespace autofill { namespace { +using test::CreateTestCreditCardFormData; +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::ElementsAreArray; +using ::testing::NiceMock; +using ::testing::Pointee; +using ::testing::Ref; +using ::testing::Return; + class MockAutofillClient : public TestAutofillClient { public: MockAutofillClient() = default;
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index d564cf9..04e39a3e 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -163,7 +163,6 @@ "prefs/pref_watcher.h", "prefs/prefs_tab_helper.cc", "prefs/prefs_tab_helper.h", - "profiles/profile_chooser_constants.h", "profiles/profile_error_dialog.cc", "profiles/profile_error_dialog.h", "recently_audible_helper.cc",
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 487d39e..03b711af 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -1502,6 +1502,18 @@ <message name="IDS_PRIVACY_GUIDE_MSBB_ITEM_FOUR" desc="Fourth bullet point that describes the details of the MSBB toggle."> If you also share Chrome usage reports, those reports include the URLs you visit </message> + <message name="IDS_PRIVACY_GUIDE_MSBB_ITEM_TWO_V3" desc="Second bullet point that describes the details of the MSBB toggle."> + From the address bar, you can open page info to see additional info about the page you're visiting + </message> + <message name="IDS_PRIVACY_GUIDE_MSBB_ITEM_THREE_V3" desc="Third bullet point that describes the details of the MSBB toggle."> + If you also save your bookmarks in your Google Account, you can track product prices in Chrome and get notified when the price drops + </message> + <message name="IDS_PRIVACY_GUIDE_MSBB_ITEM_FOUR_V3" desc="Forth bullet point that describes the details of the MSBB toggle."> + URLs you visit are sent to Google to predict what sites you might visit next and to show you additional info about the page you're visiting + </message> + <message name="IDS_PRIVACY_GUIDE_MSBB_ITEM_FIVE_V3" desc="Fifth bullet point that describes the details of the MSBB toggle."> + If you also share Chrome usage reports, those reports include the URLs you visit + </message> <message name="IDS_PRIVACY_GUIDE_HISTORY_SYNC_TOGGLE" desc="Title for the history sync toggle."> History sync </message> @@ -1607,6 +1619,15 @@ <message name="IDS_PRIVACY_GUIDE_SB_ENHANCED_ITEM_SEVEN" desc="Seventh bullet point that describes the details of the Safe Browsing control."> Temporarily links this data to your Google Account when you’re signed in, to protect you across Google apps </message> + <message name="IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_ONE" desc="First bullet point that describes the details of the search suggestions toggle."> + When you tap or type in the address bar or search box, you'll see suggestions from your default search engine. This is off in Incognito. + </message> + <message name="IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_TWO" desc="Second bullet point that describes the details of the search suggestions toggle."> + What you type in the address bar or search box is sent to your default search engine + </message> + <message name="IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_THREE" desc="Third bullet point that describes the details of the search suggestions toggle."> + Depending on your settings, Chrome may also send cookies and your current URL + </message> <!-- Safety check --> <message name="IDS_PREFS_SAFETY_CHECK" desc="Title of the Safety check element in settings, allowing the user to check multiple areas of browser safety. [CHAR_LIMIT=32]">
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FIVE_V3.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FIVE_V3.png.sha1 new file mode 100644 index 0000000..ab49eaae0 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FIVE_V3.png.sha1
@@ -0,0 +1 @@ +1c268e1cf5adb363769ffdd96bdb51f6243ff4ee \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FOUR_V3.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FOUR_V3.png.sha1 new file mode 100644 index 0000000..155aab8 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_FOUR_V3.png.sha1
@@ -0,0 +1 @@ +96a7ca148799a976ec4af696e1868ce1b94f053d \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_THREE_V3.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_THREE_V3.png.sha1 new file mode 100644 index 0000000..9406c25 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_THREE_V3.png.sha1
@@ -0,0 +1 @@ +de573b499c0caff684d3a20d2609a94b7955e1cc \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_TWO_V3.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_TWO_V3.png.sha1 new file mode 100644 index 0000000..a25bbf3 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_MSBB_ITEM_TWO_V3.png.sha1
@@ -0,0 +1 @@ +48dd6c30cca38bb3b602adf8b4f10fbcd1889f90 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_ONE.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_ONE.png.sha1 new file mode 100644 index 0000000..13e0cbd --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_ONE.png.sha1
@@ -0,0 +1 @@ +26f9c2092fd433216c606953423708d5d4c86245 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_THREE.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_THREE.png.sha1 new file mode 100644 index 0000000..c463b7a --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_THREE.png.sha1
@@ -0,0 +1 @@ +f748cc79b82ba342b3f5bb8abdf7a8771f551f07 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_TWO.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_TWO.png.sha1 new file mode 100644 index 0000000..c7a5c335 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_PRIVACY_GUIDE_SEARCH_SUGGESTIONS_ITEM_TWO.png.sha1
@@ -0,0 +1 @@ +156e6829aa11b7ad91c9c1af91d4b26c1c2af4e8 \ No newline at end of file
diff --git a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc index da5e1b1..8b69b0b 100644 --- a/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.cc
@@ -390,7 +390,7 @@ } else { autofill_metrics::LogSaveCardPromptResultMetric( metric, is_upload_save_, is_reshow_, options_, GetSecurityLevel(), - personal_data_manager_->GetSyncSigninState()); + personal_data_manager_->GetPaymentsSigninStateForMetrics()); } } @@ -534,7 +534,7 @@ autofill_metrics::LogSaveCardPromptOfferMetric( autofill_metrics::SaveCardPromptOffer::kShown, is_upload_save_, is_reshow_, options_, GetSecurityLevel(), - personal_data_manager_->GetSyncSigninState()); + personal_data_manager_->GetPaymentsSigninStateForMetrics()); break; case BubbleType::LOCAL_CVC_SAVE: autofill_metrics::LogSaveCvcPromptOfferMetric( @@ -610,7 +610,7 @@ autofill_metrics::LogSaveCardPromptOfferMetric( autofill_metrics::SaveCardPromptOffer::kNotShownMaxStrikesReached, is_upload_save_, is_reshow_, options_, GetSecurityLevel(), - personal_data_manager_->GetSyncSigninState()); + personal_data_manager_->GetPaymentsSigninStateForMetrics()); break; case BubbleType::LOCAL_CVC_SAVE: autofill_metrics::LogSaveCvcPromptOfferMetric(
diff --git a/chrome/browser/ui/autofill/save_update_address_profile_bubble_controller_impl_unittest.cc b/chrome/browser/ui/autofill/save_update_address_profile_bubble_controller_impl_unittest.cc index 17f7f38..6a0a92e4 100644 --- a/chrome/browser/ui/autofill/save_update_address_profile_bubble_controller_impl_unittest.cc +++ b/chrome/browser/ui/autofill/save_update_address_profile_bubble_controller_impl_unittest.cc
@@ -6,8 +6,8 @@ #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback_helpers.h" +#include "base/memory/raw_ptr.h" #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/browser_process.h"
diff --git a/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.cc b/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.cc index 11d33fa..b3cc715 100644 --- a/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.cc +++ b/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.cc
@@ -286,7 +286,7 @@ void ShoppingListUiTabHelper::HandleProductInfoResponse( const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { if (url != web_contents()->GetLastCommittedURL() || !info.has_value()) { return; }
diff --git a/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.h b/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.h index 47718ee..02afee6 100644 --- a/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.h +++ b/chrome/browser/ui/commerce/price_tracking/shopping_list_ui_tab_helper.h
@@ -112,7 +112,7 @@ friend class ShoppingListUiTabHelperTest; void HandleProductInfoResponse(const GURL& url, - const absl::optional<ProductInfo>& info); + const absl::optional<const ProductInfo>& info); void HandlePriceInsightsInfoResponse( const GURL& url,
diff --git a/chrome/browser/ui/profiles/profile_chooser_constants.h b/chrome/browser/ui/profiles/profile_chooser_constants.h deleted file mode 100644 index cc2b7b8..0000000 --- a/chrome/browser/ui/profiles/profile_chooser_constants.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_PROFILES_PROFILE_CHOOSER_CONSTANTS_H_ -#define CHROME_BROWSER_UI_PROFILES_PROFILE_CHOOSER_CONSTANTS_H_ - -#include "third_party/skia/include/core/SkColor.h" - -namespace profiles { - -// Different views that can be displayed in the profile chooser bubble. -enum BubbleViewMode { - // Shows the default avatar bubble. - BUBBLE_VIEW_MODE_PROFILE_CHOOSER, - // Shows a web view for primary sign in. - BUBBLE_VIEW_MODE_GAIA_SIGNIN, - // Shows a web view for adding secondary accounts. - BUBBLE_VIEW_MODE_GAIA_ADD_ACCOUNT, - // Shows a web view for reauthenticating an account. - BUBBLE_VIEW_MODE_GAIA_REAUTH, - // Shows a view for incognito that displays the number of incognito windows. - BUBBLE_VIEW_MODE_INCOGNITO, -}; - -} // namespace profiles - -#endif // CHROME_BROWSER_UI_PROFILES_PROFILE_CHOOSER_CONSTANTS_H_
diff --git a/chrome/browser/ui/safety_hub/password_status_check_service.cc b/chrome/browser/ui/safety_hub/password_status_check_service.cc index e734190..d08ac9b 100644 --- a/chrome/browser/ui/safety_hub/password_status_check_service.cc +++ b/chrome/browser/ui/safety_hub/password_status_check_service.cc
@@ -60,7 +60,7 @@ PasswordStatusCheckService::~PasswordStatusCheckService() = default; void PasswordStatusCheckService::Shutdown() { - saved_passwords_presenter_observation_.Reset(); + insecure_credentials_manager_observation_.Reset(); bulk_leak_check_observation_.Reset(); password_check_delegate_.reset(); saved_passwords_presenter_.reset(); @@ -99,12 +99,16 @@ is_update_credential_count_pending_ = true; + // `InsecureCredentialsManager::OnSavedPasswordsChanged` will run weak and + // reuse checks on initialization. When both are concluded, observers are + // notified (`OnInsecureCredentialsChanged`). Information whether a credential + // is leaked is stored in the password manager and does not have to be re-run. InitializePasswordCheckInfrastructure(); - CHECK(saved_passwords_presenter_); - if (!saved_passwords_presenter_observation_.IsObserving()) { - saved_passwords_presenter_observation_.Observe( - saved_passwords_presenter_.get()); + CHECK(password_check_delegate_); + if (!insecure_credentials_manager_observation_.IsObserving()) { + insecure_credentials_manager_observation_.Observe( + password_check_delegate_->GetInsecureCredentialsManager()); } } @@ -128,8 +132,7 @@ password_check_delegate_->StartPasswordCheck(); } -void PasswordStatusCheckService::OnSavedPasswordsChanged( - const password_manager::PasswordStoreChangeList& changes) { +void PasswordStatusCheckService::OnInsecureCredentialsChanged() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CHECK(IsInfrastructureReady()); @@ -218,7 +221,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!is_update_credential_count_pending_ && !is_password_check_running_) { - saved_passwords_presenter_observation_.Reset(); + insecure_credentials_manager_observation_.Reset(); bulk_leak_check_observation_.Reset(); // The reset is done as a task rather than directly because when observers
diff --git a/chrome/browser/ui/safety_hub/password_status_check_service.h b/chrome/browser/ui/safety_hub/password_status_check_service.h index 45af3d6..6c2c7ac 100644 --- a/chrome/browser/ui/safety_hub/password_status_check_service.h +++ b/chrome/browser/ui/safety_hub/password_status_check_service.h
@@ -10,11 +10,12 @@ #include "chrome/browser/password_manager/bulk_leak_check_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/password_manager/core/browser/ui/insecure_credentials_manager.h" #include "components/password_manager/core/browser/ui/saved_passwords_presenter.h" class PasswordStatusCheckService : public KeyedService, - public password_manager::SavedPasswordsPresenter::Observer, + public password_manager::InsecureCredentialsManager::Observer, public password_manager::BulkLeakCheckServiceInterface::Observer { public: explicit PasswordStatusCheckService(Profile* profile); @@ -55,8 +56,8 @@ void RunPasswordCheckAsync(); // Testing functions. - bool IsObservingSavedPasswordsPresenterForTesting() const { - return saved_passwords_presenter_observation_.IsObserving(); + bool IsObservingInsecureCredentialsManagerForTesting() const { + return insecure_credentials_manager_observation_.IsObserving(); } bool IsObservingBulkLeakCheckForTesting() const { @@ -74,11 +75,10 @@ } private: - // SavedPasswordsPresenter::Observer implementation. - // Getting notified about this indicates that the presenter is initialized - // and ready to be queried for credential issues. - void OnSavedPasswordsChanged( - const password_manager::PasswordStoreChangeList& changes) override; + // InsecureCredentialsManager::Observer implementation. + // Getting notified about this indicates that the presenter is initialized and + // that weak and reuse checks have concluded. + void OnInsecureCredentialsChanged() override; // BulkLeakCheckService::Observer implementation. // This is observed to get notified of the progress of the password check. @@ -119,12 +119,13 @@ // initialized when needed. std::unique_ptr<extensions::PasswordCheckDelegate> password_check_delegate_; - // A scoped observer for `saved_passwords_presenter_`. This is used for - // detecting when `saved_passwords_presenter_` is initialized through - // `OnSavedPasswordsChanged`. - base::ScopedObservation<password_manager::SavedPasswordsPresenter, - password_manager::SavedPasswordsPresenter::Observer> - saved_passwords_presenter_observation_{this}; + // A scoped observer for `InsecureCredentialsManager`. This is used for + // detecting when password issues are available through + // `OnInsecureCredentialsChanged`. + base::ScopedObservation< + password_manager::InsecureCredentialsManager, + password_manager::InsecureCredentialsManager::Observer> + insecure_credentials_manager_observation_{this}; // A scoped observer for `BulkLeakCheckService` which is used by // `PasswordCheckDelegate`. This is used for detecting when password check is
diff --git a/chrome/browser/ui/safety_hub/password_status_check_service_unittest.cc b/chrome/browser/ui/safety_hub/password_status_check_service_unittest.cc index a6da5a2..e76aeb84 100644 --- a/chrome/browser/ui/safety_hub/password_status_check_service_unittest.cc +++ b/chrome/browser/ui/safety_hub/password_status_check_service_unittest.cc
@@ -25,11 +25,14 @@ namespace { constexpr char kTestEmail[] = "user@gmail.com"; -constexpr char kOrigin[] = "https://example.com/"; +constexpr char kOrigin1[] = "https://example1.com/"; +constexpr char kOrigin2[] = "https://example2.com/"; constexpr char16_t kUsername1[] = u"alice"; constexpr char16_t kUsername2[] = u"bob"; constexpr char16_t kUsername3[] = u"charlie"; +constexpr char16_t kUsername4[] = u"dora"; constexpr char16_t kPassword[] = u"fnlsr4@cm^mdls@fkspnsg3d"; +constexpr char16_t kWeakPassword[] = u"1234"; using password_manager::BulkLeakCheckDelegateInterface; using password_manager::BulkLeakCheckService; @@ -81,37 +84,24 @@ }; PasswordForm MakeCredential(base::StringPiece16 username, - base::StringPiece16 password) { + base::StringPiece16 password, + std::string origin = kOrigin1, + bool is_leaked = false) { PasswordForm form; form.username_value = username; form.password_value = password; - form.signon_realm = kOrigin; - form.url = GURL(kOrigin); + form.signon_realm = origin; + form.url = GURL(origin); form.in_store = PasswordForm::Store::kProfileStore; - return form; -} - -PasswordForm MakeInsecureCredential(InsecureType type) { - // Use different usernames for different issue types so credentials with these - // issues can be stored in parallel. - base::StringPiece16 username; - switch (type) { - case InsecureType::kWeak: - username = kUsername1; - break; - case InsecureType::kReused: - username = kUsername2; - break; - case InsecureType::kPhished: - case InsecureType::kLeaked: - username = kUsername3; - break; + if (is_leaked) { + // Credential issues for weak and reused are detected automatically and + // don't need to be specified explicitly. + form.password_issues.insert_or_assign( + InsecureType::kLeaked, + password_manager::InsecurityMetadata( + base::Time::Now(), password_manager::IsMuted(false), + password_manager::TriggerBackendNotification(false))); } - PasswordForm form = MakeCredential(username, kPassword); - form.password_issues.insert_or_assign( - type, password_manager::InsecurityMetadata( - base::Time::Now(), password_manager::IsMuted(false), - password_manager::TriggerBackendNotification(false))); return form; } @@ -124,11 +114,23 @@ RunUntilIdle(); } - void StoreCredentialWithIssue(InsecureType type) { - PasswordForm form = MakeInsecureCredential(type); + void StoreUndetectedWeakCredential() { + PasswordForm form = MakeCredential(kUsername1, kWeakPassword); password_store_->AddLogin(form); } + void StoreLeakedCredential() { + PasswordForm form = MakeCredential(kUsername2, kPassword, kOrigin1, true); + password_store_->AddLogin(form); + } + + void StoreUndetectedReusedCredentials() { + PasswordForm form1 = MakeCredential(kUsername3, kPassword); + PasswordForm form2 = MakeCredential(kUsername4, kPassword, kOrigin2); + password_store_->AddLogin(form1); + password_store_->AddLogin(form2); + } + void StoreCredential(base::StringPiece16 username, base::StringPiece16 password) { PasswordForm form = MakeCredential(username, password); @@ -164,7 +166,7 @@ void ExpectInfrastructureUninitialized() { EXPECT_FALSE(service()->GetSavedPasswordsPresenterForTesting()); EXPECT_FALSE(service()->GetPasswordCheckDelegateForTesting()); - EXPECT_FALSE(service()->IsObservingSavedPasswordsPresenterForTesting()); + EXPECT_FALSE(service()->IsObservingInsecureCredentialsManagerForTesting()); EXPECT_FALSE(service()->IsObservingBulkLeakCheckForTesting()); EXPECT_FALSE(service()->is_password_check_running()); EXPECT_FALSE(service()->is_update_credential_count_pending()); @@ -209,13 +211,13 @@ GetPreexistingMultipleIssueCounts) { // Based on test parameters, add different credential issues to the store. if (include_weak()) { - StoreCredentialWithIssue(InsecureType::kWeak); + StoreUndetectedWeakCredential(); } if (include_compromised()) { - StoreCredentialWithIssue(InsecureType::kLeaked); + StoreLeakedCredential(); } if (include_reused()) { - StoreCredentialWithIssue(InsecureType::kReused); + StoreUndetectedReusedCredentials(); } // Service is restarted and existing issues are found during construction. @@ -223,19 +225,19 @@ EXPECT_EQ(service()->weak_credential_count(), include_weak() ? 1UL : 0UL); EXPECT_EQ(service()->compromised_credential_count(), include_compromised() ? 1UL : 0UL); - EXPECT_EQ(service()->reused_credential_count(), include_reused() ? 1UL : 0UL); + EXPECT_EQ(service()->reused_credential_count(), include_reused() ? 2UL : 0UL); } TEST_P(PasswordStatusCheckServiceParameterizedTest, GetMultipleIssueCounts) { // Based on test parameters, add different credential issues to the store. if (include_weak()) { - StoreCredentialWithIssue(InsecureType::kWeak); + StoreUndetectedWeakCredential(); } if (include_compromised()) { - StoreCredentialWithIssue(InsecureType::kLeaked); + StoreLeakedCredential(); } if (include_reused()) { - StoreCredentialWithIssue(InsecureType::kReused); + StoreUndetectedReusedCredentials(); } // Expect to find credential issues that were added while service is active. @@ -243,7 +245,7 @@ EXPECT_EQ(service()->weak_credential_count(), include_weak() ? 1UL : 0UL); EXPECT_EQ(service()->compromised_credential_count(), include_compromised() ? 1UL : 0UL); - EXPECT_EQ(service()->reused_credential_count(), include_reused() ? 1UL : 0UL); + EXPECT_EQ(service()->reused_credential_count(), include_reused() ? 2UL : 0UL); } TEST_F(PasswordStatusCheckServiceBaseTest, RepeatedlyUpdatingDoesNotCrash) {
diff --git a/chrome/browser/ui/signin/signin_view_controller.cc b/chrome/browser/ui/signin/signin_view_controller.cc index 5a30955..4aa5ec1 100644 --- a/chrome/browser/ui/signin/signin_view_controller.cc +++ b/chrome/browser/ui/signin/signin_view_controller.cc
@@ -55,21 +55,6 @@ #if BUILDFLAG(ENABLE_DICE_SUPPORT) -// Returns the sign-in reason for |mode|. -signin_metrics::Reason GetSigninReasonFromMode(profiles::BubbleViewMode mode) { - switch (mode) { - case profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN: - return signin_metrics::Reason::kSigninPrimaryAccount; - case profiles::BUBBLE_VIEW_MODE_GAIA_ADD_ACCOUNT: - return signin_metrics::Reason::kAddSecondaryAccount; - case profiles::BUBBLE_VIEW_MODE_GAIA_REAUTH: - return signin_metrics::Reason::kReauthentication; - default: - NOTREACHED(); - return signin_metrics::Reason::kUnknownReason; - } -} - // Opens a new tab on |url| or reuses the current tab if it is the NTP. void ShowTabOverwritingNTP(Browser* browser, const GURL& url) { NavigateParams params(browser, url, ui::PAGE_TRANSITION_AUTO_BOOKMARK); @@ -158,22 +143,15 @@ } #if BUILDFLAG(ENABLE_DICE_SUPPORT) -void SigninViewController::ShowSignin(profiles::BubbleViewMode mode, - signin_metrics::AccessPoint access_point, +void SigninViewController::ShowSignin(signin_metrics::AccessPoint access_point, const GURL& redirect_url) { Profile* profile = browser_->profile(); - std::string email; - signin_metrics::Reason signin_reason = GetSigninReasonFromMode(mode); signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); - if (signin_reason == signin_metrics::Reason::kReauthentication) { - email = identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSync) - .email; - } signin_metrics::PromoAction promo_action = GetPromoActionForNewAccount(identity_manager); - ShowDiceSigninTab(signin_reason, access_point, promo_action, email, - redirect_url); + ShowDiceSigninTab(signin_metrics::Reason::kSigninPrimaryAccount, access_point, + promo_action, /*email_hint=*/std::string(), redirect_url); } void SigninViewController::ShowModalInterceptFirstRunExperienceDialog(
diff --git a/chrome/browser/ui/signin/signin_view_controller.h b/chrome/browser/ui/signin/signin_view_controller.h index de9c75a0..1f0ddcf 100644 --- a/chrome/browser/ui/signin/signin_view_controller.h +++ b/chrome/browser/ui/signin/signin_view_controller.h
@@ -13,7 +13,6 @@ #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/signin/signin_modal_dialog.h" #include "chrome/browser/ui/webui/signin/signin_utils.h" #include "chrome/common/url_constants.h" @@ -77,8 +76,7 @@ // |access_point| indicates the access point used to open the Gaia sign in // page. // DEPRECATED: Use ShowDiceEnableSyncTab instead. - void ShowSignin(profiles::BubbleViewMode mode, - signin_metrics::AccessPoint access_point, + void ShowSignin(signin_metrics::AccessPoint access_point, const GURL& redirect_url = GURL(chrome::kChromeUINewTabURL)); // Shows a Chrome Sync signin tab. |email_hint| may be empty.
diff --git a/chrome/browser/ui/signin/signin_view_controller_interactive_uitest.cc b/chrome/browser/ui/signin/signin_view_controller_interactive_uitest.cc index ca7ea04..28e8e6b 100644 --- a/chrome/browser/ui/signin/signin_view_controller_interactive_uitest.cc +++ b/chrome/browser/ui/signin/signin_view_controller_interactive_uitest.cc
@@ -94,7 +94,6 @@ IN_PROC_BROWSER_TEST_F(SignInViewControllerBrowserTest, Accelerators) { ASSERT_EQ(1, browser()->tab_strip_model()->count()); browser()->signin_view_controller()->ShowSignin( - profiles::BUBBLE_VIEW_MODE_GAIA_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); ui_test_utils::TabAddedWaiter wait_for_new_tab(browser());
diff --git a/chrome/browser/ui/views/borealis/borealis_installer_error_dialog.cc b/chrome/browser/ui/views/borealis/borealis_installer_error_dialog.cc index 400990a..2da23ee4 100644 --- a/chrome/browser/ui/views/borealis/borealis_installer_error_dialog.cc +++ b/chrome/browser/ui/views/borealis/borealis_installer_error_dialog.cc
@@ -11,7 +11,7 @@ #include "ash/public/cpp/shelf_types.h" #include "ash/public/cpp/window_properties.h" #include "ash/webui/settings/public/constants/routes.mojom.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ash/borealis/borealis_features.h" #include "chrome/browser/ash/borealis/borealis_metrics.h"
diff --git a/chrome/browser/ui/views/content_setting_site_row_view.h b/chrome/browser/ui/views/content_setting_site_row_view.h index cd869b7..96186b6d 100644 --- a/chrome/browser/ui/views/content_setting_site_row_view.h +++ b/chrome/browser/ui/views/content_setting_site_row_view.h
@@ -5,8 +5,8 @@ #ifndef CHROME_BROWSER_UI_VIEWS_CONTENT_SETTING_SITE_ROW_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_CONTENT_SETTING_SITE_ROW_VIEW_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" #include "base/task/cancelable_task_tracker.h" #include "net/base/schemeful_site.h" #include "ui/base/metadata/metadata_header_macros.h"
diff --git a/chrome/browser/ui/views/location_bar/content_setting_image_view.h b/chrome/browser/ui/views/location_bar/content_setting_image_view.h index e5cd8aa..c59e80e 100644 --- a/chrome/browser/ui/views/location_bar/content_setting_image_view.h +++ b/chrome/browser/ui/views/location_bar/content_setting_image_view.h
@@ -7,7 +7,6 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/memory/raw_ptr.h" #include "chrome/browser/ui/content_settings/content_setting_image_model.h" #include "chrome/browser/ui/content_settings/content_setting_image_model_states.h"
diff --git a/chrome/browser/ui/views/profiles/profile_menu_coordinator.cc b/chrome/browser/ui/views/profiles/profile_menu_coordinator.cc index a315cdc5..9aefd8bf 100644 --- a/chrome/browser/ui/views/profiles/profile_menu_coordinator.cc +++ b/chrome/browser/ui/views/profiles/profile_menu_coordinator.cc
@@ -50,8 +50,7 @@ std::make_unique<IncognitoMenuView>(avatar_toolbar_button, &browser); } else { #if BUILDFLAG(IS_CHROMEOS_ASH) - // Note: on Ash, Guest Sessions have incognito profiles, and use - // BUBBLE_VIEW_MODE_INCOGNITO. + // Note: on Ash, Guest Sessions have incognito profiles. NOTREACHED_NORETURN() << "The profile menu is not implemented on Ash."; #else bubble = std::make_unique<ProfileMenuView>(avatar_toolbar_button, &browser);
diff --git a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h index 042edf26..db4a135 100644 --- a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h +++ b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.h
@@ -11,7 +11,6 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/signin/signin_view_controller_delegate.h" #include "chrome/browser/ui/webui/signin/enterprise_profile_welcome_ui.h" #include "chrome/browser/ui/webui/signin/signin_utils.h"
diff --git a/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc b/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc index 580280cd..07af7f7f 100644 --- a/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc +++ b/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/i18n/message_formatter.h" +#include "base/memory/raw_ptr.h" #include "base/types/cxx23_to_underlying.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/chrome_layout_provider.h"
diff --git a/chrome/browser/ui/webui/ash/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/ash/login/gaia_screen_handler.cc index b6aebde2..ff777a2 100644 --- a/chrome/browser/ui/webui/ash/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/ash/login/gaia_screen_handler.cc
@@ -183,33 +183,6 @@ // Timeout used to prevent infinite connecting to a flaky network. constexpr base::TimeDelta kConnectingTimeout = base::Seconds(60); -GaiaScreenHandler::GaiaScreenMode GetGaiaScreenMode(const std::string& email) { - int authentication_behavior = 0; - CrosSettings::Get()->GetInteger(kLoginAuthenticationBehavior, - &authentication_behavior); - if (authentication_behavior == - em::LoginAuthenticationBehaviorProto::SAML_INTERSTITIAL) { - if (email.empty()) - return GaiaScreenHandler::GAIA_SCREEN_MODE_SAML_REDIRECT; - - user_manager::KnownUser known_user(g_browser_process->local_state()); - // If there's a populated email, we must check first that this user is using - // SAML in order to decide whether to show the interstitial page. - const user_manager::User* user = - user_manager::UserManager::Get()->FindUser(known_user.GetAccountId( - email, std::string() /* id */, AccountType::UNKNOWN)); - - // TODO(b/259675128): we shouldn't rely on `user->using_saml()` when - // deciding which IdP page to show because this flag can be outdated. Admin - // could have changed the IdP to GAIA since last authentication and we - // wouldn't know about it. - if (user && user->using_saml()) - return GaiaScreenHandler::GAIA_SCREEN_MODE_SAML_REDIRECT; - } - - return GaiaScreenHandler::GAIA_SCREEN_MODE_DEFAULT; -} - std::string GetEnterpriseDomainManager() { policy::BrowserPolicyConnectorAsh* connector = g_browser_process->platform_part()->browser_policy_connector_ash(); @@ -1643,4 +1616,35 @@ CallExternalAPI("setQuickStartEnabled"); } +// static +GaiaScreenHandler::GaiaScreenMode GaiaScreenHandler::GetGaiaScreenMode( + const std::string& email) { + int authentication_behavior = 0; + CrosSettings::Get()->GetInteger(kLoginAuthenticationBehavior, + &authentication_behavior); + if (authentication_behavior == + em::LoginAuthenticationBehaviorProto::SAML_INTERSTITIAL) { + if (email.empty()) { + return GaiaScreenHandler::GAIA_SCREEN_MODE_SAML_REDIRECT; + } + + user_manager::KnownUser known_user(g_browser_process->local_state()); + // If there's a populated email, we must check first that this user is using + // SAML in order to decide whether to show the interstitial page. + const user_manager::User* user = + user_manager::UserManager::Get()->FindUser(known_user.GetAccountId( + email, std::string() /* id */, AccountType::UNKNOWN)); + + // TODO(b/259675128): we shouldn't rely on `user->using_saml()` when + // deciding which IdP page to show because this flag can be outdated. Admin + // could have changed the IdP to GAIA since last authentication and we + // wouldn't know about it. + if (user && user->using_saml()) { + return GaiaScreenHandler::GAIA_SCREEN_MODE_SAML_REDIRECT; + } + } + + return GaiaScreenHandler::GAIA_SCREEN_MODE_DEFAULT; +} + } // namespace ash
diff --git a/chrome/browser/ui/webui/ash/login/gaia_screen_handler.h b/chrome/browser/ui/webui/ash/login/gaia_screen_handler.h index 9b9a552a..dbf3c32 100644 --- a/chrome/browser/ui/webui/ash/login/gaia_screen_handler.h +++ b/chrome/browser/ui/webui/ash/login/gaia_screen_handler.h
@@ -184,6 +184,10 @@ // NetworkStateInformer::NetworkStateInformerObserver: void UpdateState(NetworkError::ErrorReason reason) override; + // Returns the initial mode of the Gaia signin screen for a given user email + // address. Note this also affects which Gaia endpoint is used. + static GaiaScreenMode GetGaiaScreenMode(const std::string& email); + void SetNextSamlChallengeKeyHandlerForTesting( std::unique_ptr<SamlChallengeKeyHandler> handler_for_test);
diff --git a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc index 99786cf..26c0369 100644 --- a/chrome/browser/ui/webui/settings/ash/accessibility_section.cc +++ b/chrome/browser/ui/webui/settings/ash/accessibility_section.cc
@@ -467,6 +467,10 @@ return IDS_SETTINGS_ACCESSIBILITY_DISPLAY_AND_MAGNIFICATION_LINK_DESCRIPTION; } +bool IsAccessibilityGameFaceIntegrationEnabled() { + return ::features::IsAccessibilityGameFaceIntegrationEnabled(); +} + } // namespace AccessibilitySection::AccessibilitySection( @@ -1123,6 +1127,9 @@ html_source->AddBoolean("pdfOcrEnabled", base::FeatureList::IsEnabled(::features::kPdfOcr)); + html_source->AddBoolean("isAccessibilityGameFaceIntegrationEnabled", + IsAccessibilityGameFaceIntegrationEnabled()); + ::settings::AddCaptionSubpageStrings(html_source); }
diff --git a/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chrome/browser/ui/webui/welcome/welcome_handler.cc index 55beb3f..4ccccd66 100644 --- a/chrome/browser/ui/webui/welcome/welcome_handler.cc +++ b/chrome/browser/ui/webui/welcome/welcome_handler.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator.h" -#include "chrome/browser/ui/profiles/profile_chooser_constants.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/url_constants.h" #include "components/signin/public/base/signin_metrics.h" @@ -73,7 +72,6 @@ Browser* browser = GetBrowser(); browser->signin_view_controller()->ShowSignin( - profiles::BubbleViewMode::BUBBLE_VIEW_MODE_GAIA_SIGNIN, signin_metrics::AccessPoint::ACCESS_POINT_START_PAGE, redirect_url); } }
diff --git a/chrome/browser/web_applications/BUILD.gn b/chrome/browser/web_applications/BUILD.gn index 20ec366..e26be30 100644 --- a/chrome/browser/web_applications/BUILD.gn +++ b/chrome/browser/web_applications/BUILD.gn
@@ -298,6 +298,8 @@ "commands/install_preloaded_verified_app_command.h", "isolated_web_apps/isolated_web_app_downloader.cc", "isolated_web_apps/isolated_web_app_downloader.h", + "isolated_web_apps/isolated_web_app_update_apply_task.cc", + "isolated_web_apps/isolated_web_app_update_apply_task.h", "isolated_web_apps/isolated_web_app_update_apply_waiter.cc", "isolated_web_apps/isolated_web_app_update_apply_waiter.h", "isolated_web_apps/isolated_web_app_update_discovery_task.cc", @@ -865,8 +867,10 @@ ] if (is_chromeos) { - sources += - [ "commands/install_preloaded_verified_app_command_browsertest.cc" ] + sources += [ + "commands/install_preloaded_verified_app_command_browsertest.cc", + "isolated_web_apps/isolated_web_app_update_manager_browsertest.cc", + ] } if (is_linux) {
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.cc new file mode 100644 index 0000000..bcea0573 --- /dev/null +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.cc
@@ -0,0 +1,70 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h" + +#include <memory> + +#include "base/functional/bind.h" +#include "base/functional/callback.h" +#include "base/json/values_util.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" +#include "base/types/expected.h" +#include "base/values.h" +#include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_apply_update_command.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h" +#include "chrome/browser/web_applications/web_app_command_scheduler.h" +#include "components/keep_alive_registry/scoped_keep_alive.h" + +namespace web_app { + +IsolatedWebAppUpdateApplyTask::IsolatedWebAppUpdateApplyTask( + IsolatedWebAppUrlInfo url_info, + std::unique_ptr<ScopedKeepAlive> optional_keep_alive, + std::unique_ptr<ScopedProfileKeepAlive> optional_profile_keep_alive, + WebAppCommandScheduler& command_scheduler) + : url_info_(std::move(url_info)), + optional_keep_alive_(std::move(optional_keep_alive)), + optional_profile_keep_alive_(std::move(optional_profile_keep_alive)), + command_scheduler_(command_scheduler) { + debug_log_ = base::Value::Dict() + .Set("bundle_id", url_info_.web_bundle_id().id()) + .Set("app_id", url_info_.app_id()); +} + +IsolatedWebAppUpdateApplyTask::~IsolatedWebAppUpdateApplyTask() = default; + +void IsolatedWebAppUpdateApplyTask::Start(CompletionCallback callback) { + CHECK(!has_started_); + has_started_ = true; + callback_ = std::move(callback); + + debug_log_.Set("start_time", base::TimeToValue(base::Time::Now())); + + command_scheduler_->ApplyPendingIsolatedWebAppUpdate( + url_info_, std::move(optional_keep_alive_), + std::move(optional_profile_keep_alive_), + base::BindOnce(&IsolatedWebAppUpdateApplyTask::OnUpdateApplied, + weak_factory_.GetWeakPtr())); +} + +base::Value IsolatedWebAppUpdateApplyTask::AsDebugValue() const { + return base::Value(debug_log_.Clone()); +} + +void IsolatedWebAppUpdateApplyTask::OnUpdateApplied( + base::expected<void, IsolatedWebAppApplyUpdateCommandError> result) { + debug_log_.Set("end_time", base::TimeToValue(base::Time::Now())); + debug_log_.Set("result", result + .transform_error([](const auto& error) { + return "Error: " + error.message; + }) + .error_or("Success")); + + std::move(callback_).Run(result); +} + +} // namespace web_app
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h new file mode 100644 index 0000000..0e5a603 --- /dev/null +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h
@@ -0,0 +1,69 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_WEB_APPLICATIONS_ISOLATED_WEB_APPS_ISOLATED_WEB_APP_UPDATE_APPLY_TASK_H_ +#define CHROME_BROWSER_WEB_APPLICATIONS_ISOLATED_WEB_APPS_ISOLATED_WEB_APP_UPDATE_APPLY_TASK_H_ + +#include <memory> + +#include "base/functional/callback.h" +#include "base/memory/weak_ptr.h" +#include "base/types/expected.h" +#include "base/values.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h" + +class ScopedKeepAlive; +class ScopedProfileKeepAlive; + +namespace web_app { + +struct IsolatedWebAppApplyUpdateCommandError; +class WebAppCommandScheduler; + +// This task is responsible for applying a pending Isolated Web App update by +// calling `WebAppCommandScheduler::ApplyPendingIsolatedWebAppUpdate`. +class IsolatedWebAppUpdateApplyTask { + public: + using CompletionStatus = + base::expected<void, IsolatedWebAppApplyUpdateCommandError>; + using CompletionCallback = base::OnceCallback<void(CompletionStatus status)>; + + IsolatedWebAppUpdateApplyTask( + IsolatedWebAppUrlInfo url_info, + std::unique_ptr<ScopedKeepAlive> optional_keep_alive, + std::unique_ptr<ScopedProfileKeepAlive> optional_profile_keep_alive, + WebAppCommandScheduler& command_scheduler); + ~IsolatedWebAppUpdateApplyTask(); + + IsolatedWebAppUpdateApplyTask(const IsolatedWebAppUpdateApplyTask&) = delete; + IsolatedWebAppUpdateApplyTask& operator=( + const IsolatedWebAppUpdateApplyTask&) = delete; + + void Start(CompletionCallback callback); + + bool has_started() const { return has_started_; } + + const IsolatedWebAppUrlInfo& url_info() const { return url_info_; } + + base::Value AsDebugValue() const; + + private: + void OnUpdateApplied( + base::expected<void, IsolatedWebAppApplyUpdateCommandError> result); + + IsolatedWebAppUrlInfo url_info_; + std::unique_ptr<ScopedKeepAlive> optional_keep_alive_; + std::unique_ptr<ScopedProfileKeepAlive> optional_profile_keep_alive_; + base::raw_ref<WebAppCommandScheduler> command_scheduler_; + + base::Value::Dict debug_log_; + bool has_started_ = false; + CompletionCallback callback_; + + base::WeakPtrFactory<IsolatedWebAppUpdateApplyTask> weak_factory_{this}; +}; + +} // namespace web_app + +#endif // CHROME_BROWSER_WEB_APPLICATIONS_ISOLATED_WEB_APPS_ISOLATED_WEB_APP_UPDATE_APPLY_TASK_H_
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc index 7d5d02a..b0bb9c1b 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc
@@ -8,9 +8,11 @@ #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/json/values_util.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" +#include "base/time/time.h" #include "base/types/expected.h" #include "base/version.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_downloader.h" @@ -94,6 +96,8 @@ has_started_ = true; callback_ = std::move(callback); + debug_log_.Set("start_time", base::TimeToValue(base::Time::Now())); + // TODO(crbug.com/1459160): Once we support updating IWAs not installed via // policy, we need to update this annotation. net::PartialNetworkTrafficAnnotationTag update_manifest_traffic_annotation = @@ -318,12 +322,14 @@ } void IsolatedWebAppUpdateDiscoveryTask::SucceedWith(Success success) { + debug_log_.Set("end_time", base::TimeToValue(base::Time::Now())); debug_log_.Set("result", SuccessToString(success)); VLOG(1) << "Isolated Web App update discovery task succeeded: " << success; std::move(callback_).Run(success); } void IsolatedWebAppUpdateDiscoveryTask::FailWith(Error error) { + debug_log_.Set("end_time", base::TimeToValue(base::Time::Now())); debug_log_.Set("result", ErrorToString(error)); LOG(ERROR) << "Isolated Web App update discovery task failed: " << error; std::move(callback_).Run(base::unexpected(error));
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.cc index 96457b3..2c21cf2 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.cc
@@ -26,7 +26,9 @@ #include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h" #include "chrome/browser/profiles/keep_alive/scoped_profile_keep_alive.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_apply_update_command.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_location.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_waiter.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h" @@ -110,12 +112,12 @@ void IsolatedWebAppUpdateManager::Shutdown() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // Stop all potentially ongoing update discovery tasks and avoid scheduling - // new tasks. + // Stop all potentially ongoing tasks and avoid scheduling new tasks. install_manager_observation_.Reset(); update_discovery_timer_.Stop(); update_discovery_tasks_.clear(); update_apply_waiters_.clear(); + update_apply_tasks_.clear(); } base::Value IsolatedWebAppUpdateManager::AsDebugValue() const { @@ -134,6 +136,11 @@ update_apply_waiters.Append(waiter->AsDebugValue()); } + base::Value::List update_apply_tasks; + for (const auto& task : update_apply_tasks_) { + update_apply_tasks.Append(task->AsDebugValue()); + } + return base::Value( base::Value::Dict() .Set("automatic_updates_enabled", automatic_updates_enabled_) @@ -146,7 +153,9 @@ next_update_check_delta_in_minutes)) .Set("update_discovery_tasks", std::move(update_discovery_tasks)) .Set("update_discovery_log", update_discovery_results_log_.Clone()) - .Set("update_apply_waiters", std::move(update_apply_waiters))); + .Set("update_apply_waiters", std::move(update_apply_waiters)) + .Set("update_apply_tasks", std::move(update_apply_tasks)) + .Set("update_apply_log", update_apply_results_log_.Clone())); } void IsolatedWebAppUpdateManager::SetEnableAutomaticUpdatesForTesting( @@ -172,6 +181,10 @@ } } +void IsolatedWebAppUpdateManager::DiscoverUpdatesNowForTesting() { + QueueUpdateDiscoveryTasks(); +} + bool IsolatedWebAppUpdateManager::IsAnyIWAInstalled() { for (const WebApp& app : provider_->registrar_unsafe().GetApps()) { if (app.isolation_data().has_value()) { @@ -240,7 +253,7 @@ QueueUpdateDiscoveryTask(url_info, update_manifest_url); } - MaybeStartNextUpdateDiscoveryTask(); + MaybeStartNextTask(); } void IsolatedWebAppUpdateManager::QueueUpdateDiscoveryTask( @@ -252,19 +265,27 @@ provider_->registrar_unsafe(), profile_->GetURLLoaderFactory())); } -void IsolatedWebAppUpdateManager::MaybeStartNextUpdateDiscoveryTask() { - if (update_discovery_tasks_.empty()) { +void IsolatedWebAppUpdateManager::MaybeStartNextTask() { + if (IsAnyTaskRunning()) { return; } - const std::unique_ptr<IsolatedWebAppUpdateDiscoveryTask>& next_task = - update_discovery_tasks_.front(); - if (!next_task->has_started()) { - next_task->Start(base::BindOnce( + if (!update_apply_tasks_.empty()) { + update_apply_tasks_.front()->Start( + base::BindOnce(&IsolatedWebAppUpdateManager::OnUpdateApplyTaskCompleted, + // We can use `base::Unretained` here, because `this` + // owns `update_apply_tasks_`. + base::Unretained(this))); + return; + } + + if (!update_discovery_tasks_.empty()) { + update_discovery_tasks_.front()->Start(base::BindOnce( &IsolatedWebAppUpdateManager::OnUpdateDiscoveryTaskCompleted, // We can use `base::Unretained` here, because `this` owns // `update_discovery_tasks_`. base::Unretained(this))); + return; } } @@ -284,6 +305,13 @@ weak_factory_.GetWeakPtr(), url_info)); } +bool IsolatedWebAppUpdateManager::IsAnyTaskRunning() const { + return (!update_apply_tasks_.empty() && + update_apply_tasks_.front()->has_started()) || + (!update_discovery_tasks_.empty() && + update_discovery_tasks_.front()->has_started()); +} + void IsolatedWebAppUpdateManager::OnUpdateDiscoveryTaskCompleted( IsolatedWebAppUpdateDiscoveryTask::CompletionStatus status) { base::Value task_debug_value = @@ -307,7 +335,7 @@ } } - MaybeStartNextUpdateDiscoveryTask(); + MaybeStartNextTask(); } void IsolatedWebAppUpdateManager::OnUpdateApplyWaiterFinished( @@ -316,7 +344,30 @@ std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive) { update_apply_waiters_.erase(url_info.app_id()); - // TODO(cmfcmf): Start task to apply the update here. + update_apply_tasks_.push_back(std::make_unique<IsolatedWebAppUpdateApplyTask>( + url_info, std::move(keep_alive), std::move(profile_keep_alive), + provider_->scheduler())); + + MaybeStartNextTask(); +} + +void IsolatedWebAppUpdateManager::OnUpdateApplyTaskCompleted( + IsolatedWebAppUpdateApplyTask::CompletionStatus status) { + base::Value task_debug_value = update_apply_tasks_.front()->AsDebugValue(); + IsolatedWebAppUrlInfo url_info = update_apply_tasks_.front()->url_info(); + update_apply_tasks_.pop_front(); + + update_apply_results_log_.Append(std::move(task_debug_value)); + if (status.has_value()) { + VLOG(1) << "Applying an Isolated Web App update for " + << url_info.web_bundle_id().id() << " succeeded."; + } else { + LOG(ERROR) << "Applying an Isolated Web App update for " + << url_info.web_bundle_id().id() + << " failed: " << status.error(); + } + + MaybeStartNextTask(); } } // namespace web_app
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h index 09e49c55..18f68e19 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h
@@ -18,6 +18,7 @@ #include "base/time/time.h" #include "base/timer/timer.h" #include "base/values.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_task.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_apply_waiter.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.h" #include "chrome/browser/web_applications/web_app_id.h" @@ -76,6 +77,8 @@ return update_discovery_timer_; } + void DiscoverUpdatesNowForTesting(); + private: bool IsAnyIWAInstalled(); @@ -89,10 +92,11 @@ void CreateUpdateApplyWaiter(const IsolatedWebAppUrlInfo& url_info); - // Starts the next update discovery task if (a) no update discovery task is - // currently running and (b) there is at least one update discovery task in - // the queue. - void MaybeStartNextUpdateDiscoveryTask(); + // Starts the next update apply or discovery task if no other task is + // currently running. + void MaybeStartNextTask(); + + bool IsAnyTaskRunning() const; void OnUpdateDiscoveryTaskCompleted( IsolatedWebAppUpdateDiscoveryTask::CompletionStatus status); @@ -102,6 +106,9 @@ std::unique_ptr<ScopedKeepAlive> keep_alive, std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive); + void OnUpdateApplyTaskCompleted( + IsolatedWebAppUpdateApplyTask::CompletionStatus status); + raw_ref<Profile> profile_; bool automatic_updates_enabled_; @@ -121,6 +128,13 @@ base::flat_map<AppId, std::unique_ptr<IsolatedWebAppUpdateApplyWaiter>> update_apply_waiters_; + // Update apply tasks are executed serially one after each other. Only the + // task at the front of the queue can be running. Once finished, the task will + // be popped from the queue. + base::circular_deque<std::unique_ptr<IsolatedWebAppUpdateApplyTask>> + update_apply_tasks_; + base::Value::List update_apply_results_log_; + base::ScopedObservation<WebAppInstallManager, WebAppInstallManagerObserver> install_manager_observation_{this}; base::WeakPtrFactory<IsolatedWebAppUpdateManager> weak_factory_{this};
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_browsertest.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_browsertest.cc new file mode 100644 index 0000000..bec90ac --- /dev/null +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_browsertest.cc
@@ -0,0 +1,171 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h" + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/strings/strcat.h" +#include "base/strings/string_piece.h" +#include "base/task/sequenced_task_runner.h" +#include "base/test/gmock_expected_support.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_future.h" +#include "base/types/expected.h" +#include "chrome/browser/ui/web_applications/test/isolated_web_app_builder.h" +#include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_location.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_trust_checker.h" +#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h" +#include "chrome/browser/web_applications/isolated_web_apps/policy/isolated_web_app_policy_constants.h" +#include "chrome/browser/web_applications/test/web_app_test_observers.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/common/chrome_features.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_service.h" +#include "content/public/test/browser_test.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace web_app { +namespace { + +using base::test::HasValue; +using ::testing::_; +using ::testing::AllOf; +using ::testing::Eq; +using ::testing::Field; +using ::testing::Optional; +using ::testing::Pointee; +using ::testing::Property; +using ::testing::VariantWith; + +auto WebAppMatches(const auto& untranslated_name_matcher, + const auto& isolation_data_matcher) { + return Pointee(AllOf(Property("untranslated_name", &WebApp::untranslated_name, + untranslated_name_matcher), + Property("isolation_data", &WebApp::isolation_data, + isolation_data_matcher))); +} + +auto IsolationDataMatches(const auto& location_matcher, + const auto& version_matcher, + const auto& pending_update_info_matcher) { + return Optional(AllOf( + Field("location", &WebApp::IsolationData::location, location_matcher), + Field("version", &WebApp::IsolationData::version, version_matcher), + Property("pending_update_info", + &WebApp::IsolationData::pending_update_info, + pending_update_info_matcher))); +} + +auto PendingUpdateInfoMatches(const auto& location_matcher, + const auto& version_matcher) { + return Optional(AllOf( + Field("location", &WebApp::IsolationData::PendingUpdateInfo::location, + location_matcher), + Field("version", &WebApp::IsolationData::PendingUpdateInfo::version, + version_matcher))); +} + +constexpr base::StringPiece kUpdateManifestFileName = "update_manifest.json"; +constexpr base::StringPiece kBundle304FileName = "bundle304.swbn"; +constexpr base::StringPiece kBundle706FileName = "bundle706.swbn"; + +class IsolatedWebAppUpdateManagerBrowserTest + : public IsolatedWebAppBrowserTestHarness { + protected: + void SetUp() override { + scoped_feature_list_.InitAndEnableFeature( + features::kIsolatedWebAppAutomaticUpdates); + SetTrustedWebBundleIdsForTesting({url_info_.web_bundle_id()}); + SetUpFilesAndServer(); + + IsolatedWebAppBrowserTestHarness::SetUp(); + } + + void SetUpFilesAndServer() { + TestSignedWebBundle bundle304 = TestSignedWebBundleBuilder::BuildDefault( + TestSignedWebBundleBuilder::BuildOptions() + .SetAppName("app-3.0.4") + .SetVersion(base::Version("3.0.4"))); + TestSignedWebBundle bundle706 = TestSignedWebBundleBuilder::BuildDefault( + TestSignedWebBundleBuilder::BuildOptions() + .SetAppName("app-7.0.6") + .SetVersion(base::Version("7.0.6"))); + + base::ScopedAllowBlockingForTesting allow_blocking; + EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + iwa_server_.ServeFilesFromDirectory(temp_dir_.GetPath()); + EXPECT_TRUE(iwa_server_.Start()); + + EXPECT_TRUE(base::WriteFile(temp_dir_.GetPath().Append(kBundle304FileName), + bundle304.data)); + EXPECT_TRUE(base::WriteFile(temp_dir_.GetPath().Append(kBundle706FileName), + bundle706.data)); + EXPECT_TRUE(base::WriteFile( + temp_dir_.GetPath().Append(kUpdateManifestFileName), + base::ReplaceStringPlaceholders( + R"( + { + "versions": [ + {"version": "3.0.4", "src": "$1"}, + {"version": "7.0.6", "src": "$2"} + ] + } + )", + {iwa_server_.GetURL(base::StrCat({"/", kBundle304FileName})).spec(), + iwa_server_.GetURL(base::StrCat({"/", kBundle706FileName})) + .spec()}, + /*offsets=*/nullptr))); + } + + base::test::ScopedFeatureList scoped_feature_list_; + IsolatedWebAppUrlInfo url_info_ = + IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( + *web_package::SignedWebBundleId::Create(kTestEd25519WebBundleId)); + base::ScopedTempDir temp_dir_; + net::EmbeddedTestServer iwa_server_; +}; + +IN_PROC_BROWSER_TEST_F(IsolatedWebAppUpdateManagerBrowserTest, Succeeds) { + profile()->GetPrefs()->SetList( + prefs::kIsolatedWebAppInstallForceList, + base::Value::List().Append( + base::Value::Dict() + .Set(kPolicyWebBundleIdKey, url_info_.web_bundle_id().id()) + .Set(kPolicyUpdateManifestUrlKey, + iwa_server_ + .GetURL(base::StrCat({"/", kUpdateManifestFileName})) + .spec()))); + + { + base::test::TestFuture<base::expected<InstallIsolatedWebAppCommandSuccess, + InstallIsolatedWebAppCommandError>> + future; + provider().scheduler().InstallIsolatedWebApp( + url_info_, + InstalledBundle{.path = temp_dir_.GetPath().Append(kBundle304FileName)}, + base::Version("3.0.4"), /*optional_keep_alive=*/nullptr, + /*optional_profile_keep_alive=*/nullptr, future.GetCallback()); + EXPECT_THAT(future.Take(), HasValue()); + } + + WebAppTestManifestUpdatedObserver observer(&provider().install_manager()); + observer.BeginListening({url_info_.app_id()}); + + provider().iwa_update_manager().DiscoverUpdatesNowForTesting(); + observer.Wait(); + + const WebApp* web_app = + provider().registrar_unsafe().GetAppById(url_info_.app_id()); + EXPECT_THAT(web_app, + WebAppMatches("app-7.0.6", IsolationDataMatches( + VariantWith<InstalledBundle>(_), + Eq(base::Version("7.0.6")), + Eq(absl::nullopt)))); +} + +} // namespace +} // namespace web_app
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_unittest.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_unittest.cc index 98a852c0..067ae574 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_unittest.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager_unittest.cc
@@ -5,21 +5,29 @@ #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_manager.h" #include <memory> +#include <string> #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/json/values_util.h" #include "base/memory/scoped_refptr.h" +#include "base/ranges/algorithm.h" #include "base/strings/strcat.h" +#include "base/strings/string_piece.h" #include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" +#include "base/test/values_test_util.h" #include "base/time/time.h" +#include "base/version.h" #include "chrome/browser/ui/web_applications/test/isolated_web_app_builder.h" #include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_location.h" #include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h" #include "chrome/browser/web_applications/isolated_web_apps/policy/isolated_web_app_policy_constants.h" #include "chrome/browser/web_applications/test/fake_web_app_provider.h" +#include "chrome/browser/web_applications/test/fake_web_app_ui_manager.h" #include "chrome/browser/web_applications/test/fake_web_contents_manager.h" #include "chrome/browser/web_applications/test/web_app_install_test_utils.h" #include "chrome/browser/web_applications/test/web_app_test.h" @@ -30,6 +38,8 @@ #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/nacl/common/buildflags.h" +#include "components/web_package/signed_web_bundles/ed25519_public_key.h" +#include "components/web_package/signed_web_bundles/signed_web_bundle_id.h" #include "content/public/common/content_features.h" #include "net/http/http_status_code.h" #include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h" @@ -46,24 +56,28 @@ namespace web_app { namespace { +using base::test::DictionaryHasValue; using ::testing::AllOf; using ::testing::Eq; using ::testing::Field; +using ::testing::IsEmpty; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::NotNull; using ::testing::Optional; using ::testing::Pointee; using ::testing::Property; +using ::testing::SizeIs; blink::mojom::ManifestPtr CreateDefaultManifest(const GURL& application_url, - const base::Version version) { + base::StringPiece16 short_name, + const base::Version& version) { auto manifest = blink::mojom::Manifest::New(); manifest->id = application_url.DeprecatedGetOriginAsURL(); manifest->scope = application_url.Resolve("/"); manifest->start_url = application_url.Resolve("/testing-start-url.html"); manifest->display = DisplayMode::kStandalone; - manifest->short_name = u"updated app"; + manifest->short_name = short_name; manifest->version = base::UTF8ToUTF16(version.GetString()); return manifest; @@ -74,6 +88,34 @@ return arg.DirName() == directory; } +auto WebAppMatches(const auto& untranslated_name_matcher, + const auto& isolation_data_matcher) { + return Pointee(AllOf(Property("untranslated_name", &WebApp::untranslated_name, + untranslated_name_matcher), + Property("isolation_data", &WebApp::isolation_data, + isolation_data_matcher))); +} + +auto IsolationDataMatches(const auto& location_matcher, + const auto& version_matcher, + const auto& pending_update_info_matcher) { + return Optional(AllOf( + Field("location", &WebApp::IsolationData::location, location_matcher), + Field("version", &WebApp::IsolationData::version, version_matcher), + Property("pending_update_info", + &WebApp::IsolationData::pending_update_info, + pending_update_info_matcher))); +} + +auto PendingUpdateInfoMatches(const auto& location_matcher, + const auto& version_matcher) { + return Optional(AllOf( + Field("location", &WebApp::IsolationData::PendingUpdateInfo::location, + location_matcher), + Field("version", &WebApp::IsolationData::PendingUpdateInfo::version, + version_matcher))); +} + #if BUILDFLAG(ENABLE_NACL) class ScopedNaClBrowserDelegate { public: @@ -116,6 +158,10 @@ fake_provider().web_contents_manager()); } + FakeWebAppUiManager& fake_ui_manager() { + return static_cast<FakeWebAppUiManager&>(fake_provider().ui_manager()); + } + base::test::ScopedFeatureList scoped_feature_list_; data_decoder::test::InProcessDataDecoder data_decoder_; #if BUILDFLAG(ENABLE_NACL) @@ -123,34 +169,86 @@ #endif // BUILDFLAG(ENABLE_NACL) }; -class IsolatedWebAppUpdateManagerUpdateDiscoveryTest +class IsolatedWebAppUpdateManagerUpdateTest : public IsolatedWebAppUpdateManagerTest { protected: + struct IwaInfo { + IwaInfo(web_package::WebBundleSigner::KeyPair key_pair, + IsolatedWebAppLocation installed_location, + base::Version installed_version, + GURL update_manifest_url, + GURL update_bundle_url, + base::Version update_version, + std::string update_app_name) + : url_info(IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( + web_package::SignedWebBundleId::CreateForEd25519PublicKey( + key_pair.public_key))), + key_pair(std::move(key_pair)), + installed_location(std::move(installed_location)), + installed_version(std::move(installed_version)), + update_manifest_url(std::move(update_manifest_url)), + update_bundle_url(std::move(update_bundle_url)), + update_version(std::move(update_version)), + update_app_name(std::move(update_app_name)) {} + + IsolatedWebAppUrlInfo url_info; + web_package::WebBundleSigner::KeyPair key_pair; + IsolatedWebAppLocation installed_location; + base::Version installed_version; + + GURL update_manifest_url; + GURL update_bundle_url; + base::Version update_version; + std::string update_app_name; + }; + void SetUp() override { IsolatedWebAppUpdateManagerTest::SetUp(); fake_provider().SetEnableAutomaticIwaUpdates( FakeWebAppProvider::AutomaticIwaUpdateStrategy::kForceEnabled); test::AwaitStartWebAppProviderAndSubsystems(profile()); - base::Version update_version("2.0.0"); - TestSignedWebBundle bundle = TestSignedWebBundleBuilder::BuildDefault( - TestSignedWebBundleBuilder::BuildOptions().SetVersion(update_version)); + iwa_info1_ = IwaInfo( + web_package::WebBundleSigner::KeyPair::CreateRandom(), + InstalledBundle{ + .path = base::FilePath(FILE_PATH_LITERAL("/path/to/iwa1.swbn"))}, + base::Version("1.0.0"), + GURL("https://example.com/update_manifest1.json"), + GURL("https://example.com/bundle1.swbn"), base::Version("2.0.0"), + "updated app 1"); + SetUpIwaInfo(*iwa_info1_); + + iwa_info2_ = IwaInfo( + web_package::WebBundleSigner::KeyPair::CreateRandom(), + InstalledBundle{ + .path = base::FilePath(FILE_PATH_LITERAL("/path/to/iwa2.swbn"))}, + base::Version("4.0.0"), + GURL("https://example.com/update_manifest2.json"), + GURL("https://example.com/bundle2.swbn"), base::Version("7.0.0"), + "updated app 2"); + SetUpIwaInfo(*iwa_info2_); + } + + void SetUpIwaInfo(const IwaInfo& iwa_info) { + TestSignedWebBundle update_bundle = + TestSignedWebBundleBuilder::BuildDefault( + TestSignedWebBundleBuilder::BuildOptions() + .SetVersion(iwa_info.update_version) + .SetKeyPair(iwa_info.key_pair)); profile_url_loader_factory().AddResponse( - "https://example.com/update_manifest.json", + iwa_info.update_manifest_url.spec(), base::ReplaceStringPlaceholders(R"( - { - "versions": [ - { "src": "https://example.com/bundle.swbn", "version": "$1" } - ] - } - )", - {update_version.GetString()}, nullptr)); + { "versions": [ { "src": "$1", "version": "$2" } ] } + )", + {iwa_info.update_bundle_url.spec(), + iwa_info.update_version.GetString()}, + /*offsets=*/nullptr)); profile_url_loader_factory().AddResponse( - "https://example.com/bundle.swbn", - std::string(bundle.data.begin(), bundle.data.end())); + iwa_info.update_bundle_url.spec(), + std::string(update_bundle.data.begin(), update_bundle.data.end())); - GURL install_url = installed_url_info_.origin().GetURL().Resolve( + GURL install_url = iwa_info.url_info.origin().GetURL().Resolve( "/.well-known/_generated_install_page.html"); auto& page_state = @@ -158,114 +256,261 @@ page_state.url_load_result = WebAppUrlLoaderResult::kUrlLoaded; page_state.error_code = webapps::InstallableStatusCode::NO_ERROR_DETECTED; page_state.manifest_url = - installed_url_info_.origin().GetURL().Resolve("manifest.webmanifest"); + iwa_info.url_info.origin().GetURL().Resolve("manifest.webmanifest"); page_state.valid_manifest_for_web_app = true; page_state.opt_manifest = CreateDefaultManifest( - installed_url_info_.origin().GetURL(), update_version); + iwa_info.url_info.origin().GetURL(), + base::UTF8ToUTF16(iwa_info.update_app_name), iwa_info.update_version); } - IsolatedWebAppUrlInfo installed_url_info_ = - IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( - *web_package::SignedWebBundleId::Create( - "4tkrnsmftl4ggvvdkfth3piainqragus2qbhf7rlz2a3wo3rh4wqaaic")); + void SetIwaForceInstallPolicy( + std::vector<std::pair<IsolatedWebAppUrlInfo, base::StringPiece>> + entries) { + base::Value::List list; + for (const auto& [url_info, update_manifest_url] : entries) { + list.Append(base::Value::Dict() + .Set(kPolicyWebBundleIdKey, url_info.web_bundle_id().id()) + .Set(kPolicyUpdateManifestUrlKey, update_manifest_url)); + } + profile()->GetPrefs()->SetList(prefs::kIsolatedWebAppInstallForceList, + std::move(list)); + } - IsolatedWebAppLocation installed_location_ = InstalledBundle{ - .path = base::FilePath(FILE_PATH_LITERAL("/path/to/iwa.swbn"))}; + base::Value debug_log() { + return fake_provider().iwa_update_manager().AsDebugValue(); + } - IsolatedWebAppUrlInfo non_installed_url_info_ = + base::Value::List UpdateDiscoveryLog() { + return debug_log().GetDict().FindList("update_discovery_log")->Clone(); + } + + base::Value::List UpdateApplyLog() { + return debug_log().GetDict().FindList("update_apply_log")->Clone(); + } + + base::Value::List UpdateApplyWaitersLog() { + return debug_log().GetDict().FindList("update_apply_waiters")->Clone(); + } + + auto UpdateLocationMatcher() { + base::FilePath temp_dir; + EXPECT_TRUE(base::GetTempDir(&temp_dir)); + + return VariantWith<InstalledBundle>( + Field("path", &InstalledBundle::path, IsInDir(temp_dir))); + } + + absl::optional<IwaInfo> iwa_info1_; + absl::optional<IwaInfo> iwa_info2_; +}; + +TEST_F(IsolatedWebAppUpdateManagerUpdateTest, + DiscoversAndPreparesUpdateOfPolicyInstalledApps) { + IsolatedWebAppUrlInfo non_installed_url_info = IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( *web_package::SignedWebBundleId::Create( "5tkrnsmftl4ggvvdkfth3piainqragus2qbhf7rlz2a3wo3rh4wqaaic")); - - IsolatedWebAppUrlInfo dev_bundle_url_info_ = + IsolatedWebAppUrlInfo dev_bundle_url_info = IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( *web_package::SignedWebBundleId::Create( "aerugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic")); - - IsolatedWebAppUrlInfo dev_proxy_url_info_ = + IsolatedWebAppUrlInfo dev_proxy_url_info = IsolatedWebAppUrlInfo::CreateFromSignedWebBundleId( web_package::SignedWebBundleId::CreateRandomForDevelopment()); -}; -TEST_F(IsolatedWebAppUpdateManagerUpdateDiscoveryTest, - DiscoversAndPreparesUpdateOfPolicyInstalledApps) { test::InstallDummyWebApp(profile(), "non-iwa", GURL("https://a")); AddDummyIsolatedAppToRegistry( - profile(), installed_url_info_.origin().GetURL(), "installed iwa 1", - WebApp::IsolationData(installed_location_, base::Version("1.0.0"))); + profile(), iwa_info1_->url_info.origin().GetURL(), "installed iwa 1", + WebApp::IsolationData(iwa_info1_->installed_location, + iwa_info1_->installed_version)); AddDummyIsolatedAppToRegistry( - profile(), dev_proxy_url_info_.origin().GetURL(), + profile(), dev_proxy_url_info.origin().GetURL(), "installed iwa 2 (dev mode proxy)", WebApp::IsolationData( - DevModeProxy{.proxy_url = dev_proxy_url_info_.origin()}, + DevModeProxy{.proxy_url = dev_proxy_url_info.origin()}, base::Version("1.0.0"))); AddDummyIsolatedAppToRegistry( - profile(), dev_bundle_url_info_.origin().GetURL(), + profile(), dev_bundle_url_info.origin().GetURL(), "installed iwa 3 (dev mode bundle)", WebApp::IsolationData(DevModeBundle{.path = base::FilePath()}, base::Version("1.0.0"))); AddDummyIsolatedAppToRegistry(profile(), GURL("isolated-app://b"), "installed iwa 4"); - profile()->GetPrefs()->SetList( - prefs::kIsolatedWebAppInstallForceList, - base::Value::List() - .Append(base::Value::Dict() - .Set(kPolicyUpdateManifestUrlKey, - "https://example.com/update_manifest.json") - .Set(kPolicyWebBundleIdKey, - installed_url_info_.web_bundle_id().id())) - .Append(base::Value::Dict() - .Set(kPolicyUpdateManifestUrlKey, - "https://example.com/update_manifest.json") - .Set(kPolicyWebBundleIdKey, - non_installed_url_info_.web_bundle_id().id())) - .Append(base::Value::Dict() - .Set(kPolicyUpdateManifestUrlKey, - "https://example.com/update_manifest.json") - .Set(kPolicyWebBundleIdKey, - dev_bundle_url_info_.web_bundle_id().id())) - .Append(base::Value::Dict() - .Set(kPolicyUpdateManifestUrlKey, - "https://example.com/update_manifest.json") - .Set(kPolicyWebBundleIdKey, - dev_proxy_url_info_.web_bundle_id().id()))); + fake_ui_manager().SetNumWindowsForApp(iwa_info1_->url_info.app_id(), 1); + + SetIwaForceInstallPolicy( + {{iwa_info1_->url_info, iwa_info1_->update_manifest_url.spec()}, + {non_installed_url_info, "https://example.com/update_manifest.json"}, + {dev_bundle_url_info, "https://example.com/update_manifest.json"}, + {dev_proxy_url_info, "https://example.com/update_manifest.json"}}); + task_environment()->FastForwardBy(base::Hours(5)); + task_environment()->RunUntilIdle(); - base::FilePath temp_dir; - EXPECT_TRUE(base::GetTempDir(&temp_dir)); - - const WebApp* web_app = fake_provider().registrar_unsafe().GetAppById( - installed_url_info_.app_id()); - ASSERT_THAT(web_app, NotNull()); - EXPECT_THAT(web_app->untranslated_name(), Eq("installed iwa 1")); EXPECT_THAT( - web_app->isolation_data(), - Optional(AllOf( - Field("location", &WebApp::IsolationData::location, - Eq(installed_location_)), - Field("version", &WebApp::IsolationData::version, - Eq(base::Version("1.0.0"))), - Property( - "pending_update_info", - &WebApp::IsolationData::pending_update_info, - Optional(AllOf( - Field( - "location", - &WebApp::IsolationData::PendingUpdateInfo::location, - VariantWith<InstalledBundle>(Field( - "path", &InstalledBundle::path, IsInDir(temp_dir)))), - Field("version", - &WebApp::IsolationData::PendingUpdateInfo::version, - Eq(base::Version("2.0.0"))))))))); + fake_provider().registrar_unsafe().GetAppById( + iwa_info1_->url_info.app_id()), + WebAppMatches(Eq("installed iwa 1"), + IsolationDataMatches( + Eq(iwa_info1_->installed_location), + Eq(iwa_info1_->installed_version), + PendingUpdateInfoMatches(UpdateLocationMatcher(), + Eq(base::Version("2.0.0")))))); - base::Value debug_value = fake_provider().iwa_update_manager().AsDebugValue(); - base::Value::List* log = - debug_value.GetDict().FindList("update_discovery_log"); - ASSERT_THAT(log, NotNull()); - ASSERT_THAT(log->size(), Eq(1ul)); - EXPECT_THAT(log->front().GetDict().FindString("result"), - Pointee(Eq("Success::kUpdateFoundAndDryRunSuccessful"))); + ASSERT_THAT(UpdateDiscoveryLog(), SizeIs(1)); + EXPECT_THAT( + UpdateDiscoveryLog()[0].GetDict(), + DictionaryHasValue( + "result", base::Value("Success::kUpdateFoundAndDryRunSuccessful"))); + EXPECT_THAT(UpdateApplyLog(), IsEmpty()); + + // Temporary fix for crbug.com/1469880 + fake_provider().Shutdown(); +} + +TEST_F(IsolatedWebAppUpdateManagerUpdateTest, + ApplysUpdatesAfterWindowIsClosed) { + AddDummyIsolatedAppToRegistry( + profile(), iwa_info1_->url_info.origin().GetURL(), "installed app", + WebApp::IsolationData(iwa_info1_->installed_location, + iwa_info1_->installed_version)); + + fake_ui_manager().SetNumWindowsForApp(iwa_info1_->url_info.app_id(), 1); + + SetIwaForceInstallPolicy( + {{iwa_info1_->url_info, iwa_info1_->update_manifest_url.spec()}}); + task_environment()->FastForwardBy(base::Hours(5)); + task_environment()->RunUntilIdle(); + + EXPECT_THAT( + fake_provider().registrar_unsafe().GetAppById( + iwa_info1_->url_info.app_id()), + WebAppMatches(Eq("installed app"), + IsolationDataMatches(Eq(iwa_info1_->installed_location), + Eq(iwa_info1_->installed_version), + PendingUpdateInfoMatches( + UpdateLocationMatcher(), + Eq(iwa_info1_->update_version))))); + + ASSERT_THAT(UpdateDiscoveryLog(), SizeIs(1)); + EXPECT_THAT( + UpdateDiscoveryLog()[0].GetDict(), + DictionaryHasValue( + "result", base::Value("Success::kUpdateFoundAndDryRunSuccessful"))); + EXPECT_THAT(UpdateApplyLog(), IsEmpty()); + + fake_ui_manager().SetNumWindowsForApp(iwa_info1_->url_info.app_id(), 0); + task_environment()->RunUntilIdle(); + + ASSERT_THAT(UpdateApplyLog(), SizeIs(1)); + EXPECT_THAT(UpdateApplyLog()[0].GetDict(), + DictionaryHasValue("result", base::Value("Success"))); + + EXPECT_THAT( + fake_provider().registrar_unsafe().GetAppById( + iwa_info1_->url_info.app_id()), + WebAppMatches(iwa_info1_->update_app_name, + IsolationDataMatches( + UpdateLocationMatcher(), Eq(iwa_info1_->update_version), + /*pending_update_info_matcher=*/Eq(absl::nullopt)))); +} + +TEST_F(IsolatedWebAppUpdateManagerUpdateTest, + ApplysUpdatesWithHigherPriorityThanUpdateDiscovery) { + AddDummyIsolatedAppToRegistry( + profile(), iwa_info1_->url_info.origin().GetURL(), "installed app 1", + WebApp::IsolationData(iwa_info1_->installed_location, + iwa_info1_->installed_version)); + AddDummyIsolatedAppToRegistry( + profile(), iwa_info2_->url_info.origin().GetURL(), "installed app 2", + WebApp::IsolationData(iwa_info2_->installed_location, + iwa_info2_->installed_version)); + + SetIwaForceInstallPolicy( + {{iwa_info1_->url_info, iwa_info1_->update_manifest_url.spec()}, + {iwa_info2_->url_info, iwa_info2_->update_manifest_url.spec()}}); + task_environment()->FastForwardBy(base::Hours(5)); + task_environment()->RunUntilIdle(); + + auto update_discovery_log = UpdateDiscoveryLog(); + auto update_apply_log = UpdateApplyLog(); + + ASSERT_THAT(update_discovery_log, SizeIs(2)); + EXPECT_THAT( + update_discovery_log[0].GetDict(), + DictionaryHasValue( + "result", base::Value("Success::kUpdateFoundAndDryRunSuccessful"))); + EXPECT_THAT( + update_discovery_log[1].GetDict(), + DictionaryHasValue( + "result", base::Value("Success::kUpdateFoundAndDryRunSuccessful"))); + + ASSERT_THAT(update_apply_log, SizeIs(2)); + EXPECT_THAT(update_apply_log[0].GetDict(), + DictionaryHasValue("result", base::Value("Success"))); + EXPECT_THAT(update_apply_log[1].GetDict(), + DictionaryHasValue("result", base::Value("Success"))); + + std::vector<base::Value*> times( + {update_discovery_log[0].GetDict().Find("start_time"), + update_discovery_log[0].GetDict().Find("end_time"), + update_apply_log[0].GetDict().Find("start_time"), + update_apply_log[0].GetDict().Find("end_time"), + + update_discovery_log[1].GetDict().Find("start_time"), + update_discovery_log[1].GetDict().Find("end_time"), + update_apply_log[1].GetDict().Find("start_time"), + update_apply_log[1].GetDict().Find("end_time")}); + EXPECT_THAT(base::ranges::is_sorted( + times, {}, + [](base::Value* value) { return *base::ValueToTime(value); }), + IsTrue()); + + EXPECT_THAT( + fake_provider().registrar_unsafe().GetAppById( + iwa_info1_->url_info.app_id()), + WebAppMatches(iwa_info1_->update_app_name, + IsolationDataMatches( + UpdateLocationMatcher(), Eq(iwa_info1_->update_version), + /*pending_update_info_matcher=*/Eq(absl::nullopt)))); + EXPECT_THAT( + fake_provider().registrar_unsafe().GetAppById( + iwa_info2_->url_info.app_id()), + WebAppMatches(iwa_info2_->update_app_name, + IsolationDataMatches( + UpdateLocationMatcher(), Eq(iwa_info2_->update_version), + /*pending_update_info_matcher=*/Eq(absl::nullopt)))); +} + +TEST_F(IsolatedWebAppUpdateManagerUpdateTest, StopsWaitingIfIwaIsUninstalled) { + AddDummyIsolatedAppToRegistry( + profile(), iwa_info1_->url_info.origin().GetURL(), "installed app", + WebApp::IsolationData(iwa_info1_->installed_location, + iwa_info1_->installed_version)); + + fake_ui_manager().SetNumWindowsForApp(iwa_info1_->url_info.app_id(), 1); + + SetIwaForceInstallPolicy( + {{iwa_info1_->url_info, iwa_info1_->update_manifest_url.spec()}}); + task_environment()->FastForwardBy(base::Hours(5)); + task_environment()->RunUntilIdle(); + + ASSERT_THAT(UpdateDiscoveryLog(), SizeIs(1)); + EXPECT_THAT( + UpdateDiscoveryLog()[0].GetDict(), + DictionaryHasValue( + "result", base::Value("Success::kUpdateFoundAndDryRunSuccessful"))); + + ASSERT_THAT(UpdateApplyWaitersLog(), SizeIs(1)); + EXPECT_THAT( + UpdateApplyWaitersLog()[0].GetDict(), + DictionaryHasValue("app_id", base::Value(iwa_info1_->url_info.app_id()))); + + fake_ui_manager().SetNumWindowsForApp(iwa_info1_->url_info.app_id(), 0); + task_environment()->RunUntilIdle(); + + EXPECT_THAT(UpdateApplyWaitersLog(), IsEmpty()); } class IsolatedWebAppUpdateManagerDiscoveryTimerTest
diff --git a/chrome/browser/web_applications/preinstalled_web_app_window_experiment.h b/chrome/browser/web_applications/preinstalled_web_app_window_experiment.h index 15ff3de..4c705ce7 100644 --- a/chrome/browser/web_applications/preinstalled_web_app_window_experiment.h +++ b/chrome/browser/web_applications/preinstalled_web_app_window_experiment.h
@@ -5,8 +5,8 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_PREINSTALLED_WEB_APP_WINDOW_EXPERIMENT_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_PREINSTALLED_WEB_APP_WINDOW_EXPERIMENT_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/feature_list.h" +#include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/one_shot_event.h" #include "base/scoped_observation.h"
diff --git a/chrome/browser/web_applications/preinstalled_web_app_window_experiment_browsertest.cc b/chrome/browser/web_applications/preinstalled_web_app_window_experiment_browsertest.cc index 6517f9d..6728ed8 100644 --- a/chrome/browser/web_applications/preinstalled_web_app_window_experiment_browsertest.cc +++ b/chrome/browser/web_applications/preinstalled_web_app_window_experiment_browsertest.cc
@@ -9,12 +9,12 @@ #include <string> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/check.h" #include "base/command_line.h" #include "base/containers/flat_set.h" #include "base/functional/bind.h" #include "base/location.h" +#include "base/memory/raw_ptr.h" #include "base/metrics/field_trial_params.h" #include "base/one_shot_event.h" #include "base/run_loop.h"
diff --git a/chrome/browser/web_applications/web_app_sync_bridge.h b/chrome/browser/web_applications/web_app_sync_bridge.h index 64aea11..23e3a0d 100644 --- a/chrome/browser/web_applications/web_app_sync_bridge.h +++ b/chrome/browser/web_applications/web_app_sync_bridge.h
@@ -7,7 +7,6 @@ #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback_forward.h" #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr.h"
diff --git a/chrome/build/android-arm32.pgo.txt b/chrome/build/android-arm32.pgo.txt index f6af8e8..137fd4c 100644 --- a/chrome/build/android-arm32.pgo.txt +++ b/chrome/build/android-arm32.pgo.txt
@@ -1 +1 @@ -chrome-android32-main-1692596869-76b9d8e70636a4a1a97d86caa1f9a955128d0a66.profdata +chrome-android32-main-1692618364-ace317e23b123701b7ed2602e5c7e8dcbc3ede3a.profdata
diff --git a/chrome/build/android-arm64.pgo.txt b/chrome/build/android-arm64.pgo.txt index cde8f3a..298ff28 100644 --- a/chrome/build/android-arm64.pgo.txt +++ b/chrome/build/android-arm64.pgo.txt
@@ -1 +1 @@ -chrome-android64-main-1692596869-79c3df77f0d601aae795d69e66f9acacbd69bca4.profdata +chrome-android64-main-1692618364-f69a95af5428fc8605ae5367cc00256c30e30550.profdata
diff --git a/chrome/build/lacros64.pgo.txt b/chrome/build/lacros64.pgo.txt index 8eb579f..c72fbd5 100644 --- a/chrome/build/lacros64.pgo.txt +++ b/chrome/build/lacros64.pgo.txt
@@ -1 +1 @@ -chrome-chromeos-amd64-generic-main-1692576345-facc27fd89f0805843309e69dc96fe0e71d0b953.profdata +chrome-chromeos-amd64-generic-main-1692618364-a02bf6b412a1fcb23c2b63629bf3f1b3d9b11b5e.profdata
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index d950621..5c34de2 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1692553716-c146fe7b4f847c546d6fded94c8812cd9fa0293a.profdata +chrome-linux-main-1692596869-7c30e1a8ca25dd0c6f4072c555ff7cd0352d16f5.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 4ddd77b..6ffd6a68 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1692590061-559cd5543569a9acb873ba321a4462a420be5e34.profdata +chrome-mac-arm-main-1692611963-c583e278a63a71d33067f4b3a750cf9f6e4ceb6f.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 53891293..2881725d 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1692574818-12a2caccd95a0c92f6259ce9f5eb79d040ec9a62.profdata +chrome-mac-main-1692596869-568d0e1eff3ba6fa61f8c1c0ae9ebd0fae5170eb.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 39c28c66..d2fd4d0 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1692574818-691e5b61fe4deecd441f61d7dd8fd21d4004b00e.profdata +chrome-win32-main-1692608345-2ed8edefaa4c449a2347e6b954759cd98fd5167d.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index be20fa6..6a46940 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1692585803-83ac267502d76f5a9a0293d0f971b2d1311d30c0.profdata +chrome-win64-main-1692608345-9177a0cfe798e9fdfa934f52ec332f2acb31f1bd.profdata
diff --git a/chrome/common/extensions/api/accessibility_private.json b/chrome/common/extensions/api/accessibility_private.json index ead4531..83b1439 100644 --- a/chrome/common/extensions/api/accessibility_private.json +++ b/chrome/common/extensions/api/accessibility_private.json
@@ -240,7 +240,7 @@ { "id": "AccessibilityFeature", "type": "string", - "enum": [ "googleTtsLanguagePacks", "dictationContextChecking", "chromevoxSettingsMigration"], + "enum": [ "googleTtsLanguagePacks", "dictationContextChecking", "chromevoxSettingsMigration", "gameFaceIntegration"], "description": "Subset of accessibility features." }, {
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 63e7e9d6..0c2b263e 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -10375,7 +10375,7 @@ if (include_js_tests) { deps += [ "//chrome/test/data/webui:interactive_ui_tests" ] } - if (include_js2gtest_tests) { + if (include_js2gtest_tests && (is_chromeos_ash || enable_print_preview)) { deps += [ "//chrome/test/data/webui:interactive_ui_tests_js_webui" ] }
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index dd1a1b3..3034f54 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -135,6 +135,7 @@ "password_manager/password_manager_focus_test.cc", "settings/settings_focus_test.cc", "side_panel/bookmarks/sp_bookmarks_focus_test.cc", + "support_tool/support_tool_focus_test.cc", "tab_search/tab_search_focus_test.cc", ] @@ -156,26 +157,28 @@ } if (include_js2gtest_tests) { - js2gtest("interactive_ui_tests_js_webui") { - test_type = "webui" + if (is_chromeos_ash || enable_print_preview) { + js2gtest("interactive_ui_tests_js_webui") { + test_type = "webui" - sources = [ "support_tool/support_tool_interactive_ui_test.js" ] + sources = [] - if (is_chromeos_ash) { - sources += [ "cr_focus_row_behavior_interactive_test.js" ] + if (is_chromeos_ash) { + sources += [ "cr_focus_row_behavior_interactive_test.js" ] + } + + if (enable_print_preview) { + sources += [ "print_preview/print_preview_interactive_ui_tests.js" ] + } + + gen_include_files = [ + "polymer_browser_test_base.js", + "polymer_interactive_ui_test.js", + ] + + deps = [ "//chrome/browser/ui" ] + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] } - - if (enable_print_preview) { - sources += [ "print_preview/print_preview_interactive_ui_tests.js" ] - } - - gen_include_files = [ - "polymer_browser_test_base.js", - "polymer_interactive_ui_test.js", - ] - - deps = [ "//chrome/browser/ui" ] - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] } js2gtest("browser_tests_js_webui") {
diff --git a/chrome/test/data/webui/support_tool/support_tool_focus_test.cc b/chrome/test/data/webui/support_tool/support_tool_focus_test.cc new file mode 100644 index 0000000..3495bc66 --- /dev/null +++ b/chrome/test/data/webui/support_tool/support_tool_focus_test.cc
@@ -0,0 +1,30 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/scoped_feature_list.h" +#include "chrome/common/chrome_features.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/test/base/web_ui_mocha_browser_test.h" +#include "content/public/test/browser_test.h" + +class SupportToolTest : public WebUIMochaFocusTest { + protected: + SupportToolTest() { + scoped_feature_list_.InitWithFeatures( + { + features::kSupportTool, + features::kSupportToolScreenshot, + features::kSupportToolCopyTokenButton, + }, + {}); + set_test_loader_host(chrome::kChromeUISupportToolHost); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + +IN_PROC_BROWSER_TEST_F(SupportToolTest, All) { + RunTest("support_tool/support_tool_test.js", "mocha.run()"); +}
diff --git a/chrome/test/data/webui/support_tool/support_tool_interactive_ui_test.js b/chrome/test/data/webui/support_tool/support_tool_interactive_ui_test.js deleted file mode 100644 index 8a7f6b3..0000000 --- a/chrome/test/data/webui/support_tool/support_tool_interactive_ui_test.js +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2021 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -GEN_INCLUDE(['//chrome/test/data/webui/polymer_interactive_ui_test.js']); - -GEN('#include "chrome/common/chrome_features.h"'); -GEN('#include "content/public/test/browser_test.h"'); - -/** Test fixture for Polymer Support Tool element. */ -const SupportToolInteractiveUITest = class extends PolymerInteractiveUITest { - /** @override */ - get browsePreload() { - return 'chrome://support-tool'; - } - - /** @override */ - get webuiHost() { - return 'support-tool'; - } - - /** @override */ - get featureList() { - return { - enabled: [ - 'features::kSupportTool', - 'features::kSupportToolScreenshot', - 'features::kSupportToolCopyTokenButton', - ], - }; - } -}; - -// js2gtest.js requires using var (see crbug/1033337 for details). -// eslint-disable-next-line no-var -var SupportToolTest = class extends SupportToolInteractiveUITest { - /** @override */ - get browsePreload() { - return 'chrome://support-tool/test_loader.html?' + - 'module=support_tool/support_tool_test.js'; - } -}; - -TEST_F('SupportToolTest', 'All', function() { - mocha.run(); -});
diff --git a/chrome/test/interaction/feature_engagement_initialized_observer.h b/chrome/test/interaction/feature_engagement_initialized_observer.h index 97fe6dfa..80e6f3e 100644 --- a/chrome/test/interaction/feature_engagement_initialized_observer.h +++ b/chrome/test/interaction/feature_engagement_initialized_observer.h
@@ -5,7 +5,7 @@ #ifndef CHROME_TEST_INTERACTION_FEATURE_ENGAGEMENT_INITIALIZED_OBSERVER_H_ #define CHROME_TEST_INTERACTION_FEATURE_ENGAGEMENT_INITIALIZED_OBSERVER_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "ui/base/interaction/state_observer.h"
diff --git a/chromeos/ash/components/login/integrity/misconfigured_user_cleaner.h b/chromeos/ash/components/login/integrity/misconfigured_user_cleaner.h index 5566eea..4d3ed4c5 100644 --- a/chromeos/ash/components/login/integrity/misconfigured_user_cleaner.h +++ b/chromeos/ash/components/login/integrity/misconfigured_user_cleaner.h
@@ -5,7 +5,6 @@ #ifndef CHROMEOS_ASH_COMPONENTS_LOGIN_INTEGRITY_MISCONFIGURED_USER_CLEANER_H_ #define CHROMEOS_ASH_COMPONENTS_LOGIN_INTEGRITY_MISCONFIGURED_USER_CLEANER_H_ -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/component_export.h" #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h"
diff --git a/chromeos/ash/services/chromebox_for_meetings/public/mojom/BUILD.gn b/chromeos/ash/services/chromebox_for_meetings/public/mojom/BUILD.gn index b5a8e37..157c44e 100644 --- a/chromeos/ash/services/chromebox_for_meetings/public/mojom/BUILD.gn +++ b/chromeos/ash/services/chromebox_for_meetings/public/mojom/BUILD.gn
@@ -9,7 +9,10 @@ assert(is_chromeos_ash, "Non-ChromeOS builds cannot depend on //ash") mojom("mojom") { - sources = [ "cfm_service_manager.mojom" ] + sources = [ + "cfm_service_manager.mojom", + "xu_camera.mojom", + ] public_deps = [ "//mojo/public/mojom/base" ] @@ -21,7 +24,6 @@ "meet_devices_diagnostics.mojom", "meet_devices_info.mojom", "meet_devices_logger.mojom", - "xu_camera.mojom", ] public_deps += [ "//chromeos/ash/services/cros_healthd/public/mojom" ] }
diff --git a/chromeos/ash/services/secure_channel/pending_connection_manager_impl_unittest.cc b/chromeos/ash/services/secure_channel/pending_connection_manager_impl_unittest.cc index 035d954..916b41d 100644 --- a/chromeos/ash/services/secure_channel/pending_connection_manager_impl_unittest.cc +++ b/chromeos/ash/services/secure_channel/pending_connection_manager_impl_unittest.cc
@@ -7,7 +7,6 @@ #include <memory> #include <sstream> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/containers/contains.h" #include "base/containers/flat_map.h" #include "base/functional/bind.h"
diff --git a/components/allocation_recorder/crash_handler/BUILD.gn b/components/allocation_recorder/crash_handler/BUILD.gn index c4eca45..451f13f 100644 --- a/components/allocation_recorder/crash_handler/BUILD.gn +++ b/components/allocation_recorder/crash_handler/BUILD.gn
@@ -2,10 +2,14 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//third_party/protobuf/proto_library.gni") + source_set("crash_handler") { sources = [ "allocation_recorder_holder.cc", "allocation_recorder_holder.h", + "payload.cc", + "payload.h", "stream_data_source_factory.cc", "stream_data_source_factory.h", "user_stream_data_source.cc", @@ -13,6 +17,7 @@ ] deps = [ + ":memory_operation_report", "//base", "//base:debugging_buildflags", "//components/allocation_recorder/internal", @@ -20,20 +25,27 @@ "//third_party/crashpad/crashpad/minidump", "//third_party/crashpad/crashpad/snapshot", "//third_party/crashpad/crashpad/util", + "//third_party/protobuf:protobuf_lite", ] } +proto_library("memory_operation_report") { + sources = [ "memory_operation_report.proto" ] +} + source_set("unit_tests") { testonly = true sources = [ "allocation_recorder_holder_unittest.cc", + "payload_unittests.cc", "stream_data_source_factory_unittest.cc", "user_stream_data_source_unittest.cc", ] deps = [ ":crash_handler", + ":memory_operation_report", "//base", "//base/test:test_support", "//components/allocation_recorder/internal",
diff --git a/components/allocation_recorder/crash_handler/memory_operation_report.proto b/components/allocation_recorder/crash_handler/memory_operation_report.proto new file mode 100644 index 0000000..e0aa313 --- /dev/null +++ b/components/allocation_recorder/crash_handler/memory_operation_report.proto
@@ -0,0 +1,66 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +syntax = "proto3"; + +option optimize_for = LITE_RUNTIME; + +package allocation_recorder; + +enum OperationType { + // The operation is an allocation. + ALLOCATION = 0; + // The operation is a free. + FREE = 1; + // Present mainly for compatibility with the internal operation type. Entries + // with this type should not make it into this message. + NONE = 2; +} + +// A single frame of the stack trace. +message StackFrame { + uint64 address = 1; +} + +message StackTrace { + repeated StackFrame frames = 1; +} + +message MemoryOperation { + // The type of operation that this operation represents. + OperationType operation_type = 1; + // The affected address. + uint64 address = 2; + // The number of allocated bytes, only set for allocations. + optional uint64 size = 3; + // The stack trace that caused this operation. + StackTrace stack_trace = 4; +} + +message Statistics { + // The total number of memory operations recorded so far. This might be + // different from the number of operations in this report since the recorder + // overwrites old entries. + uint64 total_number_of_operations = 1; + // The total number of collisions that have been encountered. A collision + // happens when two threads concurrently try to record using the same slot. + optional uint64 total_number_of_collisions = 2; +} + +message MemoryOperationReport { + repeated MemoryOperation memory_operations = 1; + Statistics statistics = 2; +} + +message ProcessingFailures { + repeated string messages = 1; +} + +// The main message for the allocation trace recorder. +message Payload { + oneof payload { + MemoryOperationReport operation_report = 1; + ProcessingFailures processing_failures = 2; + } +}
diff --git a/components/allocation_recorder/crash_handler/payload.cc b/components/allocation_recorder/crash_handler/payload.cc new file mode 100644 index 0000000..280ea94 --- /dev/null +++ b/components/allocation_recorder/crash_handler/payload.cc
@@ -0,0 +1,127 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/allocation_recorder/crash_handler/payload.h" + +#include <iterator> +#include <string> + +#include "base/debug/allocation_trace.h" +#include "base/debug/debugging_buildflags.h" +#include "base/strings/stringprintf.h" +#include "components/allocation_recorder/crash_handler/memory_operation_report.pb.h" + +namespace allocation_recorder::crash_handler { +namespace { + +::allocation_recorder::Statistics ConvertRecorderStatistics( + const base::debug::tracer::AllocationTraceRecorderStatistics& + recorder_statistics) { + ::allocation_recorder::Statistics data; + + data.set_total_number_of_operations( + recorder_statistics.total_number_of_allocations); + +#if BUILDFLAG(ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING) + data.set_total_number_of_collisions( + recorder_statistics.total_number_of_collisions); +#endif + + return data; +} + +::allocation_recorder::StackFrame ConvertStackFrame(const void* const frame) { + ::allocation_recorder::StackFrame converted_frame; + + converted_frame.set_address(reinterpret_cast<uint64_t>(frame)); + + return converted_frame; +} + +::allocation_recorder::OperationType ConvertOperationType( + base::debug::tracer::OperationType operation_type) { + switch (operation_type) { + case base::debug::tracer::OperationType::kNone: + return allocation_recorder::OperationType::NONE; + case base::debug::tracer::OperationType::kAllocation: + return allocation_recorder::OperationType::ALLOCATION; + case base::debug::tracer::OperationType::kFree: + return allocation_recorder::OperationType::FREE; + } +} + +::allocation_recorder::StackTrace ConvertCallStack( + const base::debug::tracer::StackTraceContainer& source_trace) { + // We try to copy an _interesting_ section of the original stack trace. For + // this we find the first null entry (aka the top of the stack) and copy the + // n frames before it. + const void* const* const first_null_entry = + std::find(std::begin(source_trace), std::end(source_trace), nullptr); + + ::allocation_recorder::StackTrace data; + + for (const void* const* current_item = std::begin(source_trace); + current_item != first_null_entry; ++current_item) { + data.mutable_frames()->Add(ConvertStackFrame(*current_item)); + } + + return data; +} + +allocation_recorder::MemoryOperation ConvertSingleRecord( + const base::debug::tracer::OperationRecord& src_record) { + allocation_recorder::MemoryOperation data; + + data.set_operation_type(ConvertOperationType(src_record.GetOperationType())); + data.set_address(reinterpret_cast<uint64_t>(src_record.GetAddress())); + if (src_record.GetOperationType() == + base::debug::tracer::OperationType::kAllocation) { + data.set_size(src_record.GetSize()); + } + *(data.mutable_stack_trace()) = ConvertCallStack(src_record.GetStackTrace()); + + return data; +} + +google::protobuf::RepeatedPtrField<allocation_recorder::MemoryOperation> +ConvertMemoryOperations( + const base::debug::tracer::AllocationTraceRecorder& recorder) { + google::protobuf::RepeatedPtrField<allocation_recorder::MemoryOperation> data; + + for (size_t operation_index = 0; operation_index < recorder.size(); + ++operation_index) { + data.Add(ConvertSingleRecord(recorder[operation_index])); + } + + return data; +} +} // namespace + +allocation_recorder::Payload CreatePayloadWithMemoryOperationReport( + const base::debug::tracer::AllocationTraceRecorder& recorder) { + allocation_recorder::Payload full_report; + + *(full_report.mutable_operation_report()->mutable_statistics()) = + ConvertRecorderStatistics(recorder.GetRecorderStatistics()); + + (*full_report.mutable_operation_report()->mutable_memory_operations()) = + ConvertMemoryOperations(recorder); + + return full_report; +} + +allocation_recorder::Payload CreatePayloadWithProcessingFailures( + base::span<const base::StringPiece> error_messages) { + allocation_recorder::Payload full_report; + auto& destination_messages = + *(full_report.mutable_processing_failures()->mutable_messages()); + + for (const auto error_message : error_messages) { + destination_messages.Add(std::string(error_message)); + } + + return full_report; +} + +} // namespace allocation_recorder::crash_handler
diff --git a/components/allocation_recorder/crash_handler/payload.h b/components/allocation_recorder/crash_handler/payload.h new file mode 100644 index 0000000..c271475 --- /dev/null +++ b/components/allocation_recorder/crash_handler/payload.h
@@ -0,0 +1,53 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_ALLOCATION_RECORDER_CRASH_HANDLER_PAYLOAD_H_ +#define COMPONENTS_ALLOCATION_RECORDER_CRASH_HANDLER_PAYLOAD_H_ + +#include "base/containers/span.h" +#include "base/strings/string_piece.h" +#include "components/allocation_recorder/crash_handler/memory_operation_report.pb.h" + +namespace base::debug::tracer { +struct AllocationTraceRecorder; +} // namespace base::debug::tracer + +namespace allocation_recorder::crash_handler { + +// Various functions to create the payload that is included into to the Crashpad +// report. The payload is a Protocol Buffers message. Please see +// memory_operation_report.proto for the exact content and format. + +// Create a payload with the MemoryOperationReport set from the content of the +// passed |recorder|. +allocation_recorder::Payload CreatePayloadWithMemoryOperationReport( + const base::debug::tracer::AllocationTraceRecorder& recorder); + +// Create a payload with the ProcessingFailures set from the passed +// |error_messages|. +allocation_recorder::Payload CreatePayloadWithProcessingFailures( + base::span<const base::StringPiece> error_messages); + +// Create a payload with the ProcessingFailures set from the passed +// |error_message|. +inline allocation_recorder::Payload CreatePayloadWithProcessingFailures( + const base::StringPiece error_message) { + return CreatePayloadWithProcessingFailures( + base::make_span(&error_message, 1ul)); +} + +// Create a payload with the ProcessingFailures set from the passed +// |error_messages|. +template <size_t Extent> +inline allocation_recorder::Payload CreatePayloadWithProcessingFailures( + base::span<const base::StringPiece, Extent> error_messages) { + base::span<const base::StringPiece, base::dynamic_extent> + error_messages_as_dynamic_span = + base::make_span(std::begin(error_messages), Extent); + + return CreatePayloadWithProcessingFailures(error_messages_as_dynamic_span); +} + +} // namespace allocation_recorder::crash_handler +#endif // COMPONENTS_ALLOCATION_RECORDER_CRASH_HANDLER_PAYLOAD_H_
diff --git a/components/allocation_recorder/crash_handler/payload_unittests.cc b/components/allocation_recorder/crash_handler/payload_unittests.cc new file mode 100644 index 0000000..1e42161 --- /dev/null +++ b/components/allocation_recorder/crash_handler/payload_unittests.cc
@@ -0,0 +1,185 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/allocation_recorder/crash_handler/payload.h" + +#include "base/bits.h" +#include "base/containers/span.h" +#include "base/debug/allocation_trace.h" +#include "testing/gtest/include/gtest/gtest.h" + +using base::debug::tracer::AllocationTraceRecorder; +using base::debug::tracer::AllocationTraceRecorderStatistics; +using base::debug::tracer::OperationRecord; +using testing::TestWithParam; + +namespace allocation_recorder::crash_handler { +namespace { + +void CreateFakeAllocationData(AllocationTraceRecorder& recorder, + uint64_t number_of_entries) { + for (uint64_t entry_counter = 0; entry_counter < number_of_entries; + ++entry_counter) { + if (entry_counter & 0x1) { + recorder.OnFree(reinterpret_cast<const void*>(entry_counter)); + } else { + recorder.OnAllocation( + &recorder, entry_counter, + base::allocator::dispatcher::AllocationSubsystem::kPartitionAllocator, + nullptr); + } + } +} + +void VerifyAllocationEntriesAreEqual( + const base::debug::tracer::OperationRecord& source_entry, + const ::allocation_recorder::MemoryOperation& report_entry) { + EXPECT_EQ(reinterpret_cast<uint64_t>(source_entry.GetAddress()), + report_entry.address()); + + if (source_entry.GetOperationType() == + base::debug::tracer::OperationType::kAllocation) { + ASSERT_TRUE(report_entry.has_size()); + EXPECT_EQ(source_entry.GetSize(), report_entry.size()); + } else { + ASSERT_FALSE(report_entry.has_size()); + } + + switch (source_entry.GetOperationType()) { + case base::debug::tracer::OperationType::kAllocation: + EXPECT_EQ(report_entry.operation_type(), + ::allocation_recorder::OperationType::ALLOCATION); + break; + case base::debug::tracer::OperationType::kFree: + EXPECT_EQ(report_entry.operation_type(), + ::allocation_recorder::OperationType::FREE); + break; + case base::debug::tracer::OperationType::kNone: + ASSERT_NE(source_entry.GetOperationType(), + base::debug::tracer::OperationType::kNone); + } + + ASSERT_TRUE(report_entry.has_stack_trace()); + ASSERT_LE(std::ssize(report_entry.stack_trace().frames()), + std::ssize(source_entry.GetStackTrace())); + + const auto& report_frames = report_entry.stack_trace().frames(); + std::vector<const void*> converted_frames; + std::transform(std::begin(report_frames), std::end(report_frames), + std::back_inserter(converted_frames), + [](const allocation_recorder::StackFrame& frame) { + return reinterpret_cast<const void*>(frame.address()); + }); + + const auto [converted_call_stack_mismatch, source_call_stack_mismatch] = + std::mismatch(std::begin(converted_frames), std::end(converted_frames), + std::begin(source_entry.GetStackTrace())); + + ASSERT_EQ(converted_call_stack_mismatch, std::end(converted_frames)); + EXPECT_TRUE(std::all_of(source_call_stack_mismatch, + std::end(source_entry.GetStackTrace()), + [](const void* ptr) { return ptr == nullptr; })); +} + +} // namespace + +class CreatePayloadWithMemoryOperationReportTest : public testing::Test { + public: + AllocationTraceRecorder& GetRecorder() { return *recorder_; } + + private: + // The recorder under test. Depending on number and size of traces, it + // requires quite a lot of space. Therefore, we create it on heap to avoid any + // out-of-stack scenarios. + std::unique_ptr<AllocationTraceRecorder> const recorder_ = + std::make_unique<AllocationTraceRecorder>(); +}; + +TEST_F(CreatePayloadWithMemoryOperationReportTest, Verify) { + constexpr size_t number_of_entries = 1024; + auto& recorder = GetRecorder(); + + CreateFakeAllocationData(recorder, number_of_entries); + + ASSERT_EQ(recorder.size(), number_of_entries); + + const allocation_recorder::Payload payload = + CreatePayloadWithMemoryOperationReport(recorder); + + ASSERT_TRUE(payload.operation_report().has_statistics()); + EXPECT_EQ( + number_of_entries, + payload.operation_report().statistics().total_number_of_operations()); +#if BUILDFLAG(ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING) + ASSERT_TRUE( + payload.operation_report().statistics().has_total_number_of_collisions()); + EXPECT_EQ( + 0ul, + payload.operation_report().statistics().total_number_of_collisions()); +#endif + + ASSERT_TRUE(payload.has_operation_report()); + ASSERT_EQ(static_cast<int>(number_of_entries), + payload.operation_report().memory_operations().size()); + + for (size_t entry_index = 0; entry_index < number_of_entries; ++entry_index) { + const auto& source_entry = recorder[entry_index]; + const auto& converted_entry = + payload.operation_report().memory_operations().at(entry_index); + + VerifyAllocationEntriesAreEqual(source_entry, converted_entry); + } +} + +TEST_F(CreatePayloadWithMemoryOperationReportTest, VerifyErrorDataIsNotSet) { + auto& recorder = GetRecorder(); + + CreateFakeAllocationData(recorder, 8); + + const allocation_recorder::Payload payload = + CreatePayloadWithMemoryOperationReport(recorder); + + EXPECT_FALSE(payload.has_processing_failures()); +} + +TEST(CreatePayloadWithProcessingFailuresTest, VerifySingleMessage) { + const base::StringPiece message = "This is a very important message."; + + const allocation_recorder::Payload payload = + CreatePayloadWithProcessingFailures(message); + + ASSERT_TRUE(payload.has_processing_failures()); + EXPECT_EQ(1, payload.processing_failures().messages().size()); + EXPECT_EQ(message, payload.processing_failures().messages().at(0)); +} + +TEST(CreatePayloadWithProcessingFailuresTest, VerifyMultipleMessages) { + const base::StringPiece messages[] = {"This is a very important message.", + "You'd better not ignore it."}; + + const allocation_recorder::Payload payload = + CreatePayloadWithProcessingFailures(base::make_span(messages)); + + ASSERT_TRUE(payload.has_processing_failures()); + EXPECT_EQ(std::ssize(messages), + payload.processing_failures().messages().size()); + + for (int message_index = 0; const auto& source_message : messages) { + EXPECT_EQ(source_message, + payload.processing_failures().messages().at(message_index)) + << " at index=" << message_index; + ++message_index; + } +} + +TEST(CreatePayloadWithProcessingFailuresTest, VerifyRegularReportDataIsNotSet) { + const base::StringPiece message = "This is a very important message."; + + const allocation_recorder::Payload payload = + CreatePayloadWithProcessingFailures(message); + + EXPECT_FALSE(payload.has_operation_report()); +} + +} // namespace allocation_recorder::crash_handler
diff --git a/components/allocation_recorder/crash_handler/stream_data_source_factory.cc b/components/allocation_recorder/crash_handler/stream_data_source_factory.cc index 0c5d6db..70a0604 100644 --- a/components/allocation_recorder/crash_handler/stream_data_source_factory.cc +++ b/components/allocation_recorder/crash_handler/stream_data_source_factory.cc
@@ -8,58 +8,56 @@ #include <string> #include <utility> -#include "base/check_op.h" +#include "base/debug/allocation_trace.h" #include "base/debug/debugging_buildflags.h" #include "base/strings/string_piece.h" +#include "base/strings/stringprintf.h" +#include "components/allocation_recorder/crash_handler/payload.h" #include "components/allocation_recorder/internal/internal.h" #include "third_party/crashpad/crashpad/minidump/minidump_user_extension_stream_data_source.h" namespace allocation_recorder::crash_handler { namespace { -// Wrap the payload into the report begin and end marker, see -// |internal::kReportMarker|. -class WrappedByHeaderAndFooter final +class StringStreamDataSource final : public crashpad::MinidumpUserExtensionStreamDataSource { public: - template <typename... ArgTypes> - WrappedByHeaderAndFooter(ArgTypes&&... payload_args); - ~WrappedByHeaderAndFooter() override; + StringStreamDataSource(std::string payload, uint32_t stream_type); + ~StringStreamDataSource() override; size_t StreamDataSize() override; bool ReadStreamData(Delegate* delegate) override; private: - const std::string payload_; + std::string payload_; }; -template <typename... ArgTypes> -WrappedByHeaderAndFooter::WrappedByHeaderAndFooter(ArgTypes&&... payload_args) - : crashpad::MinidumpUserExtensionStreamDataSource( - ::allocation_recorder::internal::kStreamDataType), - payload_(std::forward<ArgTypes>(payload_args)...) {} +StringStreamDataSource::StringStreamDataSource(std::string payload, + uint32_t stream_type) + : crashpad::MinidumpUserExtensionStreamDataSource(stream_type), + payload_(std::move(payload)) {} -WrappedByHeaderAndFooter::~WrappedByHeaderAndFooter() = default; +StringStreamDataSource::~StringStreamDataSource() = default; -size_t WrappedByHeaderAndFooter::StreamDataSize() { - return 2 * internal::kLengthOfReportMarker + payload_.length(); +size_t StringStreamDataSource::StreamDataSize() { + return std::size(payload_); } -bool WrappedByHeaderAndFooter::ReadStreamData(Delegate* delegate) { - return delegate->ExtensionStreamDataSourceRead( - internal::kReportMarker, internal::kLengthOfReportMarker) && - delegate->ExtensionStreamDataSourceRead(payload_.c_str(), - payload_.length()) && - delegate->ExtensionStreamDataSourceRead( - internal::kReportMarker, internal::kLengthOfReportMarker); +bool StringStreamDataSource::ReadStreamData(Delegate* delegate) { + return delegate->ExtensionStreamDataSourceRead(std::data(payload_), + std::size(payload_)); } -template <typename... ArgTypes> -std::unique_ptr<WrappedByHeaderAndFooter> MakeWrappedStringStream( - ArgTypes&&... args) { - return std::make_unique<WrappedByHeaderAndFooter>( - std::forward<ArgTypes>(args)...); +std::unique_ptr<StringStreamDataSource> MakeStringStreamDataSource( + std::string payload) { + return std::make_unique<StringStreamDataSource>( + std::move(payload), ::allocation_recorder::internal::kStreamDataType); +} + +bool SerializePayload(const allocation_recorder::Payload& payload, + std::string& destination) { + return payload.SerializeToString(&destination); } } // namespace @@ -69,15 +67,30 @@ std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource> StreamDataSourceFactory::CreateErrorMessage( base::StringPiece error_message) const { - return MakeWrappedStringStream(error_message); + std::string serialized_report; + + if (!SerializePayload(CreatePayloadWithProcessingFailures(error_message), + serialized_report)) { + return MakeStringStreamDataSource(base::StringPrintf( + "Failed to created error message. Original message was '%s'.", + std::data(error_message))); + } + + return MakeStringStreamDataSource(std::move(serialized_report)); } #if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER) std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource> StreamDataSourceFactory::CreateReportStream( - const base::debug::tracer::AllocationTraceRecorder& - allocation_trace_recorder) const { - return CreateErrorMessage("!!REPORT CREATION NOT IMPLEMENTED!!"); + const base::debug::tracer::AllocationTraceRecorder& recorder) const { + std::string serialized_report; + + if (SerializePayload(CreatePayloadWithMemoryOperationReport(recorder), + serialized_report)) { + return MakeStringStreamDataSource(std::move(serialized_report)); + } + + return CreateErrorMessage("Failed to serialize full report."); } #endif
diff --git a/components/allocation_recorder/crash_handler/stream_data_source_factory.h b/components/allocation_recorder/crash_handler/stream_data_source_factory.h index fcda623..8bd966a 100644 --- a/components/allocation_recorder/crash_handler/stream_data_source_factory.h +++ b/components/allocation_recorder/crash_handler/stream_data_source_factory.h
@@ -31,8 +31,8 @@ #if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER) virtual std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource> - CreateReportStream(const base::debug::tracer::AllocationTraceRecorder& - allocation_trace_recorder) const; + CreateReportStream( + const base::debug::tracer::AllocationTraceRecorder& recorder) const; #endif protected:
diff --git a/components/allocation_recorder/crash_handler/stream_data_source_factory_unittest.cc b/components/allocation_recorder/crash_handler/stream_data_source_factory_unittest.cc index 421e445..3c25fb70 100644 --- a/components/allocation_recorder/crash_handler/stream_data_source_factory_unittest.cc +++ b/components/allocation_recorder/crash_handler/stream_data_source_factory_unittest.cc
@@ -7,9 +7,9 @@ #include <vector> #include "base/debug/allocation_trace.h" +#include "components/allocation_recorder/crash_handler/memory_operation_report.pb.h" #include "components/allocation_recorder/internal/internal.h" #include "components/allocation_recorder/testing/crashpad_fake_objects.h" -#include "components/allocation_recorder/testing/mock_objects.h" #include "testing/gtest/include/gtest/gtest.h" using base::debug::tracer::AllocationTraceRecorder; @@ -17,18 +17,17 @@ namespace allocation_recorder::crash_handler { namespace { + class StreamDataSourceFactoryTest : public ::testing::Test { protected: - StreamDataSourceFactory& GetSubjectUnderTest() { return *sut_; } + StreamDataSourceFactory& GetFactory() { return *factory_; } #if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER) - AllocationTraceRecorder& GetOperationTraceRecorder() const { - return *operation_trace_; - } + AllocationTraceRecorder& GetRecorder() const { return *operation_trace_; } #endif private: - const scoped_refptr<StreamDataSourceFactory> sut_ = + const scoped_refptr<StreamDataSourceFactory> factory_ = base::MakeRefCounted<StreamDataSourceFactory>(); #if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER) @@ -38,111 +37,58 @@ }; // Read the message stored in the given stream and return it. -std::vector<uint8_t> ReadMessage( +std::string ReadMessageAsString( const std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource>& stream) { BufferExtensionStreamDataSourceDelegate stream_data_source_delegate; stream->ReadStreamData(&stream_data_source_delegate); - return stream_data_source_delegate.GetMessage(); + const std::vector<uint8_t> message = stream_data_source_delegate.GetMessage(); + + return std::string(reinterpret_cast<const char*>(message.data()), + message.size()); } -// Verify the header and footer of the message match internal::kReportMarker. -// The payload_data will contain begin and end of the payload for further -// verification. -void VerifyMessageHeaderAndFooter( - const std::vector<uint8_t>& received_message, - std::pair<std::vector<uint8_t>::const_iterator, - std::vector<uint8_t>::const_iterator>& payload_data) { - // Assert here as we might continue reading out of bounds with an EXPECT_EQ. - ASSERT_GE(received_message.size(), 2 * internal::kLengthOfReportMarker); - - const auto* const expected_header_begin = - std::cbegin(internal::kReportMarker); - // Do not use std::end to calculate the end of the expected header as this - // would include the terminating 0. - const auto* const expected_header_end = - std::cbegin(internal::kReportMarker) + internal::kLengthOfReportMarker; - - // Check the header. - const auto intro_compare = std::mismatch( - expected_header_begin, expected_header_end, received_message.begin()); - EXPECT_EQ(intro_compare.first, expected_header_end) - << "difference at intro-position=" - << std::distance(expected_header_begin, intro_compare.first) - << ", expected='" << *intro_compare.first << "', found='" - << *intro_compare.second << "'."; - - const auto received_payload_begin = - std::cbegin(received_message) + internal::kLengthOfReportMarker; - const auto received_payload_end = - std::cend(received_message) - internal::kLengthOfReportMarker; - - // Check the footer. - const auto outro_compare = std::mismatch( - expected_header_begin, expected_header_end, received_payload_end); - EXPECT_EQ(outro_compare.first, expected_header_end) - << "difference at outro-position=" - << std::distance(expected_header_begin, outro_compare.first) - << ", expected='" << *outro_compare.first << "', found='" - << *outro_compare.second << "'."; - - payload_data = {received_payload_begin, received_payload_end}; -} - -void VerifyMessageFromStream( +void GetPayloadFromStream( const std::unique_ptr<crashpad::MinidumpUserExtensionStreamDataSource>& stream, - const std::string& expected_payload_param) { + allocation_recorder::Payload& payload) { ASSERT_NE(stream, nullptr); - std::vector<uint8_t> expected_payload; - std::transform( - std::begin(expected_payload_param), std::end(expected_payload_param), - std::back_inserter(expected_payload), - [](std::string::value_type c) { return static_cast<uint8_t>(c); }); + const auto received_message = ReadMessageAsString(stream); - const std::vector<uint8_t> received_message = ReadMessage(stream); - - std::pair<std::vector<uint8_t>::const_iterator, - std::vector<uint8_t>::const_iterator> - payload_range; - - VerifyMessageHeaderAndFooter(received_message, payload_range); - - ASSERT_EQ(std::ssize(expected_payload), - std::distance(payload_range.first, payload_range.second)); - - const auto payload_begin = payload_range.first; - const auto expected_payload_begin = expected_payload.begin(); - const auto expected_payload_end = expected_payload.end(); - const auto message_compare = std::mismatch( - expected_payload_begin, expected_payload_end, payload_begin); - - EXPECT_EQ(message_compare.first, expected_payload_end) - << "difference at payload-position=" - << std::distance(expected_payload_begin, message_compare.first) - << ", expected='" << *message_compare.first << "', found='" - << *message_compare.second << "'."; + ASSERT_TRUE(payload.ParseFromString(received_message)); } + } // namespace TEST_F(StreamDataSourceFactoryTest, VerifyCreateErrorMessage) { - StreamDataSourceFactory& sut = GetSubjectUnderTest(); + StreamDataSourceFactory& factory = GetFactory(); - const char* const error = "A SUPER FATAL ERROR HAPPENED"; + const char* const error = "A fatal error happened."; - VerifyMessageFromStream(sut.CreateErrorMessage(error), error); + allocation_recorder::Payload payload; + + GetPayloadFromStream(factory.CreateErrorMessage(error), payload); + + ASSERT_TRUE(payload.has_processing_failures()); + EXPECT_EQ(1, payload.processing_failures().messages().size()); + EXPECT_EQ(error, payload.processing_failures().messages().at(0)); } #if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER) TEST_F(StreamDataSourceFactoryTest, VerifyCreateReportStream) { - AllocationTraceRecorder& operation_recorder = GetOperationTraceRecorder(); - StreamDataSourceFactory& sut = GetSubjectUnderTest(); + AllocationTraceRecorder& recorder = GetRecorder(); + StreamDataSourceFactory& factory = GetFactory(); - VerifyMessageFromStream(sut.CreateReportStream(operation_recorder), - "!!REPORT CREATION NOT IMPLEMENTED!!"); + allocation_recorder::Payload payload; + + GetPayloadFromStream(factory.CreateReportStream(recorder), payload); + + EXPECT_TRUE(payload.has_operation_report()); + EXPECT_TRUE(payload.operation_report().has_statistics()); + EXPECT_EQ(0, payload.operation_report().memory_operations().size()); } #endif
diff --git a/components/allocation_recorder/internal/internal.h b/components/allocation_recorder/internal/internal.h index 7b6927c..ff5c7e4 100644 --- a/components/allocation_recorder/internal/internal.h +++ b/components/allocation_recorder/internal/internal.h
@@ -28,13 +28,5 @@ // third_party/crashpad/crashpad/minidump/ constexpr uint32_t kStreamDataType = 0x3A5F9C7B; -// The report marker will be written as an intro/outro to make the allocation -// report easier to recognize. -constexpr char kReportMarker[] = - "==== ALLOCATION_RECORDER ====== ALLOCATION_RECORDER ===="; -constexpr size_t kLengthOfReportMarker = - std::char_traits<char>::length(kReportMarker); -static_assert((kLengthOfReportMarker % 4) == 0); - } // namespace allocation_recorder::internal #endif // COMPONENTS_ALLOCATION_RECORDER_INTERNAL_INTERNAL_H_
diff --git a/components/android_autofill/browser/android_autofill_manager.cc b/components/android_autofill/browser/android_autofill_manager.cc index 02c0c6d..04cfa53 100644 --- a/components/android_autofill/browser/android_autofill_manager.cc +++ b/components/android_autofill/browser/android_autofill_manager.cc
@@ -233,7 +233,8 @@ const url::Origin& triggered_origin) { DCHECK_EQ(action_persistence, mojom::AutofillActionPersistence::kFill); driver().FillOrPreviewForm(action_persistence, form, triggered_origin, {}); - + // We do not call OnAutofillProfileOrCreditCardFormFilled() because WebView + // doesn't have AutofillProfile or CreditCard. if (auto* logger = GetEventFormLogger(field_type_group)) { logger->OnDidFillSuggestion(); }
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc index 3e4425d..914576a 100644 --- a/components/autofill/content/browser/content_autofill_driver.cc +++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -529,11 +529,6 @@ }); } -void ContentAutofillDriver::FocusNoLongerOnFormCallback( - bool had_interacted_form) { - autofill_manager_->OnFocusNoLongerOnForm(had_interacted_form); -} - void ContentAutofillDriver::FocusNoLongerOnForm(bool had_interacted_form) { if (!bad_message::CheckFrameNotPrerendering(render_frame_host())) { return; @@ -541,7 +536,7 @@ autofill_router().FocusNoLongerOnForm( this, had_interacted_form, [](ContentAutofillDriver* target, bool had_interacted_form) { - target->FocusNoLongerOnFormCallback(had_interacted_form); + target->autofill_manager_->OnFocusNoLongerOnForm(had_interacted_form); }); } @@ -561,6 +556,9 @@ const FormFieldData& field, const gfx::RectF& bounding_box) { target->autofill_manager_->OnFocusOnFormField(WithNewVersion(form), field, bounding_box); + }, + [](ContentAutofillDriver* target) { + target->autofill_manager_->OnFocusNoLongerOnForm(true); }); }
diff --git a/components/autofill/content/browser/content_autofill_driver.h b/components/autofill/content/browser/content_autofill_driver.h index f731fe1e..3473687 100644 --- a/components/autofill/content/browser/content_autofill_driver.h +++ b/components/autofill/content/browser/content_autofill_driver.h
@@ -197,7 +197,6 @@ void UnsetKeyPressHandler(); // Callbacks that are called also in other functions by ContentAutofillRouter. - void FocusNoLongerOnFormCallback(bool had_interacted_form); void UnsetKeyPressHandlerCallback(); private:
diff --git a/components/autofill/content/browser/content_autofill_router.cc b/components/autofill/content/browser/content_autofill_router.cc index 4b88168e..2ef02ee 100644 --- a/components/autofill/content/browser/content_autofill_router.cc +++ b/components/autofill/content/browser/content_autofill_router.cc
@@ -342,10 +342,9 @@ void (*callback)(ContentAutofillDriver* target, bool had_interacted_form)) { // Suppresses FocusNoLongerOnForm() if the focus has already moved to a // different frame. - LocalFrameToken frame_token( - source->render_frame_host()->GetFrameToken().value()); - if (focused_frame_ != frame_token) + if (focused_frame_ != source->GetFrameToken()) { return; + } // Prevents FocusOnFormField() from calling FocusNoLongerOnForm(). focus_no_longer_on_form_has_fired_ = true; @@ -367,22 +366,20 @@ void (*callback)(ContentAutofillDriver* target, const FormData& form, const FormFieldData& field, - const gfx::RectF& bounding_box)) { + const gfx::RectF& bounding_box), + void (*focus_no_longer_on_form)(ContentAutofillDriver* target)) { FormGlobalId form_id = form.global_id(); form_forest_.UpdateTreeOfRendererForm(std::move(form), source); // Calls FocusNoLongerOnForm() if the focus has already moved from a // different frame and FocusNoLongerOnForm() hasn't been called yet. - LocalFrameToken frame_token( - source->render_frame_host()->GetFrameToken().value()); - if (focused_frame_ != frame_token && !focus_no_longer_on_form_has_fired_) { - ForEachFrame(form_forest_, [&](ContentAutofillDriver* some_driver) { - some_driver->FocusNoLongerOnFormCallback(true); - }); + if (focused_frame_ != source->GetFrameToken() && + !focus_no_longer_on_form_has_fired_) { + ForEachFrame(form_forest_, focus_no_longer_on_form); } // Suppresses late FocusNoLongerOnForm(). - focused_frame_ = frame_token; + focused_frame_ = source->GetFrameToken(); focus_no_longer_on_form_has_fired_ = false; TriggerFormExtractionExcept(source);
diff --git a/components/autofill/content/browser/content_autofill_router.h b/components/autofill/content/browser/content_autofill_router.h index 9ecbcdb4..3cc31e9 100644 --- a/components/autofill/content/browser/content_autofill_router.h +++ b/components/autofill/content/browser/content_autofill_router.h
@@ -236,14 +236,16 @@ bool had_interacted_form, void (*callback)(ContentAutofillDriver* target, bool had_interacted_form)); - void FocusOnFormField(ContentAutofillDriver* source, - FormData form, - const FormFieldData& field, - const gfx::RectF& bounding_box, - void (*callback)(ContentAutofillDriver* target, - const FormData& form, - const FormFieldData& field, - const gfx::RectF& bounding_box)); + void FocusOnFormField( + ContentAutofillDriver* source, + FormData form, + const FormFieldData& field, + const gfx::RectF& bounding_box, + void (*callback)(ContentAutofillDriver* target, + const FormData& form, + const FormFieldData& field, + const gfx::RectF& bounding_box), + void (*focus_no_longer_on_form)(ContentAutofillDriver* target)); void DidFillAutofillFormData(ContentAutofillDriver* source, FormData form, base::TimeTicks timestamp,
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 6ead4eb..8c2b75e5 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -431,7 +431,6 @@ "strike_databases/strike_database_integrator_test_strike_database.h", "suggestions_context.cc", "suggestions_context.h", - "sync_utils.h", "ui/accessory_sheet_data.cc", "ui/accessory_sheet_data.h", "ui/accessory_sheet_enums.h",
diff --git a/components/autofill/core/browser/autocomplete_history_manager_unittest.cc b/components/autofill/core/browser/autocomplete_history_manager_unittest.cc index bc10db8..414efdf 100644 --- a/components/autofill/core/browser/autocomplete_history_manager_unittest.cc +++ b/components/autofill/core/browser/autocomplete_history_manager_unittest.cc
@@ -26,6 +26,7 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_prefs.h" +#include "components/autofill/core/common/autofill_test_utils.h" #include "components/autofill/core/common/form_data.h" #include "components/prefs/testing_pref_service.h" #include "components/version_info/version_info.h" @@ -33,16 +34,17 @@ #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/rect.h" -using testing::_; -using testing::Eq; -using testing::Field; -using testing::Return; -using testing::UnorderedElementsAre; - namespace autofill { namespace { +using test::CreateTestFormField; +using ::testing::_; +using ::testing::Eq; +using ::testing::Field; +using ::testing::Return; +using ::testing::UnorderedElementsAre; + class MockSuggestionsHandler : public AutocompleteHistoryManager::SuggestionsHandler { public: @@ -83,11 +85,10 @@ web_data_service_ = base::MakeRefCounted<MockAutofillWebDataService>(); autocomplete_manager_ = std::make_unique<AutocompleteHistoryManager>(); autocomplete_manager_->Init(web_data_service_, prefs_.get(), false); - test::CreateTestFormField(/*label=*/"", "Some Field Name", "SomePrefix", - "Some Type", &test_field_); - test::CreateTestFormField(/*label=*/"", "Another Field Name", - "AnotherPrefix", "Another Type", - &second_test_field_); + test_field_ = CreateTestFormField(/*label=*/"", "Some Field Name", + "SomePrefix", "Some Type"); + second_test_field_ = CreateTestFormField(/*label=*/"", "Another Field Name", + "AnotherPrefix", "Another Type"); } void TearDown() override { @@ -507,8 +508,8 @@ TEST_F(AutocompleteHistoryManagerTest, DoQuerySuggestionsForMeaninglessFieldNames_FilterSubStringName) { auto suggestions_handler = std::make_unique<MockSuggestionsHandler>(); - test::CreateTestFormField(/*label=*/"", "payment_cvv_info", /*value=*/"", - "Some Type", &test_field_); + test_field_ = CreateTestFormField(/*label=*/"", "payment_cvv_info", + /*value=*/"", "Some Type"); // Only expect a call when the name is not filtered out. EXPECT_CALL(*web_data_service_, @@ -537,8 +538,8 @@ TEST_F(AutocompleteHistoryManagerTest, DoQuerySuggestionsForMeaninglessFieldNames_FilterName) { auto suggestions_handler = std::make_unique<MockSuggestionsHandler>(); - test::CreateTestFormField(/*label=*/"", "input_123", /*value=*/"", - "Some Type", &test_field_); + test_field_ = + CreateTestFormField(/*label=*/"", "input_123", /*value=*/"", "Some Type"); // Only expect a call when the name is not filtered out. EXPECT_CALL(*web_data_service_, @@ -568,8 +569,8 @@ DoQuerySuggestionsForMeaninglessFieldNames_PassNameWithSubstring) { auto suggestions_handler = std::make_unique<MockSuggestionsHandler>(); int mocked_db_query_id = 100; - test::CreateTestFormField(/*label=*/"", "foOTPace", /*value=*/"", "Some Type", - &test_field_); + test_field_ = + CreateTestFormField(/*label=*/"", "foOTPace", /*value=*/"", "Some Type"); std::vector<AutofillEntry> expected_values; @@ -604,8 +605,8 @@ DoQuerySuggestionsForMeaninglessFieldNames_PassName) { auto suggestions_handler = std::make_unique<MockSuggestionsHandler>(); int mocked_db_query_id = 100; - test::CreateTestFormField(/*label=*/"", "addressline_1", /*value=*/"", - "Some Type", &test_field_); + test_field_ = CreateTestFormField(/*label=*/"", "addressline_1", /*value=*/"", + "Some Type"); std::vector<AutofillEntry> expected_values; @@ -1047,8 +1048,8 @@ form.url = GURL("http://myform.com/form.html"); form.action = GURL("http://myform.com/submit.html"); - FormFieldData field; - test::CreateTestFormField("Address", "address", "", "textarea", &field); + FormFieldData field = + CreateTestFormField("Address", "address", "", "textarea"); auto suggestions_handler = std::make_unique<MockSuggestionsHandler>(); EXPECT_CALL(*suggestions_handler.get(),
diff --git a/components/autofill/core/browser/autofill_experiments.cc b/components/autofill/core/browser/autofill_experiments.cc index 02b8332..6e51ad80 100644 --- a/components/autofill/core/browser/autofill_experiments.cc +++ b/components/autofill/core/browser/autofill_experiments.cc
@@ -114,15 +114,17 @@ "yahoo", "ymail"}; -bool IsCreditCardUploadEnabled(const syncer::SyncService* sync_service, - const std::string& user_email, - const std::string& user_country, - const AutofillSyncSigninState sync_state, - LogManager* log_manager) { +bool IsCreditCardUploadEnabled( + const syncer::SyncService* sync_service, + const std::string& user_email, + const std::string& user_country, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + LogManager* log_manager) { if (!sync_service) { // If credit card sync is not active, we're not offering to upload cards. autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kSyncServiceNull, sync_state); + autofill_metrics::CardUploadEnabled::kSyncServiceNull, + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "SYNC_SERVICE_NULL"); return false; } @@ -130,7 +132,8 @@ if (sync_service->GetTransportState() == syncer::SyncService::TransportState::PAUSED) { autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kSyncServicePaused, sync_state); + autofill_metrics::CardUploadEnabled::kSyncServicePaused, + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "SYNC_SERVICE_PAUSED"); return false; } @@ -139,7 +142,7 @@ autofill_metrics::LogCardUploadEnabledMetric( autofill_metrics::CardUploadEnabled:: kSyncServiceMissingAutofillWalletDataActiveType, - sync_state); + signin_state_for_metrics); LogCardUploadDisabled( log_manager, "SYNC_SERVICE_MISSING_AUTOFILL_WALLET_ACTIVE_DATA_TYPE"); return false; @@ -152,7 +155,7 @@ autofill_metrics::LogCardUploadEnabledMetric( autofill_metrics::CardUploadEnabled:: kSyncServiceMissingAutofillProfileActiveType, - sync_state); + signin_state_for_metrics); LogCardUploadDisabled( log_manager, "SYNC_SERVICE_MISSING_AUTOFILL_PROFILE_ACTIVE_DATA_TYPE"); @@ -167,7 +170,7 @@ if (sync_service->GetUserSettings()->IsUsingExplicitPassphrase()) { autofill_metrics::LogCardUploadEnabledMetric( autofill_metrics::CardUploadEnabled::kUsingExplicitSyncPassphrase, - sync_state); + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "USER_HAS_EXPLICIT_SYNC_PASSPHRASE"); return false; } @@ -176,7 +179,8 @@ // won't receive the cards back from Google Payments. if (sync_service->IsLocalSyncEnabled()) { autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kLocalSyncEnabled, sync_state); + autofill_metrics::CardUploadEnabled::kLocalSyncEnabled, + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "USER_ONLY_SYNCING_LOCALLY"); return false; } @@ -184,7 +188,8 @@ // Check that the user's account email address is known. if (user_email.empty()) { autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kEmailEmpty, sync_state); + autofill_metrics::CardUploadEnabled::kEmailEmpty, + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "USER_EMAIL_EMPTY"); return false; } @@ -213,7 +218,7 @@ !using_google_domain) { autofill_metrics::LogCardUploadEnabledMetric( autofill_metrics::CardUploadEnabled::kEmailDomainNotSupported, - sync_state); + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "USER_EMAIL_DOMAIN_NOT_SUPPORTED"); return false; } @@ -223,7 +228,8 @@ // required for the ability to continue to launch to more countries as // necessary. autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kEnabledByFlag, sync_state); + autofill_metrics::CardUploadEnabled::kEnabledByFlag, + signin_state_for_metrics); LogCardUploadEnabled(log_manager); return true; } @@ -234,13 +240,15 @@ if (country_iter == std::end(kAutofillUpstreamLaunchedCountries)) { // |country_code| was not found in the list of launched countries. autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kUnsupportedCountry, sync_state); + autofill_metrics::CardUploadEnabled::kUnsupportedCountry, + signin_state_for_metrics); LogCardUploadDisabled(log_manager, "UNSUPPORTED_COUNTRY"); return false; } autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled::kEnabledForCountry, sync_state); + autofill_metrics::CardUploadEnabled::kEnabledForCountry, + signin_state_for_metrics); LogCardUploadEnabled(log_manager); return true; } @@ -257,7 +265,8 @@ sync_service, personal_data_manager->GetAccountInfoForPaymentsServer().email, personal_data_manager->GetCountryCodeForExperimentGroup(), - personal_data_manager->GetSyncSigninState(), log_manager)) { + personal_data_manager->GetPaymentsSigninStateForMetrics(), + log_manager)) { return false; }
diff --git a/components/autofill/core/browser/autofill_experiments.h b/components/autofill/core/browser/autofill_experiments.h index a48ec45..c169693 100644 --- a/components/autofill/core/browser/autofill_experiments.h +++ b/components/autofill/core/browser/autofill_experiments.h
@@ -9,7 +9,7 @@ #include "base/memory/scoped_refptr.h" #include "build/build_config.h" -#include "components/autofill/core/browser/sync_utils.h" +#include "components/autofill/core/browser/metrics/autofill_metrics.h" class PrefService; @@ -29,11 +29,12 @@ // Returns true if uploading credit cards to Wallet servers is enabled. This // requires the appropriate flags and user settings to be true and the user to // be a member of a supported domain. -bool IsCreditCardUploadEnabled(const syncer::SyncService* sync_service, - const std::string& user_email, - const std::string& user_country, - const AutofillSyncSigninState sync_state, - LogManager* log_manager); +bool IsCreditCardUploadEnabled( + const syncer::SyncService* sync_service, + const std::string& user_email, + const std::string& user_country, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + LogManager* log_manager); // Returns true if autofill local card migration flow is enabled. bool IsCreditCardMigrationEnabled(PersonalDataManager* personal_data_manager,
diff --git a/components/autofill/core/browser/autofill_experiments_unittest.cc b/components/autofill/core/browser/autofill_experiments_unittest.cc index 344858f9..71afe33 100644 --- a/components/autofill/core/browser/autofill_experiments_unittest.cc +++ b/components/autofill/core/browser/autofill_experiments_unittest.cc
@@ -38,21 +38,26 @@ base::MakeRefCounted<MockDeviceAuthenticator>(); } - bool IsCreditCardUploadEnabled(const AutofillSyncSigninState sync_state) { - return IsCreditCardUploadEnabled("john.smith@gmail.com", sync_state); + bool IsCreditCardUploadEnabled( + const AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + return IsCreditCardUploadEnabled("john.smith@gmail.com", + signin_state_for_metrics); } - bool IsCreditCardUploadEnabled(const std::string& user_email, - const AutofillSyncSigninState sync_state) { - return IsCreditCardUploadEnabled(user_email, "US", sync_state); + bool IsCreditCardUploadEnabled( + const std::string& user_email, + const AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + return IsCreditCardUploadEnabled(user_email, "US", + signin_state_for_metrics); } - bool IsCreditCardUploadEnabled(const std::string& user_email, - const std::string& user_country, - const AutofillSyncSigninState sync_state) { - return autofill::IsCreditCardUploadEnabled(&sync_service_, user_email, - user_country, sync_state, - log_manager_.get()); + bool IsCreditCardUploadEnabled( + const std::string& user_email, + const std::string& user_country, + const AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + return autofill::IsCreditCardUploadEnabled( + &sync_service_, user_email, user_country, signin_state_for_metrics, + log_manager_.get()); } base::test::ScopedFeatureList scoped_feature_list_; @@ -74,7 +79,7 @@ // the client-side country check. EXPECT_TRUE(IsCreditCardUploadEnabled( "john.smith@gmail.com", "ZZ", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledByFlag, 1); @@ -87,7 +92,7 @@ // "ZZ" is NOT one of the countries in |kAutofillUpstreamLaunchedCountries|. EXPECT_FALSE(IsCreditCardUploadEnabled( "john.smith@gmail.com", "ZZ", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kUnsupportedCountry, 1); @@ -103,7 +108,7 @@ // "US" is one of the countries in |kAutofillUpstreamLaunchedCountries|. EXPECT_TRUE(IsCreditCardUploadEnabled( "john.smith@gmail.com", "US", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 1); @@ -114,7 +119,8 @@ TEST_F(AutofillExperimentsTest, IsCardUploadEnabled_AuthError) { sync_service_.SetPersistentAuthError(); - EXPECT_FALSE(IsCreditCardUploadEnabled(AutofillSyncSigninState::kSyncPaused)); + EXPECT_FALSE(IsCreditCardUploadEnabled( + AutofillMetrics::PaymentsSigninState::kSyncPaused)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kSyncServicePaused, 1); @@ -129,7 +135,7 @@ /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet()); EXPECT_FALSE(IsCreditCardUploadEnabled( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled:: @@ -150,7 +156,7 @@ syncer::UserSelectableType::kPayments}); sync_service_.SetFailedDataTypes({syncer::AUTOFILL_PROFILE}); EXPECT_FALSE(IsCreditCardUploadEnabled( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled:: @@ -167,7 +173,7 @@ IsCardUploadEnabled_SyncServiceUsingExplicitPassphrase) { sync_service_.SetIsUsingExplicitPassphrase(true); EXPECT_FALSE(IsCreditCardUploadEnabled( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kUsingExplicitSyncPassphrase, 1); @@ -180,7 +186,7 @@ sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, syncer::UserSelectableTypeSet()); EXPECT_FALSE(IsCreditCardUploadEnabled( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled:: @@ -195,7 +201,8 @@ TEST_F(AutofillExperimentsTest, IsCardUploadEnabled_EmptyUserEmail) { EXPECT_FALSE(IsCreditCardUploadEnabled( - "", AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + "", + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEmailEmpty, 1); @@ -211,7 +218,7 @@ EXPECT_TRUE(IsCreditCardUploadEnabled( "john.smith@gmail.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 1); @@ -234,7 +241,7 @@ sync_service_.SetFailedDataTypes({syncer::AUTOFILL_PROFILE}); EXPECT_TRUE(IsCreditCardUploadEnabled( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 1); @@ -247,16 +254,16 @@ IsCardUploadEnabled_UserEmailWithGoogleDomain_IsAllowed) { EXPECT_TRUE(IsCreditCardUploadEnabled( "john.smith@gmail.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "googler@google.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "old.school@googlemail.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "code.committer@chromium.org", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 4); @@ -271,16 +278,16 @@ features::kAutofillUpstreamAllowAdditionalEmailDomains); EXPECT_TRUE(IsCreditCardUploadEnabled( "cool.user@hotmail.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "cool.british.user@hotmail.co.uk", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "telecom.user@verizon.net", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "youve.got.mail@aol.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 4); @@ -298,16 +305,16 @@ features::kAutofillUpstreamAllowAllEmailDomains}); EXPECT_FALSE(IsCreditCardUploadEnabled( "cool.user@hotmail.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "cool.british.user@hotmail.co.uk", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "telecom.user@verizon.net", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "youve.got.mail@aol.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEmailDomainNotSupported, 4); @@ -322,16 +329,16 @@ features::kAutofillUpstreamAllowAllEmailDomains); EXPECT_TRUE(IsCreditCardUploadEnabled( "grad.student@university.edu", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "some.ceo@bigcorporation.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "fake.googler@google.net", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_TRUE(IsCreditCardUploadEnabled( "fake.committer@chromium.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEnabledForCountry, 4); @@ -348,16 +355,16 @@ /*disabled_features=*/{features::kAutofillUpstreamAllowAllEmailDomains}); EXPECT_FALSE(IsCreditCardUploadEnabled( "grad.student@university.edu", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "some.ceo@bigcorporation.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "fake.googler@google.net", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); EXPECT_FALSE(IsCreditCardUploadEnabled( "fake.committer@chromium.com", - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled)); + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); histogram_tester.ExpectUniqueSample( "Autofill.CardUploadEnabled", autofill_metrics::CardUploadEnabled::kEmailDomainNotSupported, 4);
diff --git a/components/autofill/core/browser/autofill_feedback_data_unittest.cc b/components/autofill/core/browser/autofill_feedback_data_unittest.cc index d505dab..f23f56e4 100644 --- a/components/autofill/core/browser/autofill_feedback_data_unittest.cc +++ b/components/autofill/core/browser/autofill_feedback_data_unittest.cc
@@ -15,13 +15,16 @@ #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/browser/test_browser_autofill_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_test_utils.h" #include "components/autofill/core/common/form_data.h" #include "testing/gmock/include/gmock/gmock.h" namespace autofill { namespace { -const char kExpectedFeedbackDataJSON[] = R"({ +using test::CreateTestFormField; + +constexpr char kExpectedFeedbackDataJSON[] = R"({ "formStructures": [ { "formSignature": "4232380759432074174", "hostFrame": "00000000000181CD000000000000A8CA", @@ -33,7 +36,7 @@ "fields": [ { "autocompleteAttribute": "cc-given-name", "fieldSignature": "3879476562", - "fieldType": "HTML_TYPE_CREDIT_CARD_NAME_FIRST", + "fieldType": "NAME_FIRST", "heuristicType": "CREDIT_CARD_NAME_FIRST", "hostFormSignature": "0", "htmlType": "HTML_TYPE_CREDIT_CARD_NAME_FIRST", @@ -54,7 +57,7 @@ }, { "autocompleteAttribute": "cc-family-name", "fieldSignature": "3213606822", - "fieldType": "HTML_TYPE_CREDIT_CARD_NAME_LAST", + "fieldType": "NAME_LAST", "heuristicType": "CREDIT_CARD_NAME_LAST", "hostFormSignature": "0", "htmlType": "HTML_TYPE_CREDIT_CARD_NAME_LAST", @@ -73,12 +76,12 @@ "serverType": "NO_SERVER_DATA", "serverTypeIsOverride": false }, { - "autocompleteAttribute": "cc-family-name", + "autocompleteAttribute": "", "fieldSignature": "1029417091", - "fieldType": "HTML_TYPE_CREDIT_CARD_NAME_LAST", + "fieldType": "EMAIL_ADDRESS", "heuristicType": "EMAIL_ADDRESS", "hostFormSignature": "0", - "htmlType": "HTML_TYPE_CREDIT_CARD_NAME_LAST", + "htmlType": "HTML_TYPE_UNSPECIFIED", "idAttribute": "", "isEmpty": true, "isFocusable": true, @@ -90,35 +93,33 @@ "rankInHostForm": "2", "rankInHostFormSignatureGroup": "0", "rankInSignatureGroup": "0", - "section": "firstnameoncard_0_11", + "section": "email_0_13", "serverType": "NO_SERVER_DATA", "serverTypeIsOverride": false } ] } ] })"; -void CreateFeedbackTestFormData(FormData* form) { - form->host_frame = test::MakeLocalFrameToken(test::RandomizeFrame(false)); - form->unique_renderer_id = test::MakeFormRendererId(); - form->name = u"MyForm"; - form->url = GURL("https://myform.com/form.html"); - form->action = GURL("https://myform.com/submit.html"); - form->main_frame_origin = +FormData CreateFeedbackTestFormData() { + FormData form; + form.host_frame = test::MakeLocalFrameToken(test::RandomizeFrame(false)); + form.unique_renderer_id = test::MakeFormRendererId(); + form.name = u"MyForm"; + form.url = GURL("https://myform.com/form.html"); + form.action = GURL("https://myform.com/submit.html"); + form.main_frame_origin = url::Origin::Create(GURL("https://myform_root.com/form.html")); - - FormFieldData field; - test::CreateTestFormField("First Name on Card", "firstnameoncard", "", "text", - "cc-given-name", &field); - field.host_frame = form->host_frame; - form->fields.push_back(field); - test::CreateTestFormField("Last Name on Card", "lastnameoncard", "", "text", - "cc-family-name", &field); - field.host_frame = form->host_frame; - form->fields.push_back(field); - test::CreateTestFormField("Email", "email", "", "email", &field); - field.host_frame = form->host_frame; - form->fields.push_back(field); + form.fields = {CreateTestFormField("First Name on Card", "firstnameoncard", + "", "text", "cc-given-name"), + CreateTestFormField("Last Name on Card", "lastnameoncard", "", + "text", "cc-family-name"), + CreateTestFormField("Email", "email", "", "email")}; + for (FormFieldData& field : form.fields) { + field.host_frame = form.host_frame; + } + return form; } + } // namespace class AutofillFeedbackDataUnitTest : public testing::Test { @@ -143,8 +144,7 @@ }; TEST_F(AutofillFeedbackDataUnitTest, CreatesCompleteReport) { - FormData form; - CreateFeedbackTestFormData(&form); + FormData form = CreateFeedbackTestFormData(); browser_autofill_manager_->OnFormsSeen( /*updated_forms=*/{form}, /*removed_forms=*/{}); @@ -162,8 +162,7 @@ } TEST_F(AutofillFeedbackDataUnitTest, IncludesLastAutofillEventLogEntry) { - FormData form; - CreateFeedbackTestFormData(&form); + FormData form = CreateFeedbackTestFormData(); FormFieldData field = form.fields[0]; browser_autofill_manager_->OnFormsSeen( /*updated_forms=*/{form}, @@ -195,9 +194,8 @@ TEST_F(AutofillFeedbackDataUnitTest, NotIncludeLastAutofillEventIfExceedTimeLimit) { TestAutofillClock clock(AutofillClock::Now()); - FormData form; - CreateFeedbackTestFormData(&form); - FormFieldData field = form.fields[0]; + FormData form = CreateFeedbackTestFormData(); + FormFieldData& field = form.fields[0]; browser_autofill_manager_->OnFormsSeen( /*updated_forms=*/{form}, /*removed_forms=*/{}); @@ -223,8 +221,7 @@ } TEST_F(AutofillFeedbackDataUnitTest, IncludesExtraLogs) { - FormData form; - CreateFeedbackTestFormData(&form); + FormData form = CreateFeedbackTestFormData(); browser_autofill_manager_->OnFormsSeen( /*updated_forms=*/{form}, /*removed_forms=*/{});
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index bebb515..bd7cf7d 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -315,6 +315,16 @@ OnFormSubmittedImpl(form, known_success, source); } +void AutofillManager::OnAutofillProfileOrCreditCardFormFilled( + autofill::FormGlobalId form, + base::span<const std::pair<const FormFieldData*, const AutofillField*>> + filled_fields, + absl::variant<const AutofillProfile*, const CreditCard*> + profile_or_credit_card) { + NotifyObservers(&Observer::OnAutofillProfileOrCreditCardFormFilled, form, + filled_fields, profile_or_credit_card); +} + void AutofillManager::OnFormsSeen( const std::vector<FormData>& updated_forms, const std::vector<FormGlobalId>& removed_forms) {
diff --git a/components/autofill/core/browser/autofill_manager.h b/components/autofill/core/browser/autofill_manager.h index 8f10d43..dec8503 100644 --- a/components/autofill/core/browser/autofill_manager.h +++ b/components/autofill/core/browser/autofill_manager.h
@@ -42,6 +42,8 @@ namespace autofill { class AutofillField; +class AutofillProfile; +class CreditCard; class CreditCardAccessManager; struct FormData; struct FormFieldData; @@ -137,7 +139,21 @@ FormGlobalId form, FieldTypeSource source) {} - virtual void OnFormSubmitted(AutofillManager& manager, FormGlobalId) {} + // Fired when form is filled. + // 'filled_fields' represents the fields that were actually sent to the + // renderer to be filled. `profile_or_credit_card` gives the information for + // which values were used to fill the form, being those either from credit + // card or an autofill profile. + // TODO(crbug.com/1331312): Get rid of FormFieldData. + virtual void OnAutofillProfileOrCreditCardFormFilled( + AutofillManager& manager, + autofill::FormGlobalId form, + base::span<const std::pair<const FormFieldData*, const AutofillField*>> + filled_fields, + absl::variant<const AutofillProfile*, const CreditCard*> + profile_or_credit_card) {} + + virtual void OnFormSubmitted(AutofillManager& manager, FormGlobalId form) {} }; // TODO(crbug.com/1151542): Move to anonymous namespace once @@ -291,6 +307,15 @@ const FormGlobalId& form_global_id, const FieldGlobalId& field_global_id) = 0; + // Notifies observers about a form being filled with an autofill address + // profile or credit card. + void OnAutofillProfileOrCreditCardFormFilled( + autofill::FormGlobalId form, + base::span<const std::pair<const FormFieldData*, const AutofillField*>> + filled_fields, + absl::variant<const AutofillProfile*, const CreditCard*> + profile_or_credit_card); + // translate::TranslateDriver::LanguageDetectionObserver: void OnTranslateDriverDestroyed( translate::TranslateDriver* translate_driver) override;
diff --git a/components/autofill/core/browser/autofill_manager_unittest.cc b/components/autofill/core/browser/autofill_manager_unittest.cc index 2512210..23114a41 100644 --- a/components/autofill/core/browser/autofill_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_manager_unittest.cc
@@ -32,9 +32,12 @@ using testing::Field; using testing::Invoke; using testing::NiceMock; +using testing::Pair; +using testing::Property; using testing::Ref; using testing::Return; using testing::UnorderedElementsAreArray; +using testing::VariantWith; namespace autofill { @@ -372,6 +375,7 @@ auto f = Eq(form.global_id()); auto g = Eq(other_form.global_id()); auto ff = Eq(field.global_id()); + auto ff_property = Property(&FormFieldData::global_id, field.global_id()); auto heuristics = Eq(FieldTypeSource::kHeuristicsOrAutocomplete); MockAutofillManagerObserver observer; @@ -401,6 +405,7 @@ EXPECT_CALL(observer, OnBeforeLoadedServerPredictions).Times(0); EXPECT_CALL(observer, OnAfterLoadedServerPredictions).Times(0); EXPECT_CALL(observer, OnFieldTypesDetermined).Times(0); + EXPECT_CALL(observer, OnAutofillProfileOrCreditCardFormFilled).Times(0); EXPECT_CALL(observer, OnFormSubmitted).Times(0); EXPECT_CALL(*manager_, ShouldParseForms) @@ -474,6 +479,14 @@ EXPECT_CALL(observer, OnAfterJavaScriptChangedAutofilledValue(m, f, ff)); manager_->OnJavaScriptChangedAutofilledValue(form, field, {}); + AutofillProfile profile; + EXPECT_CALL(observer, OnAutofillProfileOrCreditCardFormFilled( + m, f, ElementsAre(Pair(ff_property, ff_property)), + VariantWith<const AutofillProfile*>(&profile))); + manager_->OnAutofillProfileOrCreditCardFormFilled( + form.global_id(), + {{{&field, std::make_unique<AutofillField>(field).get()}}}, &profile); + EXPECT_CALL(observer, OnFormSubmitted(m, f)); manager_->OnFormSubmitted(form, true, mojom::SubmissionSource::FORM_SUBMISSION);
diff --git a/components/autofill/core/browser/autofill_test_utils.cc b/components/autofill/core/browser/autofill_test_utils.cc index 3863dd5..5673113 100644 --- a/components/autofill/core/browser/autofill_test_utils.cc +++ b/components/autofill/core/browser/autofill_test_utils.cc
@@ -161,39 +161,34 @@ form->submission_event = mojom::SubmissionIndicatorEvent::SAME_DOCUMENT_NAVIGATION; - FormFieldData field; - test::CreateTestFormField("First Name", "firstname", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("First Name", "firstname", "", "text")); types->push_back({NAME_FIRST}); - test::CreateTestFormField("Middle Name", "middlename", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Middle Name", "middlename", "", "text")); types->push_back({NAME_MIDDLE}); - test::CreateTestFormField("Last Name", "lastname", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Last Name", "lastname", "", "text")); types->push_back({NAME_LAST, NAME_LAST_SECOND}); - test::CreateTestFormField("Address Line 1", "addr1", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Address Line 1", "addr1", "", "text")); types->push_back({ADDRESS_HOME_LINE1}); - test::CreateTestFormField("Address Line 2", "addr2", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Address Line 2", "addr2", "", "text")); types->push_back({ADDRESS_HOME_SUBPREMISE, ADDRESS_HOME_LINE2}); - test::CreateTestFormField("City", "city", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back(CreateTestFormField("City", "city", "", "text")); types->push_back({ADDRESS_HOME_CITY}); - test::CreateTestFormField("State", "state", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back(CreateTestFormField("State", "state", "", "text")); types->push_back({ADDRESS_HOME_STATE}); - test::CreateTestFormField("Postal Code", "zipcode", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Postal Code", "zipcode", "", "text")); types->push_back({ADDRESS_HOME_ZIP}); - test::CreateTestFormField("Country", "country", "", "text", &field); - form->fields.push_back(field); + form->fields.push_back(CreateTestFormField("Country", "country", "", "text")); types->push_back({ADDRESS_HOME_COUNTRY}); - test::CreateTestFormField("Phone Number", "phonenumber", "", "tel", &field); - form->fields.push_back(field); + form->fields.push_back( + CreateTestFormField("Phone Number", "phonenumber", "", "tel")); types->push_back({PHONE_HOME_WHOLE_NUMBER}); - test::CreateTestFormField("Email", "email", "", "email", &field); - form->fields.push_back(field); + form->fields.push_back(CreateTestFormField("Email", "email", "", "email")); types->push_back({EMAIL_ADDRESS}); }
diff --git a/components/autofill/core/browser/browser_autofill_manager.cc b/components/autofill/core/browser/browser_autofill_manager.cc index 7595009..5840691 100644 --- a/components/autofill/core/browser/browser_autofill_manager.cc +++ b/components/autofill/core/browser/browser_autofill_manager.cc
@@ -288,6 +288,7 @@ case PopupItemId::kFieldByFieldFilling: case PopupItemId::kFillExistingPlusAddress: case PopupItemId::kCreateNewPlusAddress: + case PopupItemId::kFillFullPhoneNumber: NOTREACHED(); } NOTREACHED(); @@ -788,16 +789,19 @@ // need to parse the forms and query the server as the password manager // depends on server classifications. bool password_manager_enabled = client().IsPasswordManagerEnabled(); - sync_state_ = client().GetPersonalDataManager() - ? client().GetPersonalDataManager()->GetSyncSigninState() - : AutofillSyncSigninState::kNumSyncStates; + signin_state_for_metrics_ = + client().GetPersonalDataManager() + ? client() + .GetPersonalDataManager() + ->GetPaymentsSigninStateForMetrics() + : AutofillMetrics::PaymentsSigninState::kUnknown; if (!has_logged_autofill_enabled_) { AutofillMetrics::LogIsAutofillEnabledAtPageLoad(autofill_enabled, - sync_state_); + signin_state_for_metrics_); AutofillMetrics::LogIsAutofillProfileEnabledAtPageLoad( - IsAutofillProfileEnabled(), sync_state_); + IsAutofillProfileEnabled(), signin_state_for_metrics_); AutofillMetrics::LogIsAutofillCreditCardEnabledAtPageLoad( - IsAutofillCreditCardEnabled(), sync_state_); + IsAutofillCreditCardEnabled(), signin_state_for_metrics_); has_logged_autofill_enabled_ = true; } @@ -920,10 +924,11 @@ client().IsAutocompleteEnabled()); if (IsAutofillProfileEnabled()) { - address_form_event_logger_->OnWillSubmitForm(sync_state_, *submitted_form); + address_form_event_logger_->OnWillSubmitForm(signin_state_for_metrics_, + *submitted_form); } if (IsAutofillCreditCardEnabled()) { - credit_card_form_event_logger_->OnWillSubmitForm(sync_state_, + credit_card_form_event_logger_->OnWillSubmitForm(signin_state_for_metrics_, *submitted_form); } @@ -962,10 +967,11 @@ submitted_form->set_submission_source(source); if (IsAutofillProfileEnabled()) { - address_form_event_logger_->OnFormSubmitted(sync_state_, *submitted_form); + address_form_event_logger_->OnFormSubmitted(signin_state_for_metrics_, + *submitted_form); } if (IsAutofillCreditCardEnabled()) { - credit_card_form_event_logger_->OnFormSubmitted(sync_state_, + credit_card_form_event_logger_->OnFormSubmitted(signin_state_for_metrics_, *submitted_form); if (touch_to_fill_delegate_) { touch_to_fill_delegate_->LogMetricsAfterSubmission(*submitted_form); @@ -1416,7 +1422,7 @@ if (should_fetch_card) { credit_card_form_event_logger_->OnDidSelectCardSuggestion( - credit_card_, *form_structure, sync_state_); + credit_card_, *form_structure, signin_state_for_metrics_); credit_card_form_ = form; credit_card_field_ = field; @@ -1704,7 +1710,8 @@ if (logger) { logger->OnDidShowSuggestions(*form_structure, *autofill_field, form_structure->form_parsed_timestamp(), - sync_state_, client().IsOffTheRecord()); + signin_state_for_metrics_, + client().IsOffTheRecord()); } else if (autofill_field->ShouldSuppressSuggestionsAndFillingByDefault()) { // Suggestions were triggered on an ac=unrecognized address field. autocomplete_unrecognized_fallback_logger_->OnDidShowSuggestions(); @@ -2690,6 +2697,8 @@ if (action_persistence == mojom::AutofillActionPersistence::kFill) { form_autofill_history_.AddFormFillEntry(safe_newly_filled_fields, field.origin, is_refill); + OnAutofillProfileOrCreditCardFormFilled( + form.global_id(), safe_newly_filled_fields, profile_or_credit_card); } LOG_AF(buffer) << CTag{"table"}; @@ -2708,8 +2717,8 @@ credit_card_form_event_logger_->OnDidFillSuggestion( credit_card_, *form_structure, *autofill_trigger_field, newly_filled_fields, - base::flat_set<FieldGlobalId>(std::move(safe_fields)), sync_state_, - trigger_source); + base::flat_set<FieldGlobalId>(std::move(safe_fields)), + signin_state_for_metrics_, trigger_source); } else { // An address form was filled. CHECK(absl::holds_alternative<const AutofillProfile*>( @@ -2720,7 +2729,7 @@ } else { address_form_event_logger_->OnDidFillSuggestion( *absl::get<const AutofillProfile*>(profile_or_credit_card), - *form_structure, *autofill_trigger_field, sync_state_, + *form_structure, *autofill_trigger_field, signin_state_for_metrics_, trigger_source); } } @@ -2848,7 +2857,8 @@ const FormFieldData& field, const AutofillField& autofill_field, AutofillSuggestionTriggerSource trigger_source) const { - address_form_event_logger_->OnDidPollSuggestions(field, sync_state_); + address_form_event_logger_->OnDidPollSuggestions(field, + signin_state_for_metrics_); AutofillProfile fake_profile; // Getting the filling-relevant fields so that suggestions are based only on // those fields. Function BrowserAutofillManager::GetSkipStatuses assumes that @@ -2874,7 +2884,8 @@ const FormFieldData& field, const AutofillType& type, bool& should_display_gpay_logo) const { - credit_card_form_event_logger_->OnDidPollSuggestions(field, sync_state_); + credit_card_form_event_logger_->OnDidPollSuggestions( + field, signin_state_for_metrics_); std::vector<Suggestion> suggestions; bool with_offer = false; @@ -2951,7 +2962,8 @@ has_parsed_forms_ = true; // Record the current sync state to be used for metrics on this page. - sync_state_ = client().GetPersonalDataManager()->GetSyncSigninState(); + signin_state_for_metrics_ = + client().GetPersonalDataManager()->GetPaymentsSigninStateForMetrics(); // Setup the url for metrics that we will collect for this form. form_interactions_ukm_logger()->OnFormsParsed(client().GetUkmSourceId()); @@ -3353,15 +3365,15 @@ if (filling_context == nullptr) return false; - address_form_event_logger_->OnDidSeeFillableDynamicForm(sync_state_, - form_structure); + address_form_event_logger_->OnDidSeeFillableDynamicForm( + signin_state_for_metrics_, form_structure); base::TimeTicks now = AutofillTickClock::NowTicks(); base::TimeDelta delta = now - filling_context->original_fill_time; if (filling_context->attempted_refill && delta < kLimitBeforeRefill) { - address_form_event_logger_->OnSubsequentRefillAttempt(sync_state_, - form_structure); + address_form_event_logger_->OnSubsequentRefillAttempt( + signin_state_for_metrics_, form_structure); } return !filling_context->attempted_refill && delta < kLimitBeforeRefill; @@ -3397,7 +3409,8 @@ if (!form_structure) return; - address_form_event_logger_->OnDidRefill(sync_state_, *form_structure); + address_form_event_logger_->OnDidRefill(signin_state_for_metrics_, + *form_structure); FillingContext* filling_context = GetFillingContext(*form_structure); DCHECK(filling_context); @@ -3513,7 +3526,7 @@ auto* logger = GetEventFormLogger(*context->focused_field); if (logger) { logger->OnDidInteractWithAutofillableForm(*(context->form_structure), - sync_state_); + signin_state_for_metrics_); } }
diff --git a/components/autofill/core/browser/browser_autofill_manager.h b/components/autofill/core/browser/browser_autofill_manager.h index 3abbde86..532eb76e9 100644 --- a/components/autofill/core/browser/browser_autofill_manager.h +++ b/components/autofill/core/browser/browser_autofill_manager.h
@@ -33,6 +33,7 @@ #include "components/autofill/core/browser/form_autofill_history.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/form_types.h" +#include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/fallback_autocomplete_unrecognized_metrics.h" #include "components/autofill/core/browser/metrics/form_events/address_form_event_logger.h" #include "components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h" @@ -43,7 +44,6 @@ #include "components/autofill/core/browser/payments/full_card_request.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/single_field_form_fill_router.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/ui/fast_checkout_delegate.h" #include "components/autofill/core/browser/ui/popup_item_ids.h" #include "components/autofill/core/browser/ui/popup_types.h" @@ -824,7 +824,8 @@ // Used to record metrics. This should be set at the beginning of the // interaction and re-used throughout the context of this manager. - AutofillSyncSigninState sync_state_ = AutofillSyncSigninState::kNumSyncStates; + AutofillMetrics::PaymentsSigninState signin_state_for_metrics_ = + AutofillMetrics::PaymentsSigninState::kUnknown; // Helps with measuring whether phone number is collected and whether it is in // conjunction with WebOTP or OneTimeCode (OTC).
diff --git a/components/autofill/core/browser/field_filler_unittest.cc b/components/autofill/core/browser/field_filler_unittest.cc index fc54577..79bd4bdd 100644 --- a/components/autofill/core/browser/field_filler_unittest.cc +++ b/components/autofill/core/browser/field_filler_unittest.cc
@@ -48,6 +48,7 @@ using ::i18n::addressinput::Source; using ::i18n::addressinput::Storage; using ::i18n::addressinput::TestdataSource; +using test::CreateTestFormField; using test::CreateTestSelectField; std::u16string kMidlineEllipsis2Dots = CreditCard::GetMidlineEllipsisDots(2); @@ -1949,8 +1950,7 @@ test::ClearAlternativeStateNameMapForTesting(); test::PopulateAlternativeStateNameMapForTesting(); - AutofillField field; - test::CreateTestFormField("State", "state", "", "text", &field); + AutofillField field(CreateTestFormField("State", "state", "", "text")); field.set_heuristic_type(GetActivePatternSource(), ADDRESS_HOME_STATE); field.max_length = 4; @@ -2048,8 +2048,7 @@ .abbreviations = {"by"}, .alternative_names = {}}}); - AutofillField field; - test::CreateTestFormField("State", "state", "", "text", &field); + AutofillField field{CreateTestFormField("State", "state", "", "text")}; field.set_heuristic_type(GetActivePatternSource(), ADDRESS_HOME_STATE); field.max_length = 4;
diff --git a/components/autofill/core/browser/form_autofill_history_unittest.cc b/components/autofill/core/browser/form_autofill_history_unittest.cc index d5de012..7be436d 100644 --- a/components/autofill/core/browser/form_autofill_history_unittest.cc +++ b/components/autofill/core/browser/form_autofill_history_unittest.cc
@@ -5,6 +5,8 @@ #include "components/autofill/core/browser/form_autofill_history.h" #include <memory> +#include <string_view> +#include <utility> #include <vector> #include "base/containers/flat_map.h" @@ -21,46 +23,42 @@ #include "testing/gtest/include/gtest/gtest.h" #include "url/origin.h" -static constexpr char kExampleSite[] = "https://example.com"; namespace autofill { using ::testing::ElementsAre; using ::testing::Pair; +constexpr char kExampleSite[] = "https://example.com"; + class FormAutofillHistoryTest : public testing::Test { public: - FieldGlobalId AddNewFieldFilling(const char* label, - const char* name, - const char* value, - const char* type, + FieldGlobalId AddNewFieldFilling(std::string_view label, + std::string_view name, + std::string_view value, + std::string_view type, ServerFieldType field_type, bool is_autofilled = false) { - std::unique_ptr<FormFieldData> field = std::make_unique<FormFieldData>(); - test::CreateTestFormField(label, name, value, type, field.get()); - field->is_autofilled = is_autofilled; - std::unique_ptr<AutofillField> autofill_field = - std::make_unique<AutofillField>(*field); - autofill_field->SetTypeTo(AutofillType(field_type)); - FieldGlobalId field_id = field->global_id(); - filled_fields_.emplace_back(std::move(field), std::move(autofill_field)); - return field_id; + FormFieldData field = test::CreateTestFormField(label, name, value, type); + field.is_autofilled = is_autofilled; + AutofillField autofill_field(field); + autofill_field.SetTypeTo(AutofillType(field_type)); + filled_fields_.emplace_back(field, std::move(autofill_field)); + return field.global_id(); } void AddFormFilling(bool is_refill) { std::vector<std::pair<const FormFieldData*, const AutofillField*>> fields; for (const auto& [field, autofill_field] : filled_fields_) { - fields.emplace_back(field.get(), autofill_field.get()); + fields.emplace_back(&field, &autofill_field); } form_autofill_history_.AddFormFillEntry( fields, url::Origin::Create(GURL(kExampleSite)), is_refill); } - std::vector< - std::pair<std::unique_ptr<FormFieldData>, std::unique_ptr<AutofillField>>> - filled_fields_; + std::vector<std::pair<FormFieldData, AutofillField>> filled_fields_; FormAutofillHistory form_autofill_history_; private: - test::AutofillUnitTestEnvironment autofill_test_environemnt_; + test::AutofillUnitTestEnvironment autofill_test_environment_; }; // Tests the function FormAutofillHistory::AddFormFillEntry upon a normal fill. @@ -88,7 +86,7 @@ AddFormFilling(/*is_refill=*/false); // Modify the first name filling to simulate a refill. - filled_fields_[0].first->value = u"some-other-first-name"; + filled_fields_[0].first.value = u"some-other-first-name"; FieldGlobalId last_name_id = AddNewFieldFilling("last name", "last name", "some-other-last-name", "text", NAME_LAST, /*is_autofilled=*/true);
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 e7f7062..90264eb5 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
@@ -589,7 +589,7 @@ ], "pt": [ { - "positive_pattern": "addrcomplement", + "positive_pattern": "complemento|addrcomplement", "positive_score": 1.1, "negative_pattern": null, "match_field_attributes": ["LABEL", "NAME"],
diff --git a/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc b/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc index 8abd611..45089a9 100644 --- a/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc +++ b/components/autofill/core/browser/merchant_promo_code_manager_unittest.cc
@@ -13,21 +13,23 @@ #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_test_utils.h" #include "components/autofill/core/common/form_data.h" #include "components/strings/grit/components_strings.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" -using testing::_; -using testing::Field; -using testing::Truly; -using testing::UnorderedElementsAre; - namespace autofill { namespace { +using test::CreateTestFormField; +using ::testing::_; +using ::testing::Field; +using ::testing::Truly; +using ::testing::UnorderedElementsAre; + class MockSuggestionsHandler : public MerchantPromoCodeManager::SuggestionsHandler { public: @@ -61,8 +63,8 @@ merchant_promo_code_manager_ = std::make_unique<MerchantPromoCodeManager>(); merchant_promo_code_manager_->Init(personal_data_manager_.get(), /*is_off_the_record=*/false); - test::CreateTestFormField(/*label=*/"", "Some Field Name", "SomePrefix", - "Some Type", &test_field_); + test_field_ = CreateTestFormField(/*label=*/"", "Some Field Name", + "SomePrefix", "Some Type"); } // Sets up the TestPersonalDataManager with a promo code offer for the given @@ -147,9 +149,8 @@ // Trigger offers suggestions popup again to be able to test that we log // metrics more than once if it is a different field. - FormFieldData other_field; - test::CreateTestFormField(/*label=*/"", "Some Other Name", "SomePrefix", - "Some Type", &other_field); + FormFieldData other_field = CreateTestFormField( + /*label=*/"", "Some Other Name", "SomePrefix", "Some Type"); EXPECT_TRUE(merchant_promo_code_manager_->OnGetSingleFieldSuggestions( trigger_source, other_field, autofill_client_, suggestions_handler->GetWeakPtr(),
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.cc b/components/autofill/core/browser/metrics/autofill_metrics.cc index af3b4c7..fa5b8cc 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics.cc
@@ -1492,7 +1492,7 @@ // static void AutofillMetrics::LogIsAutofillEnabledAtPageLoad( bool enabled, - AutofillSyncSigninState sync_state) { + PaymentsSigninState sync_state) { std::string name("Autofill.IsEnabled.PageLoad"); UMA_HISTOGRAM_BOOLEAN(name, enabled); base::UmaHistogramBoolean(name + GetMetricsSyncStateSuffix(sync_state), @@ -1502,7 +1502,7 @@ // static void AutofillMetrics::LogIsAutofillProfileEnabledAtPageLoad( bool enabled, - AutofillSyncSigninState sync_state) { + PaymentsSigninState sync_state) { std::string name("Autofill.Address.IsEnabled.PageLoad"); UMA_HISTOGRAM_BOOLEAN(name, enabled); base::UmaHistogramBoolean(name + GetMetricsSyncStateSuffix(sync_state), @@ -1512,7 +1512,7 @@ // static void AutofillMetrics::LogIsAutofillCreditCardEnabledAtPageLoad( bool enabled, - AutofillSyncSigninState sync_state) { + PaymentsSigninState sync_state) { std::string name("Autofill.CreditCard.IsEnabled.PageLoad"); UMA_HISTOGRAM_BOOLEAN(name, enabled); base::UmaHistogramBoolean(name + GetMetricsSyncStateSuffix(sync_state), @@ -2823,27 +2823,25 @@ return form_type_bv; } -void AutofillMetrics::LogServerCardLinkClicked( - AutofillSyncSigninState sync_state) { - UMA_HISTOGRAM_ENUMERATION("Autofill.ServerCardLinkClicked", sync_state, - AutofillSyncSigninState::kNumSyncStates); +void AutofillMetrics::LogServerCardLinkClicked(PaymentsSigninState sync_state) { + base::UmaHistogramEnumeration("Autofill.ServerCardLinkClicked", sync_state); } // static const char* AutofillMetrics::GetMetricsSyncStateSuffix( - AutofillSyncSigninState sync_state) { + PaymentsSigninState sync_state) { switch (sync_state) { - case AutofillSyncSigninState::kSignedOut: + case PaymentsSigninState::kSignedOut: return ".SignedOut"; - case AutofillSyncSigninState::kSignedIn: + case PaymentsSigninState::kSignedIn: return ".SignedIn"; - case AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled: + case PaymentsSigninState::kSignedInAndWalletSyncTransportEnabled: return ".SignedInAndWalletSyncTransportEnabled"; - case AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled: + case PaymentsSigninState::kSignedInAndSyncFeatureEnabled: return ".SignedInAndSyncFeatureEnabled"; - case AutofillSyncSigninState::kSyncPaused: + case PaymentsSigninState::kSyncPaused: return ".SyncPaused"; - case AutofillSyncSigninState::kNumSyncStates: + case PaymentsSigninState::kUnknown: return ".Unknown"; } }
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.h b/components/autofill/core/browser/metrics/autofill_metrics.h index 05d02ea..c507d6d 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.h +++ b/components/autofill/core/browser/metrics/autofill_metrics.h
@@ -26,7 +26,6 @@ #include "components/autofill/core/browser/form_types.h" #include "components/autofill/core/browser/metrics/form_events/form_events.h" #include "components/autofill/core/browser/metrics/log_event.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/ui/popup_types.h" #include "components/autofill/core/common/dense_set.h" #include "components/autofill/core/common/mojom/autofill_types.mojom-forward.h" @@ -844,6 +843,26 @@ kMaxValue = kBoth }; + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class PaymentsSigninState { + // The user is not signed in to Chromium. + kSignedOut = 0, + // The user is signed in to Chromium. + kSignedIn = 1, + // The user is signed in to Chromium and sync transport is active for Wallet + // data. + kSignedInAndWalletSyncTransportEnabled = 2, + // The user is signed in, has enabled the sync feature and has not disabled + // Wallet sync. + kSignedInAndSyncFeatureEnabled = 3, + // The user has enabled the sync feature, but has then signed out, so sync + // is paused. + kSyncPaused = 4, + kUnknown = 5, + kMaxValue = kUnknown + }; + AutofillMetrics() = delete; AutofillMetrics(const AutofillMetrics&) = delete; AutofillMetrics& operator=(const AutofillMetrics&) = delete; @@ -1021,19 +1040,18 @@ const base::TimeDelta& duration); // This should be called each time a page containing forms is loaded. - static void LogIsAutofillEnabledAtPageLoad( - bool enabled, - AutofillSyncSigninState sync_state); + static void LogIsAutofillEnabledAtPageLoad(bool enabled, + PaymentsSigninState sync_state); // This should be called each time a page containing forms is loaded. static void LogIsAutofillProfileEnabledAtPageLoad( bool enabled, - AutofillSyncSigninState sync_state); + PaymentsSigninState sync_state); // This should be called each time a page containing forms is loaded. static void LogIsAutofillCreditCardEnabledAtPageLoad( bool enabled, - AutofillSyncSigninState sync_state); + PaymentsSigninState sync_state); // This should be called each time a new chrome profile is launched. static void LogIsAutofillEnabledAtStartup(bool enabled); @@ -1229,7 +1247,7 @@ // Records the fact that the server card link was clicked with information // about the current sync state. - static void LogServerCardLinkClicked(AutofillSyncSigninState sync_state); + static void LogServerCardLinkClicked(PaymentsSigninState sync_state); // Records if an autofilled field of a specific type was edited by the user. // TODO(crbug.com/1368096): This metric is the successor of @@ -1254,8 +1272,7 @@ // Records the visible page language upon form submission. static void LogFieldParsingTranslatedFormLanguageMetric(base::StringPiece); - static const char* GetMetricsSyncStateSuffix( - AutofillSyncSigninState sync_state); + static const char* GetMetricsSyncStateSuffix(PaymentsSigninState sync_state); // Records whether a document collected phone number, and/or used WebOTP, // and/or used OneTimeCode (OTC) during its lifecycle.
diff --git a/components/autofill/core/browser/metrics/autofill_metrics_test_base.h b/components/autofill/core/browser/metrics/autofill_metrics_test_base.h index 500f1113..a6a231f 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics_test_base.h +++ b/components/autofill/core/browser/metrics/autofill_metrics_test_base.h
@@ -205,11 +205,11 @@ // Forwards to test::CreateTestFormField(). This is a hack meant as an // intermediate step towards removing the out-parameters from // autofill_form_util.h. + // TODO(crbug.com/1465839): Replace the short-hand by `CreateTestFormField` + // now that that also returns by value. template <typename... Args> [[nodiscard]] FormFieldData CreateField(Args... args) { - FormFieldData field; - test::CreateTestFormField(args..., &field); - return field; + return test::CreateTestFormField(args...); } TestBrowserAutofillManager& autofill_manager() {
diff --git a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc index a0691d9..564bf26 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics_unittest.cc
@@ -48,7 +48,6 @@ #include "components/autofill/core/browser/payments/test_credit_card_save_manager.h" #include "components/autofill/core/browser/payments/test_payments_client.h" #include "components/autofill/core/browser/personal_data_manager.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/browser/test_autofill_tick_clock.h" @@ -111,7 +110,7 @@ namespace autofill::autofill_metrics { using mojom::SubmissionSource; -using SyncSigninState = AutofillSyncSigninState; +using PaymentsSigninState = AutofillMetrics::PaymentsSigninState; using AutofillStatus = AutofillMetrics::AutofillStatus; namespace { @@ -7688,8 +7687,8 @@ TEST_F(AutofillMetricsTest, LogIsAutofillEnabledAtPageLoad_BySyncState) { { base::HistogramTester histogram_tester; - AutofillMetrics::LogIsAutofillEnabledAtPageLoad(/*enabled=*/true, - SyncSigninState::kSignedIn); + AutofillMetrics::LogIsAutofillEnabledAtPageLoad( + /*enabled=*/true, PaymentsSigninState::kSignedIn); histogram_tester.ExpectBucketCount("Autofill.IsEnabled.PageLoad.SignedIn", true, 1); // Make sure the metric without the sync state is still recorded. @@ -7698,7 +7697,7 @@ { base::HistogramTester histogram_tester; AutofillMetrics::LogIsAutofillEnabledAtPageLoad( - /*enabled=*/false, SyncSigninState::kSignedOut); + /*enabled=*/false, PaymentsSigninState::kSignedOut); histogram_tester.ExpectBucketCount("Autofill.IsEnabled.PageLoad.SignedOut", false, 1); // Make sure the metric without the sync state is still recorded. @@ -7709,19 +7708,17 @@ TEST_F(AutofillMetricsTest, LogServerCardLinkClicked) { { base::HistogramTester histogram_tester; - AutofillMetrics::LogServerCardLinkClicked( - AutofillSyncSigninState::kSignedIn); + AutofillMetrics::LogServerCardLinkClicked(PaymentsSigninState::kSignedIn); histogram_tester.ExpectTotalCount("Autofill.ServerCardLinkClicked", 1); histogram_tester.ExpectBucketCount("Autofill.ServerCardLinkClicked", - AutofillSyncSigninState::kSignedIn, 1); + PaymentsSigninState::kSignedIn, 1); } { base::HistogramTester histogram_tester; - AutofillMetrics::LogServerCardLinkClicked( - AutofillSyncSigninState::kSignedOut); + AutofillMetrics::LogServerCardLinkClicked(PaymentsSigninState::kSignedOut); histogram_tester.ExpectTotalCount("Autofill.ServerCardLinkClicked", 1); histogram_tester.ExpectBucketCount("Autofill.ServerCardLinkClicked", - AutofillSyncSigninState::kSignedOut, 1); + PaymentsSigninState::kSignedOut, 1); } }
diff --git a/components/autofill/core/browser/metrics/form_events/address_form_event_logger.cc b/components/autofill/core/browser/metrics/form_events/address_form_event_logger.cc index 36de1d75..7d585b8 100644 --- a/components/autofill/core/browser/metrics/form_events/address_form_event_logger.cc +++ b/components/autofill/core/browser/metrics/form_events/address_form_event_logger.cc
@@ -36,10 +36,10 @@ const AutofillProfile& profile, const FormStructure& form, const AutofillField& field, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, const AutofillTriggerSource trigger_source) { AutofillProfile::RecordType record_type = profile.record_type(); - sync_state_ = sync_state; + signin_state_for_metrics_ = signin_state_for_metrics; form_interactions_ukm_logger_->LogDidFillSuggestion(record_type, form, field); @@ -71,22 +71,23 @@ } void AddressFormEventLogger::OnDidSeeFillableDynamicForm( - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, const FormStructure& form) { - sync_state_ = sync_state; + signin_state_for_metrics_ = signin_state_for_metrics; Log(FORM_EVENT_DID_SEE_FILLABLE_DYNAMIC_FORM, form); } -void AddressFormEventLogger::OnDidRefill(AutofillSyncSigninState sync_state, - const FormStructure& form) { - sync_state_ = sync_state; +void AddressFormEventLogger::OnDidRefill( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form) { + signin_state_for_metrics_ = signin_state_for_metrics; Log(FORM_EVENT_DID_DYNAMIC_REFILL, form); } void AddressFormEventLogger::OnSubsequentRefillAttempt( - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, const FormStructure& form) { - sync_state_ = sync_state; + signin_state_for_metrics_ = signin_state_for_metrics; Log(FORM_EVENT_DYNAMIC_CHANGE_AFTER_REFILL, form); }
diff --git a/components/autofill/core/browser/metrics/form_events/address_form_event_logger.h b/components/autofill/core/browser/metrics/form_events/address_form_event_logger.h index 49b402e..015c5b0e 100644 --- a/components/autofill/core/browser/metrics/form_events/address_form_event_logger.h +++ b/components/autofill/core/browser/metrics/form_events/address_form_event_logger.h
@@ -15,7 +15,6 @@ #include "components/autofill/core/browser/metrics/autofill_metrics_utils.h" #include "components/autofill/core/browser/metrics/form_events/form_event_logger_base.h" #include "components/autofill/core/browser/metrics/form_events/form_events.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/common/dense_set.h" namespace autofill::autofill_metrics { @@ -42,20 +41,24 @@ ~AddressFormEventLogger() override; - void OnDidFillSuggestion(const AutofillProfile& profile, - const FormStructure& form, - const AutofillField& field, - AutofillSyncSigninState sync_state, - const AutofillTriggerSource trigger_source); + void OnDidFillSuggestion( + const AutofillProfile& profile, + const FormStructure& form, + const AutofillField& field, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const AutofillTriggerSource trigger_source); - void OnDidSeeFillableDynamicForm(AutofillSyncSigninState sync_state, - const FormStructure& form); + void OnDidSeeFillableDynamicForm( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form); - void OnDidRefill(AutofillSyncSigninState sync_state, - const FormStructure& form); + void OnDidRefill( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form); - void OnSubsequentRefillAttempt(AutofillSyncSigninState sync_state, - const FormStructure& form); + void OnSubsequentRefillAttempt( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form); protected: void RecordPollSuggestions() override;
diff --git a/components/autofill/core/browser/metrics/form_events/address_form_event_logger_unittest.cc b/components/autofill/core/browser/metrics/form_events/address_form_event_logger_unittest.cc index d59c27f..1a36427 100644 --- a/components/autofill/core/browser/metrics/form_events/address_form_event_logger_unittest.cc +++ b/components/autofill/core/browser/metrics/form_events/address_form_event_logger_unittest.cc
@@ -35,8 +35,8 @@ /*is_in_any_main_frame=*/true, /*form_interactions_ukm_logger=*/nullptr, /*client=*/autofill_client_.get()); - logger.OnDidSeeFillableDynamicForm(AutofillSyncSigninState::kSignedOut, - form_structure); + logger.OnDidSeeFillableDynamicForm( + AutofillMetrics::PaymentsSigninState::kSignedOut, form_structure); histogram_tester.ExpectBucketCount( "Autofill.FormEvents.Address.WithNoData.SignedOut", FORM_EVENT_DID_SEE_FILLABLE_DYNAMIC_FORM, 1); @@ -48,7 +48,8 @@ /*is_in_any_main_frame=*/true, /*form_interactions_ukm_logger=*/nullptr, /*client=*/autofill_client_.get()); - logger.OnDidRefill(AutofillSyncSigninState::kSignedIn, form_structure); + logger.OnDidRefill(AutofillMetrics::PaymentsSigninState::kSignedIn, + form_structure); histogram_tester.ExpectBucketCount( "Autofill.FormEvents.Address.WithNoData.SignedIn", FORM_EVENT_DID_DYNAMIC_REFILL, 1);
diff --git a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc index b3b31c1..73fc916 100644 --- a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc +++ b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.cc
@@ -57,14 +57,15 @@ const FormStructure& form, const AutofillField& field, const base::TimeTicks& form_parsed_timestamp, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, bool off_the_record) { if (DoSuggestionsIncludeVirtualCard()) Log(FORM_EVENT_SUGGESTIONS_SHOWN_WITH_VIRTUAL_CARD, form); // Also perform the logging actions from the base class: FormEventLoggerBase::OnDidShowSuggestions(form, field, form_parsed_timestamp, - sync_state, off_the_record); + signin_state_for_metrics, + off_the_record); suggestion_shown_timestamp_ = AutofillTickClock::NowTicks(); @@ -90,8 +91,8 @@ void CreditCardFormEventLogger::OnDidSelectCardSuggestion( const CreditCard& credit_card, const FormStructure& form, - AutofillSyncSigninState sync_state) { - sync_state_ = sync_state; + AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + signin_state_for_metrics_ = signin_state_for_metrics; card_selected_has_offer_ = false; if (has_eligible_offer_) { @@ -159,10 +160,10 @@ const AutofillField& field, const base::flat_set<FieldGlobalId>& newly_filled_fields, const base::flat_set<FieldGlobalId>& safe_fields, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, const AutofillTriggerSource trigger_source) { CreditCard::RecordType record_type = credit_card.record_type(); - sync_state_ = sync_state; + signin_state_for_metrics_ = signin_state_for_metrics; ukm::builders::Autofill_CreditCardFill builder = form_interactions_ukm_logger_->CreateCreditCardFillBuilder(); builder.SetFormSignature(HashFormSignature(form.form_signature()));
diff --git a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h index e408a4a..3fd1dc3 100644 --- a/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h +++ b/components/autofill/core/browser/metrics/form_events/credit_card_form_event_logger.h
@@ -18,7 +18,6 @@ #include "components/autofill/core/browser/metrics/form_events/form_events.h" #include "components/autofill/core/browser/metrics/payments/card_metadata_metrics.h" #include "components/autofill/core/browser/personal_data_manager.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/common/autofill_tick_clock.h" #include "components/autofill/core/common/signatures.h" @@ -57,15 +56,17 @@ const autofill_metrics::CardMetadataLoggingContext& metadata_logging_context); - void OnDidShowSuggestions(const FormStructure& form, - const AutofillField& field, - const base::TimeTicks& form_parsed_timestamp, - AutofillSyncSigninState sync_state, - bool off_the_record) override; + void OnDidShowSuggestions( + const FormStructure& form, + const AutofillField& field, + const base::TimeTicks& form_parsed_timestamp, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + bool off_the_record) override; - void OnDidSelectCardSuggestion(const CreditCard& credit_card, - const FormStructure& form, - AutofillSyncSigninState sync_state); + void OnDidSelectCardSuggestion( + const CreditCard& credit_card, + const FormStructure& form, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics); // To be called whenever (by BrowserAutofillManager) whenever a form is filled // (but not on preview). @@ -88,7 +89,7 @@ const AutofillField& field, const base::flat_set<FieldGlobalId>& newly_filled_fields, const base::flat_set<FieldGlobalId>& safe_fields, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, const AutofillTriggerSource trigger_source); // Logging what type of authentication flow was prompted.
diff --git a/components/autofill/core/browser/metrics/form_events/form_event_logger_base.cc b/components/autofill/core/browser/metrics/form_events/form_event_logger_base.cc index 651431f..1555af5 100644 --- a/components/autofill/core/browser/metrics/form_events/form_event_logger_base.cc +++ b/components/autofill/core/browser/metrics/form_events/form_event_logger_base.cc
@@ -56,8 +56,8 @@ void FormEventLoggerBase::OnDidInteractWithAutofillableForm( const FormStructure& form, - AutofillSyncSigninState sync_state) { - sync_state_ = sync_state; + AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + signin_state_for_metrics_ = signin_state_for_metrics; if (!has_logged_interacted_) { has_logged_interacted_ = true; LogUkmInteractedWithForm(form.form_signature()); @@ -67,8 +67,8 @@ void FormEventLoggerBase::OnDidPollSuggestions( const FormFieldData& field, - AutofillSyncSigninState sync_state) { - sync_state_ = sync_state; + AutofillMetrics::PaymentsSigninState signin_state_for_metrics) { + signin_state_for_metrics_ = signin_state_for_metrics; // Record only one poll user action for consecutive polls of the same field. // This is to avoid recording too many poll actions (for example when a user // types in a field, triggering multiple queries) to make the analysis more @@ -107,9 +107,9 @@ const FormStructure& form, const AutofillField& field, const base::TimeTicks& form_parsed_timestamp, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, bool off_the_record) { - sync_state_ = sync_state; + signin_state_for_metrics_ = signin_state_for_metrics; form_interactions_ukm_logger_->LogSuggestionsShown( form, field, form_parsed_timestamp, off_the_record); @@ -144,9 +144,10 @@ time_from_interaction_to_submission_ = time_from_interaction_to_submission; } -void FormEventLoggerBase::OnWillSubmitForm(AutofillSyncSigninState sync_state, - const FormStructure& form) { - sync_state_ = sync_state; +void FormEventLoggerBase::OnWillSubmitForm( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form) { + signin_state_for_metrics_ = signin_state_for_metrics; // Not logging this kind of form if we haven't logged a user interaction. if (!has_logged_interacted_) return; @@ -166,9 +167,10 @@ base::RecordAction(base::UserMetricsAction("Autofill_OnWillSubmitForm")); } -void FormEventLoggerBase::OnFormSubmitted(AutofillSyncSigninState sync_state, - const FormStructure& form) { - sync_state_ = sync_state; +void FormEventLoggerBase::OnFormSubmitted( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form) { + signin_state_for_metrics_ = signin_state_for_metrics; // Not logging this kind of form if we haven't logged a user interaction. if (!has_logged_interacted_) return; @@ -248,8 +250,9 @@ name += ".WithBothServerAndLocalData"; base::UmaHistogramEnumeration(name, event, NUM_FORM_EVENTS); base::UmaHistogramEnumeration( - name + AutofillMetrics::GetMetricsSyncStateSuffix(sync_state_), event, - NUM_FORM_EVENTS); + name + + AutofillMetrics::GetMetricsSyncStateSuffix(signin_state_for_metrics_), + event, NUM_FORM_EVENTS); } void FormEventLoggerBase::LogWillSubmitForm(const FormStructure& form) {
diff --git a/components/autofill/core/browser/metrics/form_events/form_event_logger_base.h b/components/autofill/core/browser/metrics/form_events/form_event_logger_base.h index cfbb61e..513b3b7 100644 --- a/components/autofill/core/browser/metrics/form_events/form_event_logger_base.h +++ b/components/autofill/core/browser/metrics/form_events/form_event_logger_base.h
@@ -14,7 +14,6 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/form_events/form_events.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/common/form_field_data.h" #include "components/autofill/core/common/form_interactions_flow.h" @@ -38,11 +37,13 @@ local_record_type_count_ = local_record_type_count; } - void OnDidInteractWithAutofillableForm(const FormStructure& form, - AutofillSyncSigninState sync_state); + void OnDidInteractWithAutofillableForm( + const FormStructure& form, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics); - void OnDidPollSuggestions(const FormFieldData& field, - AutofillSyncSigninState sync_state); + void OnDidPollSuggestions( + const FormFieldData& field, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics); void OnDidParseForm(const FormStructure& form); @@ -55,14 +56,16 @@ const FormStructure& form, const AutofillField& field, const base::TimeTicks& form_parsed_timestamp, - AutofillSyncSigninState sync_state, + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, bool off_the_record); - void OnWillSubmitForm(AutofillSyncSigninState sync_state, - const FormStructure& form); + void OnWillSubmitForm( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form); - void OnFormSubmitted(AutofillSyncSigninState sync_state, - const FormStructure& form); + void OnFormSubmitted( + AutofillMetrics::PaymentsSigninState signin_state_for_metrics, + const FormStructure& form); void OnTypedIntoNonFilledField(); void OnEditedAutofilledField(); @@ -232,7 +235,8 @@ // Weak reference. const raw_ref<AutofillClient> client_; - AutofillSyncSigninState sync_state_ = AutofillSyncSigninState::kNumSyncStates; + AutofillMetrics::PaymentsSigninState signin_state_for_metrics_ = + AutofillMetrics::PaymentsSigninState::kUnknown; }; } // namespace autofill::autofill_metrics
diff --git a/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.cc b/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.cc index 5062011..7e59bae0 100644 --- a/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.cc +++ b/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.cc
@@ -35,8 +35,9 @@ .Record(ukm_recorder); } -void LogCardUploadEnabledMetric(CardUploadEnabled metric_value, - AutofillSyncSigninState sync_state) { +void LogCardUploadEnabledMetric( + CardUploadEnabled metric_value, + AutofillMetrics::PaymentsSigninState sync_state) { const std::string parent_metric = std::string("Autofill.CardUploadEnabled"); base::UmaHistogramEnumeration(parent_metric, metric_value); @@ -65,12 +66,13 @@ UMA_HISTOGRAM_BOOLEAN("Autofill.SaveCardCardholderNameWasEdited", edited); } -void LogSaveCardPromptOfferMetric(SaveCardPromptOffer metric, - bool is_uploading, - bool is_reshow, - AutofillClient::SaveCreditCardOptions options, - security_state::SecurityLevel security_level, - AutofillSyncSigninState sync_state) { +void LogSaveCardPromptOfferMetric( + SaveCardPromptOffer metric, + bool is_uploading, + bool is_reshow, + AutofillClient::SaveCreditCardOptions options, + security_state::SecurityLevel security_level, + AutofillMetrics::PaymentsSigninState sync_state) { DCHECK_LE(metric, SaveCardPromptOffer::kMaxValue); std::string base_histogram_name = "Autofill.SaveCreditCardPromptOffer"; std::string destination = is_uploading ? ".Upload" : ".Local"; @@ -125,7 +127,7 @@ bool is_reshow, AutofillClient::SaveCreditCardOptions options, security_state::SecurityLevel security_level, - AutofillSyncSigninState sync_state) { + AutofillMetrics::PaymentsSigninState sync_state) { DCHECK_LE(metric, SaveCardPromptResult::kMaxValue); std::string base_histogram_name = "Autofill.SaveCreditCardPromptResult"; std::string destination = is_uploading ? ".Upload" : ".Local";
diff --git a/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h b/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h index 6022bcd..ac0bbc31 100644 --- a/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h +++ b/components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h
@@ -184,8 +184,9 @@ // Records the reason for why (or why not) card upload was enabled for the // user. -void LogCardUploadEnabledMetric(CardUploadEnabled metric, - AutofillSyncSigninState sync_state); +void LogCardUploadEnabledMetric( + CardUploadEnabled metric, + AutofillMetrics::PaymentsSigninState sync_state); // When credit card save is not offered (either at all on mobile or by simply // not showing the bubble on desktop), logs the occurrence. @@ -203,12 +204,13 @@ // from its prefilled value or not. void LogSaveCardCardholderNameWasEdited(bool edited); -void LogSaveCardPromptOfferMetric(SaveCardPromptOffer metric, - bool is_uploading, - bool is_reshow, - AutofillClient::SaveCreditCardOptions options, - security_state::SecurityLevel security_level, - AutofillSyncSigninState sync_state); +void LogSaveCardPromptOfferMetric( + SaveCardPromptOffer metric, + bool is_uploading, + bool is_reshow, + AutofillClient::SaveCreditCardOptions options, + security_state::SecurityLevel security_level, + AutofillMetrics::PaymentsSigninState sync_state); void LogSaveCardPromptResultMetric( SaveCardPromptResult metric, @@ -216,7 +218,7 @@ bool is_reshow, AutofillClient::SaveCreditCardOptions options, security_state::SecurityLevel security_level, - AutofillSyncSigninState sync_state); + AutofillMetrics::PaymentsSigninState sync_state); void LogSaveCvcPromptOfferMetric(SaveCardPromptOffer metric, bool is_uploading,
diff --git a/components/autofill/core/browser/mock_autofill_manager_observer.h b/components/autofill/core/browser/mock_autofill_manager_observer.h index 8b69e0b..28e02776 100644 --- a/components/autofill/core/browser/mock_autofill_manager_observer.h +++ b/components/autofill/core/browser/mock_autofill_manager_observer.h
@@ -12,6 +12,9 @@ namespace autofill { +class AutofillProfile; +class CreditCard; + class MockAutofillManagerObserver : public AutofillManager::Observer { public: MockAutofillManagerObserver(); @@ -104,6 +107,16 @@ (override)); MOCK_METHOD(void, + OnAutofillProfileOrCreditCardFormFilled, + (AutofillManager&, + FormGlobalId, + (base::span<const std::pair<const FormFieldData*, + const AutofillField*>>), + (absl::variant<const AutofillProfile*, const CreditCard*> + profile_or_credit_card)), + (override)); + + MOCK_METHOD(void, OnFormSubmitted, (AutofillManager&, FormGlobalId), (override));
diff --git a/components/autofill/core/browser/payments/credit_card_save_manager.cc b/components/autofill/core/browser/payments/credit_card_save_manager.cc index 24fcead..93d75bf 100644 --- a/components/autofill/core/browser/payments/credit_card_save_manager.cc +++ b/components/autofill/core/browser/payments/credit_card_save_manager.cc
@@ -239,8 +239,7 @@ if ((should_request_name_from_user_ && should_request_expiration_date_from_user_) || (should_request_expiration_date_from_user_ && - personal_data_manager_->GetSyncSigninState() == - AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled)) { + personal_data_manager_->IsPaymentsWalletSyncTransportEnabled())) { LogCardUploadDecisions(upload_decision_metrics_); pending_upload_request_origin_ = url::Origin(); return; @@ -309,7 +308,8 @@ client_->GetSyncService(), personal_data_manager_->GetAccountInfoForPaymentsServer().email, personal_data_manager_->GetCountryCodeForExperimentGroup(), - personal_data_manager_->GetSyncSigninState(), client_->GetLogManager()); + personal_data_manager_->GetPaymentsSigninStateForMetrics(), + client_->GetLogManager()); } void CreditCardSaveManager::OnDidUploadCard(
diff --git a/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc b/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc index fda9108..481f0b3f 100644 --- a/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc +++ b/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc
@@ -2733,8 +2733,7 @@ // submitting. #if !BUILDFLAG(IS_IOS) // Wallet Sync Transport is enabled. - personal_data().SetSyncAndSignInState( - AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled); + personal_data().SetIsPaymentsWalletSyncTransportEnabled(true); // Create, fill and submit an address form in order to establish a recent // profile which can be selected for the upload request. @@ -2773,8 +2772,7 @@ // submitting. #if !BUILDFLAG(IS_IOS) // Wallet Sync Transport is not enabled. - personal_data().SetSyncAndSignInState( - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled); + personal_data().SetIsPaymentsWalletSyncTransportEnabled(false); // Create, fill and submit an address form in order to establish a recent // profile which can be selected for the upload request.
diff --git a/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc b/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc index b9ae91e7..77a7345 100644 --- a/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc +++ b/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc
@@ -34,7 +34,6 @@ #include "components/autofill/core/browser/payments/test_local_card_migration_manager.h" #include "components/autofill/core/browser/payments/test_payments_client.h" #include "components/autofill/core/browser/personal_data_manager.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/browser/test_autofill_driver.h" @@ -407,8 +406,7 @@ // Trigger migration if user only signs in. TEST_F(LocalCardMigrationManagerTest, MigrateCreditCard_SignInOnly) { // Mock Chrome Sync is disabled. - local_card_migration_manager_->ResetSyncState( - AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled); + local_card_migration_manager_->EnablePaymentsWalletSyncInTransportMode(); // Use one local card with more valid local cards available. UseLocalCardWithOtherLocalCardsOnFile();
diff --git a/components/autofill/core/browser/payments/test_local_card_migration_manager.cc b/components/autofill/core/browser/payments/test_local_card_migration_manager.cc index 4527306..7676c613 100644 --- a/components/autofill/core/browser/payments/test_local_card_migration_manager.cc +++ b/components/autofill/core/browser/payments/test_local_card_migration_manager.cc
@@ -52,9 +52,8 @@ LocalCardMigrationManager::OnUserAcceptedMainMigrationDialog(selected_cards); } -void TestLocalCardMigrationManager::ResetSyncState( - AutofillSyncSigninState sync_state) { - personal_data_manager_->SetSyncAndSignInState(sync_state); +void TestLocalCardMigrationManager::EnablePaymentsWalletSyncInTransportMode() { + personal_data_manager_->SetIsPaymentsWalletSyncTransportEnabled(true); } void TestLocalCardMigrationManager::OnDidGetUploadDetails(
diff --git a/components/autofill/core/browser/payments/test_local_card_migration_manager.h b/components/autofill/core/browser/payments/test_local_card_migration_manager.h index 75d3d80..b440626c 100644 --- a/components/autofill/core/browser/payments/test_local_card_migration_manager.h +++ b/components/autofill/core/browser/payments/test_local_card_migration_manager.h
@@ -12,7 +12,6 @@ #include "base/memory/raw_ptr.h" #include "components/autofill/core/browser/payments/local_card_migration_manager.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/test_personal_data_manager.h" namespace autofill { @@ -60,9 +59,10 @@ void OnUserAcceptedMainMigrationDialog( const std::vector<std::string>& selected_cards) override; - // Mock the Chrome Sync state in the LocalCardMigrationManager. If not set, - // default to AutofillSyncSigninState::kSignedInAndSyncFeature. - void ResetSyncState(AutofillSyncSigninState sync_state); + // By default, the `LocalCardMigrationManager` syncing state is "signed in + // and sync-the-feature enabled". Using this function, tests can simulate + // sync transport mode. + void EnablePaymentsWalletSyncInTransportMode(); private: void OnDidGetUploadDetails(
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index af0b97e..80e63ce 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -723,35 +723,53 @@ } bool PersonalDataManager::IsPaymentsDownloadActive() const { - return GetSyncSigninState() == - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled || - GetSyncSigninState() == - AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled; + if (!sync_service_ || !identity_manager_ || + sync_service_->GetAccountInfo().IsEmpty() || + sync_service_->GetTransportState() == + syncer::SyncService::TransportState::PAUSED) { + return false; + } + return sync_service_->IsSyncFeatureEnabled() || + sync_service_->GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA); } -AutofillSyncSigninState PersonalDataManager::GetSyncSigninState() const { +bool PersonalDataManager::IsPaymentsWalletSyncTransportEnabled() const { + if (!sync_service_ || !identity_manager_ || + sync_service_->GetAccountInfo().IsEmpty() || + sync_service_->GetTransportState() == + syncer::SyncService::TransportState::PAUSED) { + return false; + } + return !sync_service_->IsSyncFeatureEnabled() && + sync_service_->GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA); +} + +AutofillMetrics::PaymentsSigninState +PersonalDataManager::GetPaymentsSigninStateForMetrics() const { + using PaymentsSigninState = AutofillMetrics::PaymentsSigninState; + // Check if the user is signed out. if (!sync_service_ || !identity_manager_ || sync_service_->GetAccountInfo().IsEmpty()) { - return AutofillSyncSigninState::kSignedOut; + return PaymentsSigninState::kSignedOut; } if (sync_service_->GetTransportState() == syncer::SyncService::TransportState::PAUSED) { - return AutofillSyncSigninState::kSyncPaused; + return PaymentsSigninState::kSyncPaused; } // Check if the user has turned on sync. if (sync_service_->IsSyncFeatureEnabled()) { - return AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled; + return PaymentsSigninState::kSignedInAndSyncFeatureEnabled; } // Check if Wallet data types are supported. if (sync_service_->GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA)) { - return AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled; + return PaymentsSigninState::kSignedInAndWalletSyncTransportEnabled; } - return AutofillSyncSigninState::kSignedIn; + return PaymentsSigninState::kSignedIn; } void PersonalDataManager::AddObserver(PersonalDataManagerObserver* observer) { @@ -2511,8 +2529,7 @@ } void PersonalDataManager::OnUserAcceptedCardsFromAccountOption() { - DCHECK_EQ(AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled, - GetSyncSigninState()); + DCHECK(IsPaymentsWalletSyncTransportEnabled()); prefs::SetUserOptedInWalletSyncTransport( pref_service_, sync_service_->GetAccountInfo().account_id, /*opted_in=*/true); @@ -2571,13 +2588,12 @@ } void PersonalDataManager::LogServerCardLinkClicked() const { - AutofillMetrics::LogServerCardLinkClicked(GetSyncSigninState()); + AutofillMetrics::LogServerCardLinkClicked(GetPaymentsSigninStateForMetrics()); } void PersonalDataManager::OnUserAcceptedUpstreamOffer() { // If the user is in sync transport mode for Wallet, record an opt-in. - if (GetSyncSigninState() == - AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled) { + if (IsPaymentsWalletSyncTransportEnabled()) { prefs::SetUserOptedInWalletSyncTransport( pref_service_, sync_service_->GetAccountInfo().account_id, /*opted_in=*/true);
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index da9c777e..e0291d0d 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -28,6 +28,7 @@ #include "components/autofill/core/browser/data_model/iban.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/geo/alternative_state_name_map_updater.h" +#include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/payments/account_info_getter.h" #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/personal_data_manager_cleaner.h" @@ -36,7 +37,6 @@ #include "components/autofill/core/browser/strike_databases/autofill_profile_save_strike_database.h" #include "components/autofill/core/browser/strike_databases/autofill_profile_update_strike_database.h" #include "components/autofill/core/browser/strike_databases/strike_database_base.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/ui/suggestion.h" #include "components/autofill/core/browser/webdata/autofill_change.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" @@ -168,11 +168,17 @@ // the user is not signed-in or the identity manager is not available. absl::optional<CoreAccountInfo> GetPrimaryAccountInfo() const; - // Returns whether credit card download is active (sync as a transport). + // Returns whether credit card download is active (meaning that wallet sync is + // running at least in transport mode). bool IsPaymentsDownloadActive() const; - // Returns the current sync status. - virtual AutofillSyncSigninState GetSyncSigninState() const; + // Returns true if wallet sync is running in transport mode (meaning that + // Sync-the-feature is disabled). + virtual bool IsPaymentsWalletSyncTransportEnabled() const; + + // Returns the current sync status for the purpose of metrics only (do not + // guard actual logic behind this value). + AutofillMetrics::PaymentsSigninState GetPaymentsSigninStateForMetrics() const; // Adds a listener to be notified of PersonalDataManager events. virtual void AddObserver(PersonalDataManagerObserver* observer);
diff --git a/components/autofill/core/browser/personal_data_manager_unittest.cc b/components/autofill/core/browser/personal_data_manager_unittest.cc index 49bf67f..d3d1e03b 100644 --- a/components/autofill/core/browser/personal_data_manager_unittest.cc +++ b/components/autofill/core/browser/personal_data_manager_unittest.cc
@@ -39,7 +39,6 @@ #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/payments/mandatory_reauth_metrics.h" #include "components/autofill/core/browser/personal_data_manager_test_base.h" -#include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/browser/ui/label_formatter_utils.h" #include "components/autofill/core/browser/ui/suggestion.h" @@ -1505,8 +1504,7 @@ // Sign out. identity_test_env_.ClearPrimaryAccount(); sync_service_.SetAccountInfo(CoreAccountInfo()); - EXPECT_EQ(AutofillSyncSigninState::kSignedOut, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE(sync_service_.GetAccountInfo().IsEmpty()); EXPECT_EQ(0U, personal_data_->GetCreditCards().size()); // Add local card. @@ -1528,8 +1526,9 @@ identity_test_env_.identity_manager()->GetPrimaryAccountInfo( signin::ConsentLevel::kSync)); sync_service_.SetHasSyncConsent(true); - EXPECT_EQ(AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE( + sync_service_.IsSyncFeatureEnabled() && + sync_service_.GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA)); ASSERT_TRUE(TurnOnSyncFeature()); // Check saved local card should be not lost. @@ -4453,7 +4452,8 @@ #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) && // !BUILDFLAG(IS_CHROMEOS_ASH) -TEST_F(PersonalDataManagerSyncTransportModeTest, GetSyncSigninState) { +TEST_F(PersonalDataManagerSyncTransportModeTest, + GetPaymentsSigninStateForMetrics) { // Make sure a non-sync-consented account is available for the first tests. ASSERT_TRUE(identity_test_env_.identity_manager()->HasPrimaryAccount( signin::ConsentLevel::kSignin)); @@ -4463,8 +4463,9 @@ /*types=*/{syncer::UserSelectableType::kAutofill, syncer::UserSelectableType::kPayments}); - EXPECT_EQ(AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled, - personal_data_->GetSyncSigninState()); + EXPECT_EQ(AutofillMetrics::PaymentsSigninState:: + kSignedInAndWalletSyncTransportEnabled, + personal_data_->GetPaymentsSigninStateForMetrics()); // Check that the sync state is |SignedIn| if the sync service does not have // wallet data active. @@ -4472,15 +4473,15 @@ /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet( {syncer::UserSelectableType::kAutofill})); - EXPECT_EQ(AutofillSyncSigninState::kSignedIn, - personal_data_->GetSyncSigninState()); + EXPECT_EQ(AutofillMetrics::PaymentsSigninState::kSignedIn, + personal_data_->GetPaymentsSigninStateForMetrics()); // Nothing should change if |kAutofill| is also removed. sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet()); - EXPECT_EQ(AutofillSyncSigninState::kSignedIn, - personal_data_->GetSyncSigninState()); + EXPECT_EQ(AutofillMetrics::PaymentsSigninState::kSignedIn, + personal_data_->GetPaymentsSigninStateForMetrics()); // ClearPrimaryAccount is not supported on CrOS. #if !BUILDFLAG(IS_CHROMEOS_ASH) @@ -4489,8 +4490,8 @@ identity_test_env_.ClearPrimaryAccount(); sync_service_.SetAccountInfo(CoreAccountInfo()); sync_service_.SetHasSyncConsent(false); - EXPECT_EQ(AutofillSyncSigninState::kSignedOut, - personal_data_->GetSyncSigninState()); + EXPECT_EQ(AutofillMetrics::PaymentsSigninState::kSignedOut, + personal_data_->GetPaymentsSigninStateForMetrics()); } #endif @@ -4507,8 +4508,9 @@ // Check that the sync state is |SignedInAndSyncFeature| if the sync feature // is enabled. - EXPECT_EQ(AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled, - personal_data_->GetSyncSigninState()); + EXPECT_EQ( + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled, + personal_data_->GetPaymentsSigninStateForMetrics()); } // On mobile, no dedicated opt-in is required for WalletSyncTransport - the @@ -4541,8 +4543,9 @@ // Account wallet storage only makes sense together with support for // unconsented primary accounts, i.e. on Win/Mac/Linux. #if !BUILDFLAG(IS_CHROMEOS_ASH) - EXPECT_EQ(AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE( + !sync_service_.IsSyncFeatureEnabled() && + sync_service_.GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA)); // Make sure an opt-in gets recorded if the user accepted an Upstream offer. personal_data_->OnUserAcceptedUpstreamOffer(); @@ -4562,9 +4565,7 @@ sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/syncer::UserSelectableTypeSet()); - - EXPECT_EQ(AutofillSyncSigninState::kSignedIn, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE(!sync_service_.GetAccountInfo().IsEmpty()); // Make sure an opt-in does not get recorded even if the user accepted an // Upstream offer. @@ -4584,8 +4585,7 @@ sync_service_.SetAccountInfo(CoreAccountInfo()); sync_service_.SetHasSyncConsent(false); { - EXPECT_EQ(AutofillSyncSigninState::kSignedOut, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE(sync_service_.GetAccountInfo().IsEmpty()); // Make sure an opt-in does not get recorded even if the user accepted an // Upstream offer. @@ -4603,8 +4603,7 @@ sync_service_.SetAccountInfo(active_info); sync_service_.SetHasSyncConsent(true); { - EXPECT_EQ(AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled, - personal_data_->GetSyncSigninState()); + EXPECT_TRUE(sync_service_.IsSyncFeatureEnabled()); // Make sure an opt-in does not get recorded even if the user accepted an // Upstream offer.
diff --git a/components/autofill/core/browser/single_field_form_fill_router_unittest.cc b/components/autofill/core/browser/single_field_form_fill_router_unittest.cc index dad60e1e..28b7ddc 100644 --- a/components/autofill/core/browser/single_field_form_fill_router_unittest.cc +++ b/components/autofill/core/browser/single_field_form_fill_router_unittest.cc
@@ -81,8 +81,8 @@ std::make_unique<SingleFieldFormFillRouter>( autocomplete_history_manager_.get(), iban_manager_.get(), merchant_promo_code_manager_.get()); - test::CreateTestFormField(/*label=*/"", "Some Field Name", "SomePrefix", - "SomeType", &test_field_); + test_field_ = test::CreateTestFormField(/*label=*/"", "Some Field Name", + "SomePrefix", "SomeType"); } base::test::ScopedFeatureList scoped_feature_list_async_parse_form_;
diff --git a/components/autofill/core/browser/sync_utils.h b/components/autofill/core/browser/sync_utils.h deleted file mode 100644 index c89175a..0000000 --- a/components/autofill/core/browser/sync_utils.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_SYNC_UTILS_H_ -#define COMPONENTS_AUTOFILL_CORE_BROWSER_SYNC_UTILS_H_ - -namespace autofill { - -// Since these values are persisted to logs, they should not be re-numbered or -// removed. -enum AutofillSyncSigninState { - // The user is not signed in to Chromium. - kSignedOut, - // The user is signed in to Chromium. - kSignedIn, - // The user is signed in to Chromium and sync transport is active for Wallet - // data. - kSignedInAndWalletSyncTransportEnabled, - // The user is signed in, has enabled the sync feature and has not disabled - // Wallet sync. - kSignedInAndSyncFeatureEnabled, - // The user has enabled the sync feature, but has then signed out, so sync is - // paused. - kSyncPaused, - kNumSyncStates, -}; - -} // namespace autofill - -#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_SYNC_UTILS_H_
diff --git a/components/autofill/core/browser/test_personal_data_manager.cc b/components/autofill/core/browser/test_personal_data_manager.cc index 9545728..09012d29 100644 --- a/components/autofill/core/browser/test_personal_data_manager.cc +++ b/components/autofill/core/browser/test_personal_data_manager.cc
@@ -18,8 +18,11 @@ TestPersonalDataManager::~TestPersonalDataManager() = default; -AutofillSyncSigninState TestPersonalDataManager::GetSyncSigninState() const { - return sync_and_signin_state_; +bool TestPersonalDataManager::IsPaymentsWalletSyncTransportEnabled() const { + if (payments_wallet_sync_transport_enabled_.has_value()) { + return *payments_wallet_sync_transport_enabled_; + } + return PersonalDataManager::IsPaymentsWalletSyncTransportEnabled(); } void TestPersonalDataManager::RecordUseOf(
diff --git a/components/autofill/core/browser/test_personal_data_manager.h b/components/autofill/core/browser/test_personal_data_manager.h index 4d447dd..bb1875f 100644 --- a/components/autofill/core/browser/test_personal_data_manager.h +++ b/components/autofill/core/browser/test_personal_data_manager.h
@@ -42,7 +42,7 @@ // PersonalDataManager overrides. These functions are overridden as needed // for various tests, whether to skip calls to uncreated databases/services, // or to make things easier in general to toggle. - AutofillSyncSigninState GetSyncSigninState() const override; + bool IsPaymentsWalletSyncTransportEnabled() const override; void RecordUseOf(absl::variant<const AutofillProfile*, const CreditCard*> profile_or_credit_card) override; std::string SaveImportedCreditCard( @@ -156,8 +156,8 @@ payments_customer_data_ = std::move(customer_data); } - void SetSyncAndSignInState(AutofillSyncSigninState sync_and_signin_state) { - sync_and_signin_state_ = sync_and_signin_state; + void SetIsPaymentsWalletSyncTransportEnabled(bool enabled) { + payments_wallet_sync_transport_enabled_ = enabled; } void SetAccountInfoForPayments(const CoreAccountInfo& account_info) { @@ -176,8 +176,7 @@ absl::optional<bool> autofill_wallet_import_enabled_; absl::optional<bool> eligible_for_account_storage_; absl::optional<bool> payment_methods_mandatory_reauth_enabled_; - AutofillSyncSigninState sync_and_signin_state_ = - AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled; + absl::optional<bool> payments_wallet_sync_transport_enabled_; CoreAccountInfo account_info_; TestInMemoryStrikeDatabase inmemory_strike_database_;
diff --git a/components/autofill/core/browser/ui/popup_item_ids.h b/components/autofill/core/browser/ui/popup_item_ids.h index f4bbb75..3ce4988 100644 --- a/components/autofill/core/browser/ui/popup_item_ids.h +++ b/components/autofill/core/browser/ui/popup_item_ids.h
@@ -25,6 +25,9 @@ // form. We need it as a separate id from `kAddressEntry` because it has a // different UI and for logging. kFillEverythingFromAddressProfile, + // When triggered from a phone number field this suggestion will fill every + // phone number field. + kFillFullPhoneNumber, kAutocompleteEntry, kInsecureContextPaymentDisabledMessage, kPasswordEntry,
diff --git a/components/autofill/core/browser/ui/suggestion_selection.cc b/components/autofill/core/browser/ui/suggestion_selection.cc index b4bfca6..7ab6b58 100644 --- a/components/autofill/core/browser/ui/suggestion_selection.cc +++ b/components/autofill/core/browser/ui/suggestion_selection.cc
@@ -66,8 +66,6 @@ } // Creates the suggestion that will open the delete address profile dialog. -// TODO(crbug.com/1459990): Use this once the new popup with submenus -// implementation is complete. Suggestion GetDeleteAddressProfileSuggestion(Suggestion::BackendId backend_id) { Suggestion suggestion(l10n_util::GetStringUTF16( IDS_AUTOFILL_DELETE_ADDRESS_PROFILE_POPUP_OPTION_SELECTED)); @@ -80,8 +78,6 @@ } // Creates the suggestion that will fill all address related fields. -// TODO(crbug.com/1459990): Use this once the new submenu implementation is -// complete. Suggestion GetFillFullAddressSuggestion(Suggestion::BackendId backend_id) { Suggestion suggestion(l10n_util::GetStringUTF16( IDS_AUTOFILL_FILL_ADDRESS_GROUP_POPUP_OPTION_SELECTED)); @@ -93,8 +89,6 @@ } // Creates the suggestion that will fill all name related fields. -// TODO(crbug.com/1459990): Use this once the delete the new popup with submenus -// implementation is complete. Suggestion GetFillFullNameSuggestion(Suggestion::BackendId backend_id) { Suggestion suggestion(l10n_util::GetStringUTF16( IDS_AUTOFILL_FILL_NAME_GROUP_POPUP_OPTION_SELECTED)); @@ -123,6 +117,7 @@ IDS_AUTOFILL_A11Y_ANNOUNCE_FILL_EVERYTHING_FROM_ADDRESS_PROFILE_POPUP_OPTION_SELECTED); return suggestion; } + // Append new suggestions to `suggestions` based on the `ServerFieldType` list // provided. Suggestions are not added if their info is not found in the // provided `profile`. Returns true if any suggestion was added. @@ -154,6 +149,9 @@ } // Adds name related child suggestions to build autofill popup submenu. +// The param `type` refers to the triggering field type (clicked by the users) +// and is used to define whether the `PopupItemId::kFillFullName` suggestion +// will be available. void AddNameChildSuggestions(const AutofillType& type, const AutofillProfile& profile, const std::string& app_locale, @@ -173,7 +171,57 @@ }; } +// Adds address line suggestions (ADDRESS_HOME_LINE1 and/or +// ADDRESS_HOME_LINE2) to `suggestions.children`. It potentially includes +// sub-children if one of the added suggestions contains +// ADDRESS_HOME_HOUSE_NUMBER and/or ADDRESS_HOME_STREET_NAME. Returns true if at +// least one suggestion was appended to `suggestions.children`. +bool AddAddressLineChildSuggestions(const AutofillProfile& profile, + const std::string& app_locale, + std::vector<Suggestion>& suggestions) { + auto add_address_line = [&](ServerFieldType type) -> bool { + CHECK(type == ADDRESS_HOME_LINE1 || type == ADDRESS_HOME_LINE2); + + if (!AddFieldByFieldSuggestions({type}, profile, app_locale, suggestions)) { + return false; + } + + if (CheckIfTypeContainsSubtype(type, ADDRESS_HOME_HOUSE_NUMBER, profile, + app_locale) && + AddFieldByFieldSuggestions({ADDRESS_HOME_HOUSE_NUMBER}, profile, + app_locale, suggestions.back().children)) { + Suggestion& address_line_suggestion = suggestions.back().children.back(); + address_line_suggestion.labels = { + {Suggestion::Text(l10n_util::GetStringUTF16( + IDS_AUTOFILL_HOUSE_NUMBER_SUGGESTION_SECONDARY_TEXT))}}; + address_line_suggestion + .acceptance_a11y_announcement = l10n_util::GetStringUTF16( + IDS_AUTOFILL_HOUSE_NUMBER_SUGGESTION_SECONDARY_TEXT_OPTION_SELECTED); + } + if (CheckIfTypeContainsSubtype(type, ADDRESS_HOME_STREET_NAME, profile, + app_locale) && + AddFieldByFieldSuggestions({ADDRESS_HOME_STREET_NAME}, profile, + app_locale, suggestions.back().children)) { + Suggestion& address_line_suggestion = suggestions.back().children.back(); + address_line_suggestion.labels = { + {Suggestion::Text(l10n_util::GetStringUTF16( + IDS_AUTOFILL_STREET_NAME_SUGGESTION_SECONDARY_TEXT))}}; + address_line_suggestion + .acceptance_a11y_announcement = l10n_util::GetStringUTF16( + IDS_AUTOFILL_STREET_NAME_SUGGESTION_SECONDARY_TEXT_OPTION_SELECTED); + } + + return true; + }; + bool added_address_line1 = add_address_line(ADDRESS_HOME_LINE1); + bool added_address_line2 = add_address_line(ADDRESS_HOME_LINE2); + return added_address_line1 || added_address_line2; +} + // Adds address related child suggestions to build autofill popup submenu. +// The param `type` refers to the triggering field type (clicked by the users) +// and is used to define whether the `PopupItemId::kFillFullAddress` suggestion +// will be available. void AddAddressChildSuggestions(const AutofillType& type, const AutofillProfile& profile, const std::string& app_locale, @@ -187,53 +235,49 @@ GetFillFullAddressSuggestion(Suggestion::BackendId(profile.guid()))); } - // Adds a suggestion of `type` (where type is an address line) and - // potentially includes children if the suggestion contains - // ADDRESS_HOME_HOUSE_NUMBER and/or ADDRESS_HOME_STREET_NAME. - auto add_address_line = [&](ServerFieldType type) -> bool { - CHECK(type == ADDRESS_HOME_LINE1 || type == ADDRESS_HOME_LINE2); - bool added_address_line = AddFieldByFieldSuggestions( - {type}, profile, app_locale, suggestion.children); - if (added_address_line) { - if (CheckIfTypeContainsSubtype(type, ADDRESS_HOME_HOUSE_NUMBER, profile, - app_locale)) { - AddFieldByFieldSuggestions({ADDRESS_HOME_HOUSE_NUMBER}, profile, - app_locale, - suggestion.children.back().children); - } - if (CheckIfTypeContainsSubtype(type, ADDRESS_HOME_STREET_NAME, profile, - app_locale)) { - AddFieldByFieldSuggestions({ADDRESS_HOME_STREET_NAME}, profile, - app_locale, - suggestion.children.back().children); - } - } - - return added_address_line; - }; - - bool added_address_line1 = add_address_line(ADDRESS_HOME_LINE1); - bool added_address_line2 = add_address_line(ADDRESS_HOME_LINE2); + bool added_any_address_line = + AddAddressLineChildSuggestions(profile, app_locale, suggestion.children); bool added_zip = AddFieldByFieldSuggestions({ADDRESS_HOME_ZIP}, profile, app_locale, suggestion.children); - if (added_address_line1 || added_address_line2 || added_zip) { + if (added_any_address_line || added_zip) { suggestion.children.push_back( AutofillSuggestionGenerator::CreateSeparator()); } } // Adds contact related child suggestions (i.e email and phone number) to -// build autofill popup submenu. -void AddContactChildSuggestions(const AutofillProfile& profile, +// build autofill popup submenu. The param `type` refers to the triggering field +// type (clicked by the users) and is used to define whether the phone number +// suggestion will behave as `PopupItemId::kFieldByFieldFilling` or as +// `PopupItemId::kFillFullPhoneNumber`. +void AddContactChildSuggestions(const AutofillType& type, + const AutofillProfile& profile, const std::string& app_locale, Suggestion& suggestion) { - // TODO(crbug.com/1459990): Create phone number suggestion. + // Creates a phone number suggestion for the autofill submenu. When triggered + // from a phone number field this suggestion will fill every phone number + // field. Otherwise it fills a specific field. + bool phone_number_suggestion_added = false; + if (profile.HasInfo(PHONE_HOME_WHOLE_NUMBER)) { + Suggestion phone_number_suggestion( + profile.GetInfo(PHONE_HOME_WHOLE_NUMBER, app_locale)); + const bool is_phone_field = type.group() == FieldTypeGroup::kPhoneHome || + type.group() == FieldTypeGroup::kPhoneBilling; + phone_number_suggestion.popup_item_id = + is_phone_field ? PopupItemId::kFillFullPhoneNumber + : PopupItemId::kFieldByFieldFilling; + phone_number_suggestion.payload = Suggestion::BackendId(profile.guid()); + suggestion.children.push_back(std::move(phone_number_suggestion)); + phone_number_suggestion_added = true; + } if (AddFieldByFieldSuggestions({EMAIL_ADDRESS}, profile, app_locale, - suggestion.children)) { + suggestion.children) || + phone_number_suggestion_added) { suggestion.children.push_back( AutofillSuggestionGenerator::CreateSeparator()); } } + // Adds footer child suggestions to build autofill popup submenu. void AddFooterChildSuggestions(const AutofillProfile& profile, Suggestion& suggestion) { @@ -256,7 +300,7 @@ Suggestion& suggestion) { AddNameChildSuggestions(type, profile, app_locale, suggestion); AddAddressChildSuggestions(type, profile, app_locale, suggestion); - AddContactChildSuggestions(profile, app_locale, suggestion); + AddContactChildSuggestions(type, profile, app_locale, suggestion); AddFooterChildSuggestions(profile, suggestion); }
diff --git a/components/autofill/core/browser/ui/suggestion_selection_unittest.cc b/components/autofill/core/browser/ui/suggestion_selection_unittest.cc index d6625e735..4d1f64f 100644 --- a/components/autofill/core/browser/ui/suggestion_selection_unittest.cc +++ b/components/autofill/core/browser/ui/suggestion_selection_unittest.cc
@@ -196,8 +196,11 @@ Not(u"Marie")))); } +// TODO(crbug.com/1459990): Consider having a test fixture for granular filling +// related tests. In general these tests are quite lengthy and finding a way to +// make them more concise is desirable. TEST_F(SuggestionSelectionTest, - GetPrefixMatchedSuggestions_ChildrenSuggestions) { + GetPrefixMatchedSuggestions_FirstLevelChildrenSuggestions) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( features::kAutofillGranularFillingAvailable); @@ -230,11 +233,12 @@ // 7. address line 2 // 8. Zip // 9. line separator - // 10. email - // 11. line separator - // 12. edit profile - // 13. delete address - ASSERT_EQ(13U, suggestions[0].children.size()); + // 10. phone number + // 11. email + // 12. line separator + // 13. edit profile + // 14. delete address + ASSERT_EQ(14U, suggestions[0].children.size()); EXPECT_THAT( suggestions[0].children, ElementsAre( @@ -261,13 +265,31 @@ EqualsSuggestion(PopupItemId::kSeparator), EqualsSuggestion( PopupItemId::kFieldByFieldFilling, + profile.GetInfo(ServerFieldType::PHONE_HOME_WHOLE_NUMBER, + app_locale)), + EqualsSuggestion( + PopupItemId::kFieldByFieldFilling, profile.GetInfo(ServerFieldType::EMAIL_ADDRESS, app_locale)), EqualsSuggestion(PopupItemId::kSeparator), EqualsSuggestion(PopupItemId::kEditAddressProfile), EqualsSuggestion(PopupItemId::kDeleteAddressProfile))); +} - // The address line 1 (sixth child) suggestion should have the following - // children: house number street name +TEST_F(SuggestionSelectionTest, + GetPrefixMatchedSuggestions_SecondLevelChildrenSuggestions) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kAutofillGranularFillingAvailable); + + AutofillProfile profile = test::GetFullProfile(); + std::string app_locale = comparator_.app_locale(); + std::vector<AutofillProfile*> matched_profiles; + auto suggestions = GetPrefixMatchedSuggestions( + AutofillType(NAME_FIRST), u"", GetCanonicalUtf16Content(""), app_locale, + /*field_is_autofilled=*/false, {&profile}, &matched_profiles); + + // We should have two levels of children, The address line 1 (sixth child) + // suggestion should have the following children: house number street name. ASSERT_EQ(2U, suggestions[0].children[5].children.size()); EXPECT_THAT( suggestions[0].children[5].children, @@ -280,6 +302,53 @@ PopupItemId::kFieldByFieldFilling, profile.GetInfo(ServerFieldType::ADDRESS_HOME_STREET_NAME, app_locale)))); + // House number and street name suggestions should have labels. + EXPECT_EQ(suggestions[0].children[5].children[0].labels, + std::vector<std::vector<Suggestion::Text>>( + {{Suggestion::Text(u"Building number")}})); + EXPECT_EQ(suggestions[0].children[5].children[1].labels, + std::vector<std::vector<Suggestion::Text>>( + {{Suggestion::Text(u"Street")}})); +} + +// Asserts that when the triggering field is a phone field, the phone number +// suggestion is of type `PopupItemId::kFillFullPhoneNumber`. In other +// scenarios, phone number is of type `PopupItemId::kFieldByFieldFilling` as the +// user expressed intent to use their phone number their phone number on a +// "random" field. +TEST_F(SuggestionSelectionTest, + GetPrefixMatchedSuggestions_ChildrenSuggestionsPhoneField) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature( + features::kAutofillGranularFillingAvailable); + + AutofillProfile profile = test::GetFullProfile(); + std::string app_locale = comparator_.app_locale(); + std::vector<AutofillProfile*> matched_profiles; + auto suggestions = GetPrefixMatchedSuggestions( + AutofillType(PHONE_HOME_WHOLE_NUMBER), u"", GetCanonicalUtf16Content(""), + app_locale, + /*field_is_autofilled=*/false, {&profile}, &matched_profiles); + + // The child suggestions should be: + // + // 1. first name + // 2. middle name + // 3. family name + // 4. line separator + // 5. address line 1 + // 6. address line 2 + // 7. Zip + // 8. line separator + // 9. phone number + // 10. email + // 11. line separator + // 12. edit profile + // 13. delete address + ASSERT_EQ(13U, suggestions[0].children.size()); + EXPECT_THAT( + suggestions[0].children[8], + Field(&Suggestion::popup_item_id, PopupItemId::kFillFullPhoneNumber)); } TEST_F(SuggestionSelectionTest, @@ -306,11 +375,12 @@ // 7. address line 2 // 8. Zip // 9. line separator - // 10. email - // 11. line separator - // 12. edit address - // 13. delete address - ASSERT_EQ(13U, suggestions[0].children.size()); + // 10. phone number + // 11. email + // 12. line separator + // 13. edit address + // 14. delete address + ASSERT_EQ(14U, suggestions[0].children.size()); EXPECT_THAT(suggestions[0].children[4], Field(&Suggestion::popup_item_id, PopupItemId::kFillFullAddress)); }
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 988fe4d..8e8f8e9 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -545,6 +545,12 @@ "AutofillGranularFillingAvailable", base::FEATURE_DISABLED_BY_DEFAULT); +// Controls whether testing forms using devtools will be available. +// TODO(crbug.com/1459990): Clean up when launched. +BASE_FEATURE(kAutofillTestFormWithDevtools, + "AutofillTestFormWithDevtools", + base::FEATURE_DISABLED_BY_DEFAULT); + // Allows silent profile updates even when the profile import requirements are // not met. BASE_FEATURE(kAutofillSilentProfileUpdateForInsufficientImport, @@ -562,7 +568,7 @@ // TODO(crbug.com/1419578): Remove when launched. BASE_FEATURE(kAutofillSplitCreditCardNumbersCautiously, "AutofillSplitCreditCardNumbersCautiously", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); // Controls whether Autofill should search prefixes of all words/tokens when // filtering profiles, or only on prefixes of the whole string.
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index c7f6943..bf9e3c5 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -185,6 +185,8 @@ COMPONENT_EXPORT(AUTOFILL) BASE_DECLARE_FEATURE(kAutofillGranularFillingAvailable); COMPONENT_EXPORT(AUTOFILL) +BASE_DECLARE_FEATURE(kAutofillTestFormWithDevtools); +COMPONENT_EXPORT(AUTOFILL) BASE_DECLARE_FEATURE(kAutofillSilentProfileUpdateForInsufficientImport); COMPONENT_EXPORT(AUTOFILL) BASE_DECLARE_FEATURE(kAutofillSkipComparingInferredLabels);
diff --git a/components/autofill/core/common/autofill_regex_constants.h b/components/autofill/core/common/autofill_regex_constants.h index bd75ed3f..4724fc6 100644 --- a/components/autofill/core/common/autofill_regex_constants.h +++ b/components/autofill/core/common/autofill_regex_constants.h
@@ -92,7 +92,7 @@ u"|addresssuppl|complementnom|appartement" // fr-FR u"|indirizzo2" // it-IT u"|住所2" // ja-JP - u"|addrcomplement" // pt-BR, pt-PT + u"|complemento|addrcomplement" // pt-BR, pt-PT u"|Улица" // ru u"|地址2" // zh-CN u"|주소.?2"; // ko-KR
diff --git a/components/autofill/core/common/autofill_test_utils.cc b/components/autofill/core/common/autofill_test_utils.cc index 0a78a742..0780477 100644 --- a/components/autofill/core/common/autofill_test_utils.cc +++ b/components/autofill/core/common/autofill_test_utils.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include <string> #include <string_view> +#include <utility> #include <vector> #include "base/check.h" @@ -112,68 +113,40 @@ std::string_view value, std::string_view type) { FormFieldData field; - CreateTestFormField(label, name, value, type, &field); + field.host_frame = MakeLocalFrameToken(); + field.unique_renderer_id = MakeFieldRendererId(); + field.label = base::UTF8ToUTF16(label); + field.name = base::UTF8ToUTF16(name); + field.value = base::UTF8ToUTF16(value); + field.form_control_type = type; + field.is_focusable = true; return field; } -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - FormFieldData* field) { - field->host_frame = MakeLocalFrameToken(); - field->unique_renderer_id = MakeFieldRendererId(); - field->label = base::UTF8ToUTF16(label); - field->name = base::UTF8ToUTF16(name); - field->value = base::UTF8ToUTF16(value); - field->form_control_type = type; - field->is_focusable = true; -} - FormFieldData CreateTestFormField(std::string_view label, std::string_view name, std::string_view value, std::string_view type, std::string_view autocomplete) { - FormFieldData field; - CreateTestFormField(label, name, value, type, autocomplete, &field); + FormFieldData field = CreateTestFormField(label, name, value, type); + field.autocomplete_attribute = autocomplete; + field.parsed_autocomplete = ParseAutocompleteAttribute(autocomplete); return field; } -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - std::string_view autocomplete, - FormFieldData* field) { - CreateTestFormField(label, name, value, type, field); - field->autocomplete_attribute = autocomplete; - field->parsed_autocomplete = ParseAutocompleteAttribute(autocomplete); -} - FormFieldData CreateTestFormField(std::string_view label, std::string_view name, std::string_view value, std::string_view type, std::string_view autocomplete, uint64_t max_length) { - FormFieldData field; - CreateTestFormField(label, name, value, type, autocomplete, max_length, - &field); - return field; -} - -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - std::string_view autocomplete, - uint64_t max_length, - FormFieldData* field) { + FormFieldData field = CreateTestFormField(label, name, value, type); // First, set the `max_length`, as the `parsed_autocomplete` is set based on // this value. - field->max_length = max_length; - CreateTestFormField(label, name, value, type, autocomplete, field); + field.max_length = max_length; + field.autocomplete_attribute = autocomplete; + field.parsed_autocomplete = ParseAutocompleteAttribute(autocomplete); + return field; } FormFieldData CreateTestSelectField(std::string_view label,
diff --git a/components/autofill/core/common/autofill_test_utils.h b/components/autofill/core/common/autofill_test_utils.h index 5061d1d6..c172d34 100644 --- a/components/autofill/core/common/autofill_test_utils.h +++ b/components/autofill/core/common/autofill_test_utils.h
@@ -126,37 +126,18 @@ std::string_view name, std::string_view value, std::string_view type); -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - FormFieldData* field); [[nodiscard]] FormFieldData CreateTestFormField(std::string_view label, std::string_view name, std::string_view value, std::string_view type, std::string_view autocomplete); -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - std::string_view autocomplete, - FormFieldData* field); - [[nodiscard]] FormFieldData CreateTestFormField(std::string_view label, std::string_view name, std::string_view value, std::string_view type, std::string_view autocomplete, uint64_t max_length); -void CreateTestFormField(std::string_view label, - std::string_view name, - std::string_view value, - std::string_view type, - std::string_view autocomplete, - uint64_t max_length, - FormFieldData* field); // Provides a quick way to populate a select field. [[nodiscard]] FormFieldData CreateTestSelectField(
diff --git a/components/autofill_strings.grdp b/components/autofill_strings.grdp index 07032289..b7308504 100644 --- a/components/autofill_strings.grdp +++ b/components/autofill_strings.grdp
@@ -109,12 +109,11 @@ <message name="IDS_AUTOFILL_A11Y_ANNOUNCE_FILLED_FORM" desc="Screen reader announcement indicating that current form was autofilled."> The form was filled in </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> + <!--TODO(crbug.com/1459990): Align with writers about related strings and remove translateable=false--> <message name="IDS_AUTOFILL_A11Y_ANNOUNCE_EDIT_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="Screen reader announcement indicating that edit autofill profile option was selected." translateable="false"> The edit address option was selected </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> <message name="IDS_AUTOFILL_A11Y_ANNOUNCE_DELETE_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="Screen reader announcement indicating that delete autofill profile option was selected." translateable="false"> The delete address option was selected </message> @@ -123,7 +122,6 @@ The autofilled info was cleared from the form </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> <message name="IDS_AUTOFILL_A11Y_ANNOUNCE_FILL_ADDRESS_GROUP_POPUP_OPTION_SELECTED" desc="Screen reader announcement indicating that filling address fields option was selected." translateable="false"> The fill address fields option was selected </message> @@ -140,7 +138,6 @@ Fill full name </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> <message name="IDS_AUTOFILL_A11Y_ANNOUNCE_FILL_EVERYTHING_FROM_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="Screen reader announcement indicating that the fill everything option was selected." translateable="false"> The fill everything option was selected </message> @@ -153,17 +150,30 @@ Manage... </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> <message name="IDS_AUTOFILL_EDIT_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="The text displayed at the bottom of the Autofill sub meny to open the edit address profile dialog." meaning="Entry point to address profile deletion." translateable="false"> Edit address </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> <message name="IDS_AUTOFILL_DELETE_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="The text displayed at the bottom of the Autofill sub menu to open the delete address profile dialog." meaning="Entry point to address profile deletion." translateable="false"> Delete address </message> - <!--TODO(crbug.com/1459990): Align with writers about this string and remove translateable=false--> + <message name="IDS_AUTOFILL_HOUSE_NUMBER_SUGGESTION_SECONDARY_TEXT_OPTION_SELECTED" desc="The secondary text displayed on a house number suggestion was selected." meaning="The label for the house number field type store by autofill has been selected in the subpopup." translateable="false"> + Building number option selected + </message> + + <message name="IDS_AUTOFILL_STREET_NAME_SUGGESTION_SECONDARY_TEXT_OPTION_SELECTED" desc="The secondary text displayed on a street name suggestion was selected." meaning="The label for the street namefield type store by autofill has been selected in the subpopup." translateable="false"> + Street option selected + </message> + + <message name="IDS_AUTOFILL_HOUSE_NUMBER_SUGGESTION_SECONDARY_TEXT" desc="The secondary text displayed on a house number suggestion." meaning="The label for the house number field type store by autofill." translateable="false"> + Building number + </message> + + <message name="IDS_AUTOFILL_STREET_NAME_SUGGESTION_SECONDARY_TEXT" desc="The secondary text displayed on a street name suggestion." meaning="The label for the street namefield type store by autofill." translateable="false"> + Street + </message> + <message name="IDS_AUTOFILL_FILL_EVERYTHING_FROM_ADDRESS_PROFILE_POPUP_OPTION_SELECTED" desc="The text displayed at the footer of the Autofill sub menu to fill everything from the address profile." meaning="Fill every available information from the address profile." translateable="false"> Fill everything </message>
diff --git a/components/browser_sync/sync_api_component_factory_impl.cc b/components/browser_sync/sync_api_component_factory_impl.cc index 6bc87d13..86eadbd 100644 --- a/components/browser_sync/sync_api_component_factory_impl.cc +++ b/components/browser_sync/sync_api_component_factory_impl.cc
@@ -65,8 +65,8 @@ #include "components/sync_user_events/user_event_model_type_controller.h" #if BUILDFLAG(ENABLE_SUPERVISED_USERS) +#include "components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h" #include "components/supervised_user/core/browser/supervised_user_settings_service.h" -#include "components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h" #endif // BUILDFLAG(ENABLE_SUPERVISED_USER) #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -566,8 +566,8 @@ #if BUILDFLAG(ENABLE_SUPERVISED_USERS) if (supervised_user_settings_service_) { controllers.push_back( - std::make_unique<SupervisedUserSyncModelTypeController>( - syncer::SUPERVISED_USER_SETTINGS, dump_stack, + std::make_unique<SupervisedUserSettingsModelTypeController>( + dump_stack, sync_client_->GetModelTypeStoreService()->GetStoreFactory(), supervised_user_settings_service_->AsWeakPtr(), sync_client_->GetPrefService()));
diff --git a/components/browser_ui/styles/android/BUILD.gn b/components/browser_ui/styles/android/BUILD.gn index 7c28310..83eb27e9 100644 --- a/components/browser_ui/styles/android/BUILD.gn +++ b/components/browser_ui/styles/android/BUILD.gn
@@ -189,9 +189,11 @@ "java/res/drawable/ic_language.xml", "java/res/drawable/ic_lightbulb_24dp.xml", "java/res/drawable/ic_link_24dp.xml", + "java/res/drawable/ic_manage_search_24dp.xml", "java/res/drawable/ic_mic_off_white_24dp.xml", "java/res/drawable/ic_mic_white_24dp.xml", "java/res/drawable/ic_music_note_24dp.xml", + "java/res/drawable/ic_notification_add_24dp.xml", "java/res/drawable/ic_offline_pin_24dp_on_dark_bg.xml", "java/res/drawable/ic_offline_pin_24dp_on_light_bg.xml", "java/res/drawable/ic_outline_email_24dp.xml", @@ -222,6 +224,7 @@ "java/res/drawable/ic_warning_red_16dp.xml", "java/res/drawable/ic_warning_red_24dp.xml", "java/res/drawable/ic_web_asset_24dp.xml", + "java/res/drawable/ic_youtube_searched_for_24dp.xml", "java/res/drawable/smartphone_black_24dp.xml", "java/res/drawable/toolbar_hairline.xml", "java/res/values-night/colors.xml",
diff --git a/components/browser_ui/styles/android/java/res/drawable/ic_manage_search_24dp.xml b/components/browser_ui/styles/android/java/res/drawable/ic_manage_search_24dp.xml new file mode 100644 index 0000000..4e7c24b --- /dev/null +++ b/components/browser_ui/styles/android/java/res/drawable/ic_manage_search_24dp.xml
@@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2023 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="@macro/default_icon_color"> + <path + android:fillColor="@android:color/white" + android:pathData="M8 9H2V7h6v2zm0 3H2v2h6v-2zm12.59 7l-3.83-3.83c-.8.52-1.74.83-2.76.83-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5c0 1.02-.31 1.96-.83 2.75L22 17.59 20.59 19zM17 11c0-1.65-1.35-3-3-3s-3 1.35-3 3 1.35 3 3 3 3-1.35 3-3zM2 19h13v-2H2v2z"/> +</vector>
diff --git a/components/browser_ui/styles/android/java/res/drawable/ic_notification_add_24dp.xml b/components/browser_ui/styles/android/java/res/drawable/ic_notification_add_24dp.xml new file mode 100644 index 0000000..7f24709 --- /dev/null +++ b/components/browser_ui/styles/android/java/res/drawable/ic_notification_add_24dp.xml
@@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2022 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="@macro/default_icon_color"> + <path + android:fillColor="@android:color/white" + android:pathData="M20,7.69h-2.25V10h-1.5V7.69H14V6.31h2.25V4h1.5v2.31H20V7.69z M13.5,11v3h-7V9c0-1.93,1.57-3.5,3.5-3.5 c0.58,0,1.13,0.14,1.61,0.39l1.1-1.1C12.19,4.47,11.62,4.23,11,4.1V3c0-0.55-0.45-1-1-1S9,2.45,9,3v1.1C6.72,4.56,5,6.58,5,9v5H4 v1.5h12V14h-1v-3H13.5z M10,18c0.83,0,1.5-0.67,1.5-1.5h-3C8.5,17.33,9.17,18,10,18z"/> +</vector>
diff --git a/components/browser_ui/styles/android/java/res/drawable/ic_youtube_searched_for_24dp.xml b/components/browser_ui/styles/android/java/res/drawable/ic_youtube_searched_for_24dp.xml new file mode 100644 index 0000000..8595981 --- /dev/null +++ b/components/browser_ui/styles/android/java/res/drawable/ic_youtube_searched_for_24dp.xml
@@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2023 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="@macro/default_icon_color"> + <path + android:fillColor="@android:color/white" + android:pathData="M16.27 13.27c.77-1.07 1.24-2.36 1.24-3.77 0-3.59-2.91-6.5-6.5-6.5-3.46 0-6.28 2.7-6.48 6.11L3.22 7.79 1.8 9.21l3.71 3.71 3.71-3.71L7.8 7.79 6.56 9.04C6.79 6.77 8.68 5 11.01 5c2.49 0 4.5 2.01 4.5 4.5S13.5 14 11.01 14c-.86 0-1.65-.25-2.33-.67l-1.45 1.45C8.3 15.55 9.6 16 11.01 16c1.41 0 2.7-.47 3.77-1.24l5.73 5.73L22 19l-5.73-5.73z"/> +</vector>
diff --git a/components/commerce/core/android/shopping_service_android.cc b/components/commerce/core/android/shopping_service_android.cc index 51e78db..7bf9d34 100644 --- a/components/commerce/core/android/shopping_service_android.cc +++ b/components/commerce/core/android/shopping_service_android.cc
@@ -93,7 +93,7 @@ JNIEnv* env, const ScopedJavaGlobalRef<jobject>& callback, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ScopedJavaLocalRef<jobject> info_java_object(nullptr); if (info.has_value()) { info_java_object = Java_ShoppingService_createProductInfo(
diff --git a/components/commerce/core/android/shopping_service_android.h b/components/commerce/core/android/shopping_service_android.h index 3cbf3f4..4888e8e 100644 --- a/components/commerce/core/android/shopping_service_android.h +++ b/components/commerce/core/android/shopping_service_android.h
@@ -105,7 +105,7 @@ void HandleProductInfoCallback(JNIEnv* env, const ScopedJavaGlobalRef<jobject>& callback, const GURL& url, - const absl::optional<ProductInfo>& info); + const absl::optional<const ProductInfo>& info); void HandleMerchantInfoCallback(JNIEnv* env, const ScopedJavaGlobalRef<jobject>& callback,
diff --git a/components/commerce/core/shopping_service.cc b/components/commerce/core/shopping_service.cc index 92b1213c..e9a37bc 100644 --- a/components/commerce/core/shopping_service.cc +++ b/components/commerce/core/shopping_service.cc
@@ -220,8 +220,8 @@ service->HandleOptGuideProductInfoResponse( url, web_wrapper.get(), - base::BindOnce( - [](const GURL&, const absl::optional<ProductInfo>&) {}), + base::BindOnce([](const GURL&, + const absl::optional<const ProductInfo>&) {}), decision, metadata); service->PDPMetricsCallback(web_wrapper->IsOffTheRecord(), decision,
diff --git a/components/commerce/core/shopping_service.h b/components/commerce/core/shopping_service.h index 3ce1b8e1..8f60caf 100644 --- a/components/commerce/core/shopping_service.h +++ b/components/commerce/core/shopping_service.h
@@ -253,7 +253,8 @@ // Callbacks for querying a single URL or observing information from all // navigated urls. using ProductInfoCallback = - base::OnceCallback<void(const GURL&, const absl::optional<ProductInfo>&)>; + base::OnceCallback<void(const GURL&, + const absl::optional<const ProductInfo>&)>; using MerchantInfoCallback = base::OnceCallback<void(const GURL&, absl::optional<MerchantInfo>)>; using PriceInsightsInfoCallback =
diff --git a/components/commerce/core/shopping_service_unittest.cc b/components/commerce/core/shopping_service_unittest.cc index d65d5a5..8f3b205 100644 --- a/components/commerce/core/shopping_service_unittest.cc +++ b/components/commerce/core/shopping_service_unittest.cc
@@ -105,7 +105,7 @@ GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_TRUE(info.has_value()); @@ -139,7 +139,7 @@ shopping_service_->GetProductInfoForUrl( GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_FALSE(info.has_value()); run_loop->Quit(); @@ -171,7 +171,7 @@ GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_TRUE(info.has_value()); @@ -205,7 +205,7 @@ shopping_service_->GetProductInfoForUrl( GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_FALSE(info.has_value()); run_loop->Quit(); @@ -296,7 +296,7 @@ shopping_service_->GetProductInfoForUrl( GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_TRUE(info.has_value()); @@ -357,7 +357,7 @@ shopping_service_->GetProductInfoForUrl( GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_TRUE(info.has_value()); @@ -435,7 +435,7 @@ shopping_service_->GetProductInfoForUrl( GURL(kProductUrl), base::BindOnce( [](base::RunLoop* run_loop, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { ASSERT_EQ(kProductUrl, url.spec()); ASSERT_TRUE(info.has_value());
diff --git a/components/commerce/core/webui/shopping_list_handler.cc b/components/commerce/core/webui/shopping_list_handler.cc index b7d191b..751c2e4 100644 --- a/components/commerce/core/webui/shopping_list_handler.cc +++ b/components/commerce/core/webui/shopping_list_handler.cc
@@ -30,7 +30,7 @@ shopping_list::mojom::ProductInfoPtr ProductInfoToMojoProduct( const GURL& url, - const absl::optional<ProductInfo>& info, + const absl::optional<const ProductInfo>& info, const std::string& locale) { auto product_info = shopping_list::mojom::ProductInfo::New(); @@ -448,7 +448,7 @@ void ShoppingListHandler::OnFetchProductInfoForCurrentUrl( GetProductInfoForCurrentUrlCallback callback, const GURL& url, - const absl::optional<ProductInfo>& info) { + const absl::optional<const ProductInfo>& info) { std::move(callback).Run(ProductInfoToMojoProduct(url, info, locale_)); }
diff --git a/components/commerce/core/webui/shopping_list_handler.h b/components/commerce/core/webui/shopping_list_handler.h index b612d61..61b3a8c 100644 --- a/components/commerce/core/webui/shopping_list_handler.h +++ b/components/commerce/core/webui/shopping_list_handler.h
@@ -125,7 +125,7 @@ void OnFetchProductInfoForCurrentUrl( GetProductInfoForCurrentUrlCallback callback, const GURL& url, - const absl::optional<ProductInfo>& info); + const absl::optional<const ProductInfo>& info); void OnFetchPriceInsightsInfoForCurrentUrl( GetPriceInsightsInfoForCurrentUrlCallback callback,
diff --git a/components/content_settings/browser/ui/cookie_controls_controller.cc b/components/content_settings/browser/ui/cookie_controls_controller.cc index 67a14b8..9f06c35e 100644 --- a/components/content_settings/browser/ui/cookie_controls_controller.cc +++ b/components/content_settings/browser/ui/cookie_controls_controller.cc
@@ -43,10 +43,6 @@ namespace { -// The number of page reloads in the last 30 seconds that is considered to be a -// high confidence breakage signal. -constexpr int kFrequentReloadThreshold = 3; - constexpr char kEntryPointAnimatedKey[] = "entry_point_animated"; constexpr char kLastExpirationKey[] = "last_expiration"; constexpr char kLastVisitedActiveException[] = "last_visited_active_exception"; @@ -262,7 +258,7 @@ return CookieControlsBreakageConfidenceLevel::kMedium; } - if (recent_reloads_count_ >= kFrequentReloadThreshold) { + if (recent_reloads_count_ >= features::kUserBypassUIReloadCount.Get()) { return CookieControlsBreakageConfidenceLevel::kHigh; } @@ -494,7 +490,7 @@ recent_reloads_count_ = recent_reloads_count; // Only inform the observers if there is a potential confidence level change. - if (recent_reloads_count_ < kFrequentReloadThreshold && + if (recent_reloads_count_ < features::kUserBypassUIReloadCount.Get() && !has_exception_expired_since_last_visit_) { return; } @@ -641,7 +637,7 @@ timer_.Stop(); } else { if (!timer_.IsRunning()) { - timer_.Start(FROM_HERE, base::Seconds(30), this, + timer_.Start(FROM_HERE, features::kUserBypassUIReloadTime.Get(), this, &CookieControlsController::TabObserver::ResetReloadCounter); } reload_count_++;
diff --git a/components/content_settings/core/common/features.cc b/components/content_settings/core/common/features.cc index 5a2ff48..99357bb 100644 --- a/components/content_settings/core/common/features.cc +++ b/components/content_settings/core/common/features.cc
@@ -64,6 +64,12 @@ const base::FeatureParam<base::TimeDelta> kUserBypassUIExceptionExpiration{ &kUserBypassUI, "expiration", base::Days(90)}; +const base::FeatureParam<int> kUserBypassUIReloadCount{&kUserBypassUI, + "reload-count", 3}; + +const base::FeatureParam<base::TimeDelta> kUserBypassUIReloadTime{ + &kUserBypassUI, "reload-time", base::Seconds(30)}; + BASE_FEATURE(kImprovedSemanticsActivityIndicators, "ImprovedSemanticsActivityIndicators", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/components/content_settings/core/common/features.h b/components/content_settings/core/common/features.h index 46c8a851..17f4c3a3 100644 --- a/components/content_settings/core/common/features.h +++ b/components/content_settings/core/common/features.h
@@ -79,6 +79,16 @@ extern const base::FeatureParam<base::TimeDelta> kUserBypassUIExceptionExpiration; +// Determines how many refreshes within `kUserBypassUIReloadTime` are required +// before a high confidence signal is returned. +COMPONENT_EXPORT(CONTENT_SETTINGS_FEATURES) +extern const base::FeatureParam<int> kUserBypassUIReloadCount; + +// Determines how long a user has to make `kUserBypassUIReloadCount` refreshes +// before a high confidence signal is returned. +COMPONENT_EXPORT(CONTENT_SETTINGS_FEATURES) +extern const base::FeatureParam<base::TimeDelta> kUserBypassUIReloadTime; + // Hide activity indicators if a permission is no longer used. COMPONENT_EXPORT(CONTENT_SETTINGS_FEATURES) BASE_DECLARE_FEATURE(kImprovedSemanticsActivityIndicators);
diff --git a/components/omnibox/browser/calculator_provider.h b/components/omnibox/browser/calculator_provider.h index a1a3569c..8c4dbaf6 100644 --- a/components/omnibox/browser/calculator_provider.h +++ b/components/omnibox/browser/calculator_provider.h
@@ -9,7 +9,7 @@ #include <string> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "components/omnibox/browser/autocomplete_match.h" #include "components/omnibox/browser/autocomplete_provider.h" #include "components/omnibox/browser/autocomplete_provider_listener.h"
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/AllowBackForwardCacheForCacheControlNoStorePageEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/AllowBackForwardCacheForCacheControlNoStorePageEnabled.yaml index bb143f2..783b2a21 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/AllowBackForwardCacheForCacheControlNoStorePageEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/AllowBackForwardCacheForCacheControlNoStorePageEnabled.yaml
@@ -9,12 +9,11 @@ If the policy is enabled or unset, the page with <ph name="CACHE_CONTROL_NO_STORE_NAME">Cache-Control: no-store</ph> header might be restored from back/forward cache unless the cache eviction is triggered (e.g. when there is HTTP-only cookie change to the site). If the policy is disabled, the page with <ph name="CACHE_CONTROL_NO_STORE_NAME">Cache-Control: no-store</ph> header will not be stored in back/forward cache. -future_on: -- fuchsia supported_on: - chrome.*:116- - chrome_os:116- - android:116- +- fuchsia:117- deprecated: false device_only: false supported_chrome_os_management: ['google_cloud']
diff --git a/components/policy/test/data/policy_test_cases.json b/components/policy/test/data/policy_test_cases.json index 5d457832..df44c9d 100644 --- a/components/policy/test/data/policy_test_cases.json +++ b/components/policy/test/data/policy_test_cases.json
@@ -23761,7 +23761,8 @@ "mac", "chromeos_ash", "chromeos_lacros", - "android" + "android", + "fuchsia" ], "policy_pref_mapping_tests": [ {
diff --git a/components/query_tiles/internal/BUILD.gn b/components/query_tiles/internal/BUILD.gn index 79f8f50..1915f40b 100644 --- a/components/query_tiles/internal/BUILD.gn +++ b/components/query_tiles/internal/BUILD.gn
@@ -91,6 +91,7 @@ ":internal", "//base", "//base/test:test_support", + "//components/background_task_scheduler:public", "//components/image_fetcher/core:test_support", "//components/leveldb_proto", "//components/leveldb_proto:test_support",
diff --git a/components/query_tiles/internal/tile_service_scheduler.h b/components/query_tiles/internal/tile_service_scheduler.h index bdcdec9..28a9ca35 100644 --- a/components/query_tiles/internal/tile_service_scheduler.h +++ b/components/query_tiles/internal/tile_service_scheduler.h
@@ -5,7 +5,6 @@ #ifndef COMPONENTS_QUERY_TILES_INTERNAL_TILE_SERVICE_SCHEDULER_H_ #define COMPONENTS_QUERY_TILES_INTERNAL_TILE_SERVICE_SCHEDULER_H_ -#include "components/background_task_scheduler/background_task_scheduler.h" #include "components/query_tiles/internal/tile_types.h" namespace query_tiles {
diff --git a/components/query_tiles/internal/tile_service_scheduler_impl.cc b/components/query_tiles/internal/tile_service_scheduler_impl.cc index 25b85af..1fdb31b 100644 --- a/components/query_tiles/internal/tile_service_scheduler_impl.cc +++ b/components/query_tiles/internal/tile_service_scheduler_impl.cc
@@ -11,6 +11,7 @@ #include "base/rand_util.h" #include "base/time/default_tick_clock.h" #include "base/time/time.h" +#include "components/background_task_scheduler/background_task_scheduler.h" #include "components/prefs/pref_service.h" #include "components/query_tiles/internal/stats.h" #include "components/query_tiles/internal/tile_config.h"
diff --git a/components/query_tiles/internal/tile_service_scheduler_impl.h b/components/query_tiles/internal/tile_service_scheduler_impl.h index e2284f3..ffd86bd 100644 --- a/components/query_tiles/internal/tile_service_scheduler_impl.h +++ b/components/query_tiles/internal/tile_service_scheduler_impl.h
@@ -14,6 +14,10 @@ #include "components/query_tiles/tile_service_prefs.h" #include "net/base/backoff_entry_serializer.h" +namespace background_task { +class BackgroundTaskScheduler; +} // namespace background_task + class PrefService; namespace query_tiles {
diff --git a/components/query_tiles/internal/tile_service_scheduler_unittest.cc b/components/query_tiles/internal/tile_service_scheduler_unittest.cc index f3262ed..7e32a614 100644 --- a/components/query_tiles/internal/tile_service_scheduler_unittest.cc +++ b/components/query_tiles/internal/tile_service_scheduler_unittest.cc
@@ -16,6 +16,7 @@ #include "base/test/task_environment.h" #include "base/test/test_mock_time_task_runner.h" #include "base/time/time.h" +#include "components/background_task_scheduler/background_task_scheduler.h" #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_service.h" #include "components/query_tiles/internal/black_hole_log_sink.h"
diff --git a/components/query_tiles/test/fake_server_response.cc b/components/query_tiles/test/fake_server_response.cc index e442129..c24e678d 100644 --- a/components/query_tiles/test/fake_server_response.cc +++ b/components/query_tiles/test/fake_server_response.cc
@@ -5,7 +5,6 @@ #include "components/query_tiles/test/fake_server_response.h" #include "base/strings/string_number_conversions.h" -#include "components/query_tiles/internal/tile_fetcher.h" #include "components/query_tiles/proto/tile_response.pb.h" namespace query_tiles { @@ -66,11 +65,6 @@ } // namespace // static -void FakeServerResponse::SetTileFetcherServerURL(const GURL& url) { - TileFetcher::SetOverrideURLForTesting(url); -} - -// static std::string FakeServerResponse::CreateServerResponseProto(int levels, int tiles_per_level) { proto::ServerResponse server_response;
diff --git a/components/query_tiles/test/fake_server_response.h b/components/query_tiles/test/fake_server_response.h index 68a663c..635d19c 100644 --- a/components/query_tiles/test/fake_server_response.h +++ b/components/query_tiles/test/fake_server_response.h
@@ -16,8 +16,6 @@ // query tiles server interaction for using in tests. class FakeServerResponse { public: - // Sets the query tile server endpoint to the given |url|. - static void SetTileFetcherServerURL(const GURL& url); // Creates a fake server response proto, which has |levels| tiers, and each // tier has |tiles_per_level| tiles.
diff --git a/components/reporting/util/task_runner_context_unittest.cc b/components/reporting/util/task_runner_context_unittest.cc index c6f68f5..ef910b75 100644 --- a/components/reporting/util/task_runner_context_unittest.cc +++ b/components/reporting/util/task_runner_context_unittest.cc
@@ -8,10 +8,10 @@ #include <memory> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/check.h" #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/synchronization/waitable_event.h"
diff --git a/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher.h b/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher.h index 04f382e..bea7209 100644 --- a/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher.h +++ b/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher.h
@@ -7,9 +7,9 @@ #include <map> #include <queue> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece_forward.h" #include "base/supports_user_data.h"
diff --git a/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher_unittest.cc b/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher_unittest.cc index 90daf7b..1719a65 100644 --- a/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher_unittest.cc +++ b/components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher_unittest.cc
@@ -5,8 +5,8 @@ #include "components/segmentation_platform/embedder/input_delegate/tab_rank_dispatcher.h" #include <memory> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" +#include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/test/gmock_callback_support.h" #include "base/time/time.h"
diff --git a/components/services/app_service/public/cpp/intent_util.cc b/components/services/app_service/public/cpp/intent_util.cc index cea9bbcc..0a1dd4d6 100644 --- a/components/services/app_service/public/cpp/intent_util.cc +++ b/components/services/app_service/public/cpp/intent_util.cc
@@ -105,6 +105,7 @@ intent->mime_type = mime_type; intent->files = std::vector<apps::IntentFilePtr>{}; auto file = std::make_unique<apps::IntentFile>(filesystem_url); + file->mime_type = mime_type; intent->files.push_back(std::move(file)); } if (!drive_share_url.is_empty()) {
diff --git a/components/services/app_service/public/cpp/intent_util_unittest.cc b/components/services/app_service/public/cpp/intent_util_unittest.cc index e91b4982..2a576306 100644 --- a/components/services/app_service/public/cpp/intent_util_unittest.cc +++ b/components/services/app_service/public/cpp/intent_util_unittest.cc
@@ -788,6 +788,25 @@ EXPECT_TRUE(intent->MatchFilter(filter)); } +/* + * Tests that the MakeShareIntent function overload for making intent for a + * single files creates an intent with consistent mime types. + */ +TEST_F(IntentUtilTest, ShareSingleIntent) { + const std::string mime_type = "image/jpeg"; + const GURL file_url = GURL("https://www.google.com/"); + const GURL drive_share_url = GURL("https://drive.google.com/"); + + auto intent = apps_util::MakeShareIntent(file_url, mime_type, drive_share_url, + /* is_directory: */ false); + + ASSERT_EQ(1u, intent->files.size()); + ASSERT_TRUE(intent->mime_type); + EXPECT_EQ(mime_type, intent->mime_type.value()); + ASSERT_TRUE(intent->files[0]->mime_type); + EXPECT_EQ(mime_type, intent->files[0]->mime_type.value()); +} + TEST_F(IntentUtilTest, TextMatch) { std::string mime_type1 = "text/plain"; std::string mime_type2 = "image/jpeg";
diff --git a/components/services/app_service/public/cpp/shortcut/shortcut_update.h b/components/services/app_service/public/cpp/shortcut/shortcut_update.h index f1ff590..5c4f0e1 100644 --- a/components/services/app_service/public/cpp/shortcut/shortcut_update.h +++ b/components/services/app_service/public/cpp/shortcut/shortcut_update.h
@@ -8,8 +8,8 @@ #include <memory> #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/component_export.h" +#include "base/memory/raw_ptr.h" #include "components/services/app_service/public/cpp/macros.h" #include "components/services/app_service/public/cpp/shortcut/shortcut.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/components/services/storage/service_worker/service_worker_database.cc b/components/services/storage/service_worker/service_worker_database.cc index fc61b1d..e3305213 100644 --- a/components/services/storage/service_worker/service_worker_database.cc +++ b/components/services/storage/service_worker/service_worker_database.cc
@@ -2406,6 +2406,15 @@ blink::ServiceWorkerRouterSource::SourceType::kFetchEvent; source.fetch_event_source.emplace(); break; + case ServiceWorkerRegistrationData::RouterRules::RuleV1::Source:: + kCacheSource: + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + blink::ServiceWorkerRouterCacheSource cache_source; + if (s.cache_source().has_cache_name()) { + cache_source.cache_name = s.cache_source().cache_name(); + } + source.cache_source = cache_source; + break; } router_rule.sources.emplace_back(source); } @@ -2852,6 +2861,12 @@ case blink::ServiceWorkerRouterSource::SourceType::kFetchEvent: source->mutable_fetch_event_source(); break; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + auto* cache_source = source->mutable_cache_source(); + if (s.cache_source->cache_name) { + cache_source->set_cache_name(*s.cache_source->cache_name); + } + break; } } }
diff --git a/components/services/storage/service_worker/service_worker_database.proto b/components/services/storage/service_worker/service_worker_database.proto index ba9fd38dd..85f4d49 100644 --- a/components/services/storage/service_worker/service_worker_database.proto +++ b/components/services/storage/service_worker/service_worker_database.proto
@@ -189,10 +189,14 @@ message NetworkSource {} message RaceSource {} message FetchEventSource {} + message CacheSource { + optional string cache_name = 1; + } oneof source { NetworkSource network_source = 1; RaceSource race_source = 2; FetchEventSource fetch_event_source = 3; + CacheSource cache_source = 4; } } repeated Condition condition = 1;
diff --git a/components/services/storage/service_worker/service_worker_database_unittest.cc b/components/services/storage/service_worker/service_worker_database_unittest.cc index b198e263..4ae2b8db 100644 --- a/components/services/storage/service_worker/service_worker_database_unittest.cc +++ b/components/services/storage/service_worker/service_worker_database_unittest.cc
@@ -3786,18 +3786,38 @@ condition.url_pattern = std::move(url_pattern); rule.conditions.emplace_back(condition); - blink::ServiceWorkerRouterSource source; - source.type = blink::ServiceWorkerRouterSource::SourceType::kNetwork; - source.network_source.emplace(); - rule.sources.push_back(source); - blink::ServiceWorkerRouterSource source2; - source2.type = blink::ServiceWorkerRouterSource::SourceType::kRace; - source2.race_source.emplace(); - rule.sources.push_back(source2); - blink::ServiceWorkerRouterSource source3; - source3.type = blink::ServiceWorkerRouterSource::SourceType::kFetchEvent; - source3.fetch_event_source.emplace(); - rule.sources.push_back(source3); + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kNetwork; + source.network_source.emplace(); + rule.sources.push_back(source); + } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kRace; + source.race_source.emplace(); + rule.sources.push_back(source); + } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kFetchEvent; + source.fetch_event_source.emplace(); + rule.sources.push_back(source); + } + { // cache source without cache_name. + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + source.cache_source.emplace(); + rule.sources.push_back(source); + } + { // cache source with cache_name. + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + blink::ServiceWorkerRouterCacheSource cache_source; + cache_source.cache_name = "example_cache_name"; + source.cache_source = cache_source; + rule.sources.push_back(source); + } router_rules.rules.emplace_back(rule); store_and_restore(router_rules);
diff --git a/components/signin/public/base/signin_switches.cc b/components/signin/public/base/signin_switches.cc index 9ec3cb9..fbd70ae 100644 --- a/components/signin/public/base/signin_switches.cc +++ b/components/signin/public/base/signin_switches.cc
@@ -52,10 +52,6 @@ base::FEATURE_DISABLED_BY_DEFAULT); #endif -#if BUILDFLAG(IS_IOS) -BASE_FEATURE(kFinchIosFre, "FinchIosFre", base::FEATURE_DISABLED_BY_DEFAULT); -#endif - // Enables a new version of the sync confirmation UI. BASE_FEATURE(kTangibleSync, "TangibleSync",
diff --git a/components/signin/public/base/signin_switches.h b/components/signin/public/base/signin_switches.h index b1a8049..e0820479 100644 --- a/components/signin/public/base/signin_switches.h +++ b/components/signin/public/base/signin_switches.h
@@ -40,11 +40,6 @@ BASE_DECLARE_FEATURE(kForceStartupSigninPromo); #endif -#if BUILDFLAG(IS_IOS) -// Experiment to test whether it's possible to finch FRE screen on iOS. -BASE_DECLARE_FEATURE(kFinchIosFre); -#endif - BASE_DECLARE_FEATURE(kTangibleSync); BASE_DECLARE_FEATURE(kSearchEngineChoice);
diff --git a/components/supervised_user/core/browser/BUILD.gn b/components/supervised_user/core/browser/BUILD.gn index 70564ca..7666b29 100644 --- a/components/supervised_user/core/browser/BUILD.gn +++ b/components/supervised_user/core/browser/BUILD.gn
@@ -100,10 +100,10 @@ "supervised_user_service.cc", "supervised_user_service.h", "supervised_user_service_observer.h", + "supervised_user_settings_model_type_controller.cc", + "supervised_user_settings_model_type_controller.h", "supervised_user_settings_service.cc", "supervised_user_settings_service.h", - "supervised_user_sync_model_type_controller.cc", - "supervised_user_sync_model_type_controller.h", "supervised_user_url_filter.cc", "supervised_user_url_filter.h", "web_content_handler.cc", @@ -165,8 +165,8 @@ "supervised_user_pref_store_unittest.cc", "supervised_user_preferences_unittest.cc", "supervised_user_service_unittest.cc", + "supervised_user_settings_model_type_controller_unittest.cc", "supervised_user_settings_service_unittest.cc", - "supervised_user_sync_model_type_controller_unittest.cc", "supervised_user_url_filter_unittest.cc", ]
diff --git a/components/supervised_user/core/browser/supervised_user_interstitial.h b/components/supervised_user/core/browser/supervised_user_interstitial.h index 7054650..9839831e 100644 --- a/components/supervised_user/core/browser/supervised_user_interstitial.h +++ b/components/supervised_user/core/browser/supervised_user_interstitial.h
@@ -8,8 +8,8 @@ #include <memory> #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ref.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ref.h" #include "components/supervised_user/core/browser/supervised_user_error_page.h" #include "url/gurl.h"
diff --git a/components/supervised_user/core/browser/supervised_user_service.cc b/components/supervised_user/core/browser/supervised_user_service.cc index 4d6d1cb..75a2ff6 100644 --- a/components/supervised_user/core/browser/supervised_user_service.cc +++ b/components/supervised_user/core/browser/supervised_user_service.cc
@@ -232,7 +232,8 @@ settings_service_->SetActive(active_); // Trigger a sync reconfig to enable/disable the right SU data types. - // The logic to do this lives in the SupervisedUserSyncModelTypeController. + // The logic to do this lives in the + // SupervisedUserSettingsModelTypeController. // TODO(crbug.com/946473): Get rid of this hack and instead call // DataTypePreconditionChanged from the controller. if (sync_service_->GetUserSettings()->IsInitialSyncFeatureSetupComplete()) {
diff --git a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller.cc b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller.cc similarity index 68% rename from components/supervised_user/core/browser/supervised_user_sync_model_type_controller.cc rename to components/supervised_user/core/browser/supervised_user_settings_model_type_controller.cc index 3273ba1..99c14f0 100644 --- a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller.cc +++ b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h" +#include "components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h" #include "base/functional/bind.h" #include "components/prefs/pref_service.h" @@ -10,28 +10,27 @@ #include "components/supervised_user/core/common/supervised_user_constants.h" #include "components/sync/model/model_type_store_service.h" -SupervisedUserSyncModelTypeController::SupervisedUserSyncModelTypeController( - syncer::ModelType type, - const base::RepeatingClosure& dump_stack, - syncer::OnceModelTypeStoreFactory store_factory, - base::WeakPtr<syncer::SyncableService> syncable_service, - PrefService* pref_service) +SupervisedUserSettingsModelTypeController:: + SupervisedUserSettingsModelTypeController( + const base::RepeatingClosure& dump_stack, + syncer::OnceModelTypeStoreFactory store_factory, + base::WeakPtr<syncer::SyncableService> syncable_service, + PrefService* pref_service) : SyncableServiceBasedModelTypeController( - type, + syncer::SUPERVISED_USER_SETTINGS, std::move(store_factory), syncable_service, dump_stack, DelegateMode::kTransportModeWithSingleModel), pref_service_(pref_service) { - DCHECK(type == syncer::SUPERVISED_USER_SETTINGS); DCHECK(pref_service); } -SupervisedUserSyncModelTypeController:: - ~SupervisedUserSyncModelTypeController() = default; +SupervisedUserSettingsModelTypeController:: + ~SupervisedUserSettingsModelTypeController() = default; syncer::DataTypeController::PreconditionState -SupervisedUserSyncModelTypeController::GetPreconditionState() const { +SupervisedUserSettingsModelTypeController::GetPreconditionState() const { DCHECK(CalledOnValidThread()); // TODO(b/292493941): use IsSubjectToParentalControls() once it is decoupled // from SupervisedUserService.
diff --git a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h similarity index 70% rename from components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h rename to components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h index adc3177..7980734 100644 --- a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h +++ b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SYNC_MODEL_TYPE_CONTROLLER_H_ -#define COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SYNC_MODEL_TYPE_CONTROLLER_H_ +#ifndef COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SETTINGS_MODEL_TYPE_CONTROLLER_H_ +#define COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SETTINGS_MODEL_TYPE_CONTROLLER_H_ #include "base/functional/callback_forward.h" #include "components/sync/service/syncable_service_based_model_type_controller.h" @@ -13,23 +13,22 @@ // A DataTypeController for supervised user sync datatypes, which enables or // disables these types based on the profile's IsSupervised state. Runs in // sync transport mode. -class SupervisedUserSyncModelTypeController +class SupervisedUserSettingsModelTypeController : public syncer::SyncableServiceBasedModelTypeController { public: // |sync_client| must not be null and must outlive this object. - SupervisedUserSyncModelTypeController( - syncer::ModelType type, + SupervisedUserSettingsModelTypeController( const base::RepeatingClosure& dump_stack, syncer::OnceModelTypeStoreFactory store_factory, base::WeakPtr<syncer::SyncableService> syncable_service, PrefService* pref_service); - SupervisedUserSyncModelTypeController( - const SupervisedUserSyncModelTypeController&) = delete; - SupervisedUserSyncModelTypeController& operator=( - const SupervisedUserSyncModelTypeController&) = delete; + SupervisedUserSettingsModelTypeController( + const SupervisedUserSettingsModelTypeController&) = delete; + SupervisedUserSettingsModelTypeController& operator=( + const SupervisedUserSettingsModelTypeController&) = delete; - ~SupervisedUserSyncModelTypeController() override; + ~SupervisedUserSettingsModelTypeController() override; // DataTypeController override. PreconditionState GetPreconditionState() const override; @@ -38,4 +37,4 @@ const raw_ptr<PrefService> pref_service_; }; -#endif // COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SYNC_MODEL_TYPE_CONTROLLER_H_ +#endif // COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_SETTINGS_MODEL_TYPE_CONTROLLER_H_
diff --git a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller_unittest.cc b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller_unittest.cc similarity index 76% rename from components/supervised_user/core/browser/supervised_user_sync_model_type_controller_unittest.cc rename to components/supervised_user/core/browser/supervised_user_settings_model_type_controller_unittest.cc index ff367c44..40ba70a8 100644 --- a/components/supervised_user/core/browser/supervised_user_sync_model_type_controller_unittest.cc +++ b/components/supervised_user/core/browser/supervised_user_settings_model_type_controller_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/supervised_user/core/browser/supervised_user_sync_model_type_controller.h" +#include "components/supervised_user/core/browser/supervised_user_settings_model_type_controller.h" #include "base/functional/callback_helpers.h" #include "base/test/mock_callback.h" @@ -10,7 +10,6 @@ #include "components/prefs/testing_pref_service.h" #include "components/supervised_user/core/common/pref_names.h" #include "components/supervised_user/core/common/supervised_user_constants.h" -#include "components/sync/base/model_type.h" #include "components/sync/base/sync_mode.h" #include "components/sync/service/data_type_controller.h" #include "testing/gmock/include/gmock/gmock.h" @@ -19,7 +18,7 @@ using syncer::DataTypeController; using ::testing::Return; -class SupervisedUserSyncModelTypeControllerTest : public testing::Test { +class SupervisedUserSettingsModelTypeControllerTest : public testing::Test { public: void SetUp() override { pref_service_.registry()->RegisterStringPref(prefs::kSupervisedUserId, @@ -30,12 +29,11 @@ TestingPrefServiceSimple pref_service_; }; -TEST_F(SupervisedUserSyncModelTypeControllerTest, +TEST_F(SupervisedUserSettingsModelTypeControllerTest, SupervisedUserMeetsPreconditions) { pref_service_.SetString(prefs::kSupervisedUserId, supervised_user::kChildAccountSUID); - SupervisedUserSyncModelTypeController controller( - syncer::SUPERVISED_USER_SETTINGS, + SupervisedUserSettingsModelTypeController controller( /*dump_stack=*/base::DoNothing(), /*store_factory=*/base::DoNothing(), /*syncable_service=*/nullptr, &pref_service_); @@ -43,10 +41,9 @@ controller.GetPreconditionState()); } -TEST_F(SupervisedUserSyncModelTypeControllerTest, +TEST_F(SupervisedUserSettingsModelTypeControllerTest, NonSupervisedUserDoesNotMeetPreconditions) { - SupervisedUserSyncModelTypeController controller( - syncer::SUPERVISED_USER_SETTINGS, + SupervisedUserSettingsModelTypeController controller( /*dump_stack=*/base::DoNothing(), /*store_factory=*/base::DoNothing(), /*syncable_service=*/nullptr, &pref_service_); @@ -54,9 +51,9 @@ controller.GetPreconditionState()); } -TEST_F(SupervisedUserSyncModelTypeControllerTest, HasTransportModeDelegate) { - SupervisedUserSyncModelTypeController controller( - syncer::SUPERVISED_USER_SETTINGS, +TEST_F(SupervisedUserSettingsModelTypeControllerTest, + HasTransportModeDelegate) { + SupervisedUserSettingsModelTypeController controller( /*dump_stack=*/base::DoNothing(), /*store_factory=*/base::DoNothing(), /*syncable_service=*/nullptr, &pref_service_);
diff --git a/components/sync/base/features.cc b/components/sync/base/features.cc index 740534e..954903c 100644 --- a/components/sync/base/features.cc +++ b/components/sync/base/features.cc
@@ -101,10 +101,6 @@ "SyncEnableLoadModelsTimeout", base::FEATURE_ENABLED_BY_DEFAULT); -BASE_FEATURE(kSyncEnforcePreferencesAllowlist, - "SyncEnforcePreferencesAllowlist", - base::FEATURE_ENABLED_BY_DEFAULT); - BASE_FEATURE(kEnablePreferencesAccountStorage, "EnablePreferencesAccountStorage", base::FEATURE_DISABLED_BY_DEFAULT); @@ -145,10 +141,6 @@ "ReplaceSyncPromosWithSignInPromos", base::FEATURE_DISABLED_BY_DEFAULT); -BASE_FEATURE(kSyncAvoidReconfigurationIfAlreadyStopping, - "SyncAvoidReconfigurationIfAlreadyStopping", - base::FEATURE_ENABLED_BY_DEFAULT); - BASE_FEATURE(kEnableBookmarksAccountStorage, "EnableBookmarksAccountStorage", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/components/sync/base/features.h b/components/sync/base/features.h index d875b70..f9e7c63 100644 --- a/components/sync/base/features.h +++ b/components/sync/base/features.h
@@ -125,10 +125,6 @@ "sync_load_models_timeout_duration", base::Seconds(30)}; -// Enable check to ensure only preferences in the allowlist are registered as -// syncable. -BASE_DECLARE_FEATURE(kSyncEnforcePreferencesAllowlist); - // Enables a separate account-scoped storage for preferences, for syncing users. // (Note that opposed to other "account storage" features, this one does not // have any effect for signed-in non-syncing users!) @@ -176,9 +172,6 @@ // Feature flag to replace all sync-related UI with sign-in ones. BASE_DECLARE_FEATURE(kReplaceSyncPromosWithSignInPromos); -// Flag to stop call to reconfiguration of datatypes if it's already stopping. -BASE_DECLARE_FEATURE(kSyncAvoidReconfigurationIfAlreadyStopping); - // If enabled, there will be two different BookmarkModel instances per profile: // one instance for "profile" bookmarks and another instance for "account" // bookmarks. See https://crbug.com/1404250 for details.
diff --git a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.cc b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.cc index 5f0e435..036f90f 100644 --- a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.cc +++ b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.cc
@@ -4,18 +4,14 @@ #include "components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h" -#include <algorithm> #include <array> #include <cstdint> -#include <iterator> -#include <string> #include <utility> +#include <vector> -#include "base/base64.h" #include "base/check_op.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/boringssl/src/include/openssl/hpke.h" namespace syncer { @@ -40,7 +36,7 @@ CrossUserSharingPublicPrivateKeyPair::CreateByImport( base::span<const uint8_t> private_key) { if (private_key.size() != X25519_PRIVATE_KEY_LEN) { - return {}; + return absl::nullopt; } return CrossUserSharingPublicPrivateKeyPair(std::move(private_key)); } @@ -48,29 +44,123 @@ CrossUserSharingPublicPrivateKeyPair::CrossUserSharingPublicPrivateKeyPair( base::span<const uint8_t> private_key) { CHECK_EQ(static_cast<size_t>(X25519_PRIVATE_KEY_LEN), private_key.size()); - - std::copy(private_key.begin(), private_key.end(), private_key_); - X25519_public_from_private(public_key_, private_key_); + CHECK(EVP_HPKE_KEY_init(key_.get(), EVP_hpke_x25519_hkdf_sha256(), + private_key.data(), X25519_PRIVATE_KEY_LEN)); } CrossUserSharingPublicPrivateKeyPair::CrossUserSharingPublicPrivateKeyPair() { - X25519_keypair(public_key_, private_key_); + CHECK(EVP_HPKE_KEY_generate(key_.get(), EVP_hpke_x25519_hkdf_sha256())); } std::array<uint8_t, X25519_PRIVATE_KEY_LEN> CrossUserSharingPublicPrivateKeyPair::GetRawPrivateKey() const { std::array<uint8_t, X25519_PRIVATE_KEY_LEN> raw_private_key; - std::copy(private_key_, private_key_ + X25519_PRIVATE_KEY_LEN, - raw_private_key.begin()); + size_t out_len; + CHECK(EVP_HPKE_KEY_private_key(key_.get(), raw_private_key.begin(), &out_len, + raw_private_key.size())); + CHECK_EQ(out_len, static_cast<size_t>(X25519_PRIVATE_KEY_LEN)); return raw_private_key; } std::array<uint8_t, X25519_PUBLIC_VALUE_LEN> CrossUserSharingPublicPrivateKeyPair::GetRawPublicKey() const { std::array<uint8_t, X25519_PUBLIC_VALUE_LEN> raw_public_key; - std::copy(public_key_, public_key_ + X25519_PUBLIC_VALUE_LEN, - raw_public_key.begin()); + size_t out_len; + CHECK(EVP_HPKE_KEY_public_key(key_.get(), raw_public_key.begin(), &out_len, + raw_public_key.size())); + CHECK_EQ(out_len, static_cast<size_t>(X25519_PUBLIC_VALUE_LEN)); return raw_public_key; } +absl::optional<std::vector<uint8_t>> +CrossUserSharingPublicPrivateKeyPair::HpkeAuthEncrypt( + base::span<const uint8_t> plaintext, + base::span<const uint8_t> recipient_public_key, + base::span<const uint8_t> authenticated_info) const { + bssl::ScopedEVP_HPKE_CTX sender_context; + + // This vector will hold the encapsulated shared secret "enc" followed by the + // symmetrically encrypted ciphertext "ct". + std::vector<uint8_t> encrypted_data(EVP_HPKE_MAX_ENC_LENGTH); + size_t encapsulated_shared_secret_len; + + if (!EVP_HPKE_CTX_setup_auth_sender( + /*ctx=*/sender_context.get(), + /*out_enc=*/encrypted_data.data(), + /*out_enc_len=*/&encapsulated_shared_secret_len, + /*max_enc=*/encrypted_data.size(), key_.get(), + /*kdf=*/EVP_hpke_hkdf_sha256(), + /*aead=*/EVP_hpke_chacha20_poly1305(), + /*peer_public_key=*/recipient_public_key.data(), + /*peer_public_key_len=*/recipient_public_key.size(), + /*info=*/authenticated_info.data(), + /*info_len=*/authenticated_info.size())) { + return absl::nullopt; + } + encrypted_data.resize(encapsulated_shared_secret_len + plaintext.size() + + EVP_HPKE_CTX_max_overhead(sender_context.get())); + + base::span<uint8_t> ciphertext = + base::make_span(encrypted_data).subspan(encapsulated_shared_secret_len); + size_t ciphertext_len; + + if (!EVP_HPKE_CTX_seal( + /*ctx=*/sender_context.get(), /*out=*/ciphertext.data(), + /*out_len=*/&ciphertext_len, + /*max_out_len=*/ciphertext.size(), /*in=*/plaintext.data(), + /*in_len*/ plaintext.size(), + /*ad=*/nullptr, + /*ad_len=*/0)) { + return absl::nullopt; + } + encrypted_data.resize(encapsulated_shared_secret_len + ciphertext_len); + + return encrypted_data; +} + +absl::optional<std::vector<uint8_t>> +CrossUserSharingPublicPrivateKeyPair::HpkeAuthDecrypt( + base::span<const uint8_t> encrypted_data, + base::span<const uint8_t> sender_public_key, + base::span<const uint8_t> authenticated_info) const { + bssl::ScopedEVP_HPKE_CTX sender_context; + + if (encrypted_data.size() < X25519_PUBLIC_VALUE_LEN) { + return absl::nullopt; + } + + base::span<const uint8_t> enc = + encrypted_data.subspan(0, X25519_PUBLIC_VALUE_LEN); + + bssl::ScopedEVP_HPKE_CTX recipient_context; + if (!EVP_HPKE_CTX_setup_auth_recipient( + /*ctx=*/recipient_context.get(), /*key=*/key_.get(), + /*kdf=*/EVP_hpke_hkdf_sha256(), + /*aead=*/EVP_hpke_chacha20_poly1305(), + /*enc=*/enc.data(), /*enc_len=*/enc.size(), + /*info=*/authenticated_info.data(), + /*info_len=*/authenticated_info.size(), + /*peer_public_key=*/sender_public_key.data(), + /*peer_public_key_len=*/sender_public_key.size())) { + return absl::nullopt; + } + + base::span<const uint8_t> ciphertext = + encrypted_data.subspan(X25519_PUBLIC_VALUE_LEN); + std::vector<uint8_t> plaintext(ciphertext.size()); + size_t plaintext_len; + + if (!EVP_HPKE_CTX_open( + /*ctx=*/recipient_context.get(), /*out=*/plaintext.data(), + /*out_len*/ &plaintext_len, /*max_out_len=*/plaintext.size(), + /*in=*/ciphertext.data(), /*in_len=*/ciphertext.size(), + /*ad=*/nullptr, + /*ad_len=*/0)) { + return absl::nullopt; + } + + plaintext.resize(plaintext_len); + return plaintext; +} + } // namespace syncer
diff --git a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h index 24f6e9a5..318ae8d 100644 --- a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h +++ b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h
@@ -8,10 +8,12 @@ #include <array> #include <memory> #include <string> +#include <vector> #include "base/containers/span.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/boringssl/src/include/openssl/curve25519.h" +#include "third_party/boringssl/src/include/openssl/hpke.h" namespace syncer { @@ -40,13 +42,31 @@ // Returns the raw public key. std::array<uint8_t, X25519_PUBLIC_VALUE_LEN> GetRawPublicKey() const; + // Encrypts the `plaintext` with Auth HPKE using |sender_public_key| + // authenticated with own private/public key-pair. + // Returns decrypted bytes as a vector if the decryption succeeds. + // |authenticated_info| is optional. + absl::optional<std::vector<uint8_t>> HpkeAuthDecrypt( + base::span<const uint8_t> encrypted_data, + base::span<const uint8_t> sender_public_key, + base::span<const uint8_t> authenticated_info) const; + + // Decrypt |encrypted_data| with Auth HPKE using own public/private key-pair + // and authenticated with |sender_public_key|. + // Returns encrypted bytes as a vector if the encryption succeeds. + // |authenticated_info| is optional and should match the one used during + // encryption. + absl::optional<std::vector<uint8_t>> HpkeAuthEncrypt( + base::span<const uint8_t> plaintext, + base::span<const uint8_t> recipient_public_key, + base::span<const uint8_t> authenticated_info) const; + private: CrossUserSharingPublicPrivateKeyPair(); explicit CrossUserSharingPublicPrivateKeyPair( base::span<const uint8_t> private_key); - uint8_t private_key_[X25519_PRIVATE_KEY_LEN]; - uint8_t public_key_[X25519_PUBLIC_VALUE_LEN]; + bssl::ScopedEVP_HPKE_KEY key_; }; } // namespace syncer
diff --git a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair_unittest.cc b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair_unittest.cc index 2cabc21..b58e742 100644 --- a/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair_unittest.cc +++ b/components/sync/engine/nigori/cross_user_sharing_public_private_key_pair_unittest.cc
@@ -95,5 +95,109 @@ EXPECT_FALSE(key.has_value()); } +TEST(CrossUserSharingPublicPrivateKeyPairTest, ShouldEncryptAndDecrypt) { + CrossUserSharingPublicPrivateKeyPair sender_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + CrossUserSharingPublicPrivateKeyPair recipient_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + + const std::string plaintext = "Sharing is caring"; + + absl::optional<std::vector<uint8_t>> encrypted_message = + sender_key_pair.HpkeAuthEncrypt( + base::as_bytes(base::make_span(plaintext)), + recipient_key_pair.GetRawPublicKey(), {}); + + EXPECT_TRUE(encrypted_message.has_value()); + + absl::optional<std::vector<uint8_t>> decrypted_message = + recipient_key_pair.HpkeAuthDecrypt(encrypted_message.value(), + sender_key_pair.GetRawPublicKey(), {}); + + EXPECT_TRUE(decrypted_message.has_value()); + EXPECT_THAT(decrypted_message.value(), testing::ElementsAreArray(plaintext)); +} + +// Ciphertext is too short to split into enc|ciphertext. +TEST(CrossUserSharingPublicPrivateKeyPairTest, + ShouldReturnEmptyOnDecryptingShortCipherText) { + CrossUserSharingPublicPrivateKeyPair sender_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + CrossUserSharingPublicPrivateKeyPair recipient_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + + std::vector<uint8_t> encrypted_message = {0, 1, 2, 3}; + + absl::optional<std::vector<uint8_t>> decrypted_message = + recipient_key_pair.HpkeAuthDecrypt(encrypted_message, + sender_key_pair.GetRawPublicKey(), {}); + + EXPECT_FALSE(decrypted_message.has_value()); +} + +// Encrypt for bad peer key (low-order X25519 points). +TEST(CrossUserSharingPublicPrivateKeyPairTest, + ShouldReturnEmptyOnEncryptingForBadPeerKey) { + CrossUserSharingPublicPrivateKeyPair sender_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + const std::vector<uint8_t> recipient_public_key(X25519_PUBLIC_VALUE_LEN, + 0x00); + + absl::optional<std::vector<uint8_t>> encrypted_message = + sender_key_pair.HpkeAuthEncrypt( + base::as_bytes(base::make_span("Sharing is caring")), + recipient_public_key, {}); + + EXPECT_FALSE(encrypted_message.has_value()); +} + +// Decrypt for bad peer key (low-order X25519 points). +TEST(CrossUserSharingPublicPrivateKeyPairTest, + ShouldReturnEmptyOnDecryptingForBadPeerKey) { + CrossUserSharingPublicPrivateKeyPair sender_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + CrossUserSharingPublicPrivateKeyPair recipient_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + + const std::vector<uint8_t> sender_public_key(X25519_PUBLIC_VALUE_LEN, 0xDE); + + absl::optional<std::vector<uint8_t>> encrypted_message = + sender_key_pair.HpkeAuthEncrypt( + base::as_bytes(base::make_span("Sharing is caring")), + recipient_key_pair.GetRawPublicKey(), {}); + + ASSERT_TRUE(encrypted_message.has_value()); + + absl::optional<std::vector<uint8_t>> decrypted_message = + recipient_key_pair.HpkeAuthDecrypt(encrypted_message.value(), + sender_public_key, {}); + + EXPECT_FALSE(decrypted_message.has_value()); +} + +// Decrypt corrupted ciphertext. +TEST(CrossUserSharingPublicPrivateKeyPairTest, + ShouldReturnEmptyOnDecryptingCorruptedCipherText) { + CrossUserSharingPublicPrivateKeyPair sender_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + CrossUserSharingPublicPrivateKeyPair recipient_key_pair = + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + + absl::optional<std::vector<uint8_t>> encrypted_message = + sender_key_pair.HpkeAuthEncrypt( + base::as_bytes(base::make_span("Sharing is caring")), + recipient_key_pair.GetRawPublicKey(), {}); + + ASSERT_TRUE(encrypted_message.has_value()); + + encrypted_message.value()[5] = encrypted_message.value()[5] ^ 0xDE; + + absl::optional<std::vector<uint8_t>> decrypted_message = + recipient_key_pair.HpkeAuthDecrypt(encrypted_message.value(), + sender_key_pair.GetRawPublicKey(), {}); + + EXPECT_FALSE(decrypted_message.has_value()); +} + } // namespace } // namespace syncer
diff --git a/components/sync/nigori/cross_user_sharing_keys.cc b/components/sync/nigori/cross_user_sharing_keys.cc index 46b49ee..8893c0c 100644 --- a/components/sync/nigori/cross_user_sharing_keys.cc +++ b/components/sync/nigori/cross_user_sharing_keys.cc
@@ -4,11 +4,11 @@ #include "components/sync/nigori/cross_user_sharing_keys.h" +#include <algorithm> #include <utility> #include <vector> #include "base/logging.h" -#include "base/notreached.h" #include "components/sync/protocol/nigori_local_data.pb.h" namespace syncer { @@ -43,8 +43,9 @@ // static CrossUserSharingKeys CrossUserSharingKeys::CreateFromProto( - const sync_pb::CrossUserSharingKeys& proto) { - CrossUserSharingKeys output; + const sync_pb::CrossUserSharingKeys& proto, + absl::optional<uint32_t> cross_user_sharing_key_pair_version) { + CrossUserSharingKeys output(cross_user_sharing_key_pair_version); for (const sync_pb::CrossUserSharingPrivateKey& key : proto.private_key()) { if (!output.AddKeyPairFromProto(key)) { DLOG(WARNING) << "Could not add PrivateKey protocol buffer message."; @@ -69,7 +70,7 @@ } CrossUserSharingKeys CrossUserSharingKeys::Clone() const { - CrossUserSharingKeys copy; + CrossUserSharingKeys copy(encryption_key_pair_version_); copy.AddAllUnknownKeysFrom(*this); return copy; } @@ -116,6 +117,17 @@ return key_pairs_map_.at(version); } -CrossUserSharingKeys::CrossUserSharingKeys() = default; +absl::optional<uint32_t> CrossUserSharingKeys::GetEncryptionKeyPairVersion() + const { + if (!encryption_key_pair_version_.has_value() || + !key_pairs_map_.contains(encryption_key_pair_version_.value())) { + return absl::nullopt; + } + return encryption_key_pair_version_; +} + +CrossUserSharingKeys::CrossUserSharingKeys( + absl::optional<uint32_t> encryption_key_pair_version) + : encryption_key_pair_version_(encryption_key_pair_version) {} } // namespace syncer
diff --git a/components/sync/nigori/cross_user_sharing_keys.h b/components/sync/nigori/cross_user_sharing_keys.h index ba9257c8..33ed8883 100644 --- a/components/sync/nigori/cross_user_sharing_keys.h +++ b/components/sync/nigori/cross_user_sharing_keys.h
@@ -21,7 +21,8 @@ static CrossUserSharingKeys CreateEmpty(); // Deserialization from proto. static CrossUserSharingKeys CreateFromProto( - const sync_pb::CrossUserSharingKeys& key_bag); + const sync_pb::CrossUserSharingKeys& key_bag, + absl::optional<uint32_t> cross_user_sharing_key_pair_version); CrossUserSharingKeys(CrossUserSharingKeys&& other); ~CrossUserSharingKeys(); @@ -53,9 +54,16 @@ const CrossUserSharingPublicPrivateKeyPair& GetKeyPair( uint32_t version) const; - private: - CrossUserSharingKeys(); + // Returns (if exists) the Public-private key-pair version for encryption + // purposes. + absl::optional<uint32_t> GetEncryptionKeyPairVersion() const; + private: + explicit CrossUserSharingKeys( + absl::optional<uint32_t> encryption_key_pair_version = absl::nullopt); + + // The version of the encryption key_pair to be used. + absl::optional<uint32_t> encryption_key_pair_version_; // Public-private key-pairs we know about, mapped by version. std::map<uint32_t, const CrossUserSharingPublicPrivateKeyPair> key_pairs_map_; };
diff --git a/components/sync/nigori/cross_user_sharing_keys_unittest.cc b/components/sync/nigori/cross_user_sharing_keys_unittest.cc index dfc22c93..9b059a0 100644 --- a/components/sync/nigori/cross_user_sharing_keys_unittest.cc +++ b/components/sync/nigori/cross_user_sharing_keys_unittest.cc
@@ -7,8 +7,6 @@ #include <vector> #include "components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h" -#include "components/sync/engine/nigori/key_derivation_params.h" -#include "components/sync/engine/nigori/nigori.h" #include "components/sync/protocol/nigori_specifics.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -32,9 +30,9 @@ } TEST(CrossUserSharingKeysTest, ShouldCreateEmptyFromProto) { - EXPECT_THAT( - CrossUserSharingKeys::CreateFromProto(sync_pb::CrossUserSharingKeys()), - SizeIs(0)); + EXPECT_THAT(CrossUserSharingKeys::CreateFromProto( + sync_pb::CrossUserSharingKeys(), absl::nullopt), + SizeIs(0)); } TEST(CrossUserSharingKeysTest, ShouldCreateNonEmptyFromProto) { @@ -47,7 +45,7 @@ ASSERT_THAT(original_keys, SizeIs(2)); const CrossUserSharingKeys restored_keys = - CrossUserSharingKeys::CreateFromProto(original_keys.ToProto()); + CrossUserSharingKeys::CreateFromProto(original_keys.ToProto(), 1); EXPECT_THAT(restored_keys, SizeIs(2)); EXPECT_TRUE(restored_keys.HasKeyPair(0)); EXPECT_TRUE(restored_keys.HasKeyPair(1)); @@ -66,7 +64,7 @@ "malformed-key"); CrossUserSharingKeys restored_keys = - CrossUserSharingKeys::CreateFromProto(malformed_proto); + CrossUserSharingKeys::CreateFromProto(malformed_proto, absl::nullopt); EXPECT_THAT(restored_keys, SizeIs(1)); EXPECT_TRUE(restored_keys.HasKeyPair(0)); @@ -120,11 +118,68 @@ CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 1); const CrossUserSharingKeys restored_keys = - CrossUserSharingKeys::CreateFromProto(original_keys.ToProto()); + CrossUserSharingKeys::CreateFromProto(original_keys.ToProto(), + absl::nullopt); EXPECT_TRUE(restored_keys.HasKeyPair(0)); EXPECT_TRUE(restored_keys.HasKeyPair(1)); } +TEST(CrossUserSharingKeysTest, + ShouldReturnEmptyEncryptionKeyPairVersionForEmptyKeys) { + CrossUserSharingKeys original_keys = CrossUserSharingKeys::CreateEmpty(); + + EXPECT_FALSE(original_keys.GetEncryptionKeyPairVersion().has_value()); +} + +TEST(CrossUserSharingKeysTest, ShouldReturnCurrentEncryptionKeyPairVersion) { + CrossUserSharingKeys original_keys = CrossUserSharingKeys::CreateEmpty(); + + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 0); + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 99); + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 1); + + const CrossUserSharingKeys restored_keys = + CrossUserSharingKeys::CreateFromProto(original_keys.ToProto(), 99); + + EXPECT_THAT(restored_keys.GetEncryptionKeyPairVersion().value(), Eq(99U)); +} + +TEST(CrossUserSharingKeysTest, + ShouldNotReturnEncryptionKeyPairVersionIfExistsAndNotSet) { + CrossUserSharingKeys original_keys = CrossUserSharingKeys::CreateEmpty(); + + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 0); + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 99); + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 1); + + const CrossUserSharingKeys restored_keys = + CrossUserSharingKeys::CreateFromProto(original_keys.ToProto(), + absl::nullopt); + + EXPECT_FALSE(restored_keys.GetEncryptionKeyPairVersion().has_value()); +} + +TEST(CrossUserSharingKeysTest, + ShouldNotReturnEncryptionKeyPairVersionIfSetAndDoesNotExist) { + CrossUserSharingKeys original_keys = CrossUserSharingKeys::CreateEmpty(); + + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 0); + original_keys.AddKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 1); + + const CrossUserSharingKeys restored_keys = + CrossUserSharingKeys::CreateFromProto(original_keys.ToProto(), 99U); + + EXPECT_FALSE(restored_keys.GetEncryptionKeyPairVersion().has_value()); +} + } // namespace } // namespace syncer
diff --git a/components/sync/nigori/cryptographer_impl.cc b/components/sync/nigori/cryptographer_impl.cc index f4b0800..c3bc89e 100644 --- a/components/sync/nigori/cryptographer_impl.cc +++ b/components/sync/nigori/cryptographer_impl.cc
@@ -5,6 +5,7 @@ #include "components/sync/nigori/cryptographer_impl.h" #include <utility> +#include <vector> #include "base/check.h" #include "base/memory/ptr_util.h" @@ -33,7 +34,8 @@ // static std::unique_ptr<CryptographerImpl> CryptographerImpl::FromProto( - const sync_pb::CryptographerData& proto) { + const sync_pb::CryptographerData& proto, + absl::optional<uint32_t> cross_user_sharing_key_pair_version) { NigoriKeyBag key_bag = NigoriKeyBag::CreateFromProto(proto.key_bag()); // TODO(crbug.com/1109221): An invalid local state should be handled in the // caller instead of CHECK-ing here, e.g. by resetting the local state. @@ -41,7 +43,8 @@ key_bag.HasKey(proto.default_key_name())); CrossUserSharingKeys cross_user_sharing_keys = - CrossUserSharingKeys::CreateFromProto(proto.cross_user_sharing_keys()); + CrossUserSharingKeys::CreateFromProto( + proto.cross_user_sharing_keys(), cross_user_sharing_key_pair_version); return base::WrapUnique( new CryptographerImpl(std::move(key_bag), proto.default_key_name(), @@ -174,4 +177,36 @@ return key_bag_.Decrypt(encrypted, decrypted); } +absl::optional<std::vector<uint8_t>> +CryptographerImpl::AuthEncryptForCrossUserSharing( + base::span<const uint8_t> plaintext, + base::span<const uint8_t> recipient_public_key) const { + absl::optional encryption_key_version = + cross_user_sharing_keys_.GetEncryptionKeyPairVersion(); + if (!encryption_key_version.has_value()) { + return absl::nullopt; + } + const CrossUserSharingPublicPrivateKeyPair& encryption_key_pair = + cross_user_sharing_keys_.GetKeyPair(encryption_key_version.value()); + + return encryption_key_pair.HpkeAuthEncrypt(plaintext, recipient_public_key, + {}); +} + +absl::optional<std::vector<uint8_t>> +CryptographerImpl::AuthDecryptForCrossUserSharing( + base::span<const uint8_t> encrypted_data, + base::span<const uint8_t> sender_public_key, + const uint32_t recipient_key_version) const { + if (!cross_user_sharing_keys_.HasKeyPair(recipient_key_version)) { + return absl::nullopt; + } + + const CrossUserSharingPublicPrivateKeyPair& decryption_key_pair = + cross_user_sharing_keys_.GetKeyPair(recipient_key_version); + + return decryption_key_pair.HpkeAuthDecrypt(encrypted_data, sender_public_key, + {}); +} + } // namespace syncer
diff --git a/components/sync/nigori/cryptographer_impl.h b/components/sync/nigori/cryptographer_impl.h index 28e832eb..43f92f7 100644 --- a/components/sync/nigori/cryptographer_impl.h +++ b/components/sync/nigori/cryptographer_impl.h
@@ -8,6 +8,7 @@ #include <cstdint> #include <memory> #include <string> +#include <vector> #include "components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h" #include "components/sync/engine/nigori/cryptographer.h" @@ -40,7 +41,9 @@ KeyDerivationParams::CreateForPbkdf2()); // Returns null in case of error (e.g. default key not present in keybag). static std::unique_ptr<CryptographerImpl> FromProto( - const sync_pb::CryptographerData& proto); + const sync_pb::CryptographerData& proto, + absl::optional<uint32_t> cross_user_sharing_key_pair_version = + absl::nullopt); CryptographerImpl& operator=(const CryptographerImpl&) = delete; @@ -104,6 +107,22 @@ size_t KeyBagSizeForTesting() const; + // Encrypts |plaintext| using Auth HPKE using |recipient_public_key| + // authentication is added with the current sender's authentication key. + // Empty optional is returned upon failure. + absl::optional<std::vector<uint8_t>> AuthEncryptForCrossUserSharing( + base::span<const uint8_t> plaintext, + base::span<const uint8_t> recipient_public_key) const; + + // Decrypts |encrypted_data| using Auth HPKE using the keys corresponding + // to |recipient_key_version| and authenticates that the sender actually used + // |sender_public_key| upon auth encryption. + // Empty optional is returned upon failure. + absl::optional<std::vector<uint8_t>> AuthDecryptForCrossUserSharing( + base::span<const uint8_t> encrypted_data, + base::span<const uint8_t> sender_public_key, + const uint32_t recipient_key_version) const; + // Cryptographer overrides. bool CanEncrypt() const override; bool CanDecrypt(const sync_pb::EncryptedData& encrypted) const override;
diff --git a/components/sync/nigori/cryptographer_impl_unittest.cc b/components/sync/nigori/cryptographer_impl_unittest.cc index 977ec0e..45cf834 100644 --- a/components/sync/nigori/cryptographer_impl_unittest.cc +++ b/components/sync/nigori/cryptographer_impl_unittest.cc
@@ -5,12 +5,13 @@ #include "components/sync/nigori/cryptographer_impl.h" #include <utility> +#include <vector> +#include "base/containers/span.h" #include "components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h" #include "components/sync/engine/nigori/key_derivation_params.h" #include "components/sync/engine/nigori/nigori.h" #include "components/sync/nigori/nigori_key_bag.h" -#include "components/sync/protocol/nigori_local_data.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -166,11 +167,12 @@ std::unique_ptr<CryptographerImpl> cryptographer = CryptographerImpl::CreateEmpty(); ASSERT_THAT(cryptographer, NotNull()); - CrossUserSharingPublicPrivateKeyPair key_pair = + absl::optional<CrossUserSharingPublicPrivateKeyPair> key_pair = CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); + ASSERT_TRUE(key_pair.has_value()); ASSERT_FALSE(cryptographer->HasKeyPair(0)); - cryptographer->EmplaceKeyPair(std::move(key_pair), 0); + cryptographer->EmplaceKeyPair(std::move(key_pair.value()), 0); EXPECT_TRUE(cryptographer->HasKeyPair(0)); } @@ -225,4 +227,40 @@ EXPECT_TRUE(cryptographer->HasKeyPair(1)); } +TEST(CryptographerImplTest, ShouldEncryptAndDecryptForCrossUserSharing) { + std::unique_ptr<CryptographerImpl> cryptographer_sender = + CryptographerImpl::FromProto( + sync_pb::CryptographerData::default_instance(), 0); + ASSERT_THAT(cryptographer_sender, NotNull()); + cryptographer_sender->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 0); + std::unique_ptr<CryptographerImpl> cryptographer_recipient = + CryptographerImpl::FromProto( + sync_pb::CryptographerData::default_instance(), 0); + + ASSERT_THAT(cryptographer_recipient, NotNull()); + cryptographer_recipient->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 0); + + const std::string plaintext = "Sharing is caring"; + + absl::optional<std::vector<uint8_t>> encrypted_message = + cryptographer_sender->AuthEncryptForCrossUserSharing( + base::as_bytes(base::make_span(plaintext)), + cryptographer_recipient->GetCrossUserSharingKeyPairForTesting(0) + .GetRawPublicKey()); + + EXPECT_TRUE(encrypted_message.has_value()); + + absl::optional<std::vector<uint8_t>> decrypted_message = + cryptographer_recipient->AuthDecryptForCrossUserSharing( + encrypted_message.value(), + cryptographer_sender->GetCrossUserSharingKeyPairForTesting(0) + .GetRawPublicKey(), + 0); + + EXPECT_TRUE(decrypted_message.has_value()); + EXPECT_THAT(decrypted_message.value(), testing::ElementsAreArray(plaintext)); +} + } // namespace syncer
diff --git a/components/sync/nigori/nigori_state.cc b/components/sync/nigori/nigori_state.cc index 74a4310..fec95d64 100644 --- a/components/sync/nigori/nigori_state.cc +++ b/components/sync/nigori/nigori_state.cc
@@ -4,6 +4,7 @@ #include "components/sync/nigori/nigori_state.h" +#include <cstdint> #include <vector> #include "base/base64.h" @@ -134,8 +135,12 @@ const sync_pb::NigoriModel& proto) { NigoriState state; - state.cryptographer = - CryptographerImpl::FromProto(proto.cryptographer_data()); + state.cryptographer = CryptographerImpl::FromProto( + proto.cryptographer_data(), + proto.has_cross_user_sharing_public_key() + ? absl::optional<uint32_t>( + proto.cross_user_sharing_public_key().version()) + : absl::nullopt); if (proto.has_pending_keys()) { state.pending_keys = proto.pending_keys();
diff --git a/components/sync/nigori/nigori_state_unittest.cc b/components/sync/nigori/nigori_state_unittest.cc index 8eebc86..90751596 100644 --- a/components/sync/nigori/nigori_state_unittest.cc +++ b/components/sync/nigori/nigori_state_unittest.cc
@@ -7,6 +7,7 @@ #include <vector> #include "components/sync/base/time.h" +#include "components/sync/engine/nigori/cross_user_sharing_public_private_key_pair.h" #include "components/sync/engine/nigori/key_derivation_params.h" #include "components/sync/engine/nigori/nigori.h" #include "components/sync/nigori/cryptographer_impl.h" @@ -149,6 +150,56 @@ state.cross_user_sharing_key_pair_version); } +TEST( + NigoriTestTest, + ShouldSetCrossUserPublicKeyVersionInCreateFromLocalProtoAndBeAbleToEncrypt) { + sync_pb::NigoriModel nigori_model; + std::unique_ptr<CryptographerImpl> cryptographer = + CryptographerImpl::CreateEmpty(); + cryptographer->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 5); + cryptographer->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 6); + ASSERT_TRUE(cryptographer->HasKeyPair(5)); + ASSERT_TRUE(cryptographer->HasKeyPair(6)); + *nigori_model.mutable_cryptographer_data() = cryptographer->ToProto(); + nigori_model.mutable_cross_user_sharing_public_key()->set_version(5); + + NigoriState state = NigoriState::CreateFromLocalProto(nigori_model); + + absl::optional<std::vector<uint8_t>> encrypted_message = + state.cryptographer->AuthEncryptForCrossUserSharing( + base::as_bytes(base::make_span("should encrypt this message")), + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair() + .GetRawPublicKey()); + + EXPECT_TRUE(encrypted_message.has_value()); +} + +TEST(NigoriTestTest, + ShouldReturnEmptyOnEncryptIfCrossUserPublicKeyVersionIsNotSet) { + sync_pb::NigoriModel nigori_model; + std::unique_ptr<CryptographerImpl> cryptographer = + CryptographerImpl::CreateEmpty(); + cryptographer->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 5); + cryptographer->EmplaceKeyPair( + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(), 6); + ASSERT_TRUE(cryptographer->HasKeyPair(5)); + ASSERT_TRUE(cryptographer->HasKeyPair(6)); + *nigori_model.mutable_cryptographer_data() = cryptographer->ToProto(); + + NigoriState state = NigoriState::CreateFromLocalProto(nigori_model); + + absl::optional<std::vector<uint8_t>> encrypted_message = + state.cryptographer->AuthEncryptForCrossUserSharing( + base::as_bytes(base::make_span("should encrypt this message")), + CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair() + .GetRawPublicKey()); + + EXPECT_FALSE(encrypted_message.has_value()); +} + } // namespace } // namespace syncer
diff --git a/components/sync/service/data_type_manager_impl.cc b/components/sync/service/data_type_manager_impl.cc index 9fbd0b1..3ab8045 100644 --- a/components/sync/service/data_type_manager_impl.cc +++ b/components/sync/service/data_type_manager_impl.cc
@@ -164,9 +164,7 @@ return; } - if (base::FeatureList::IsEnabled( - syncer::kSyncAvoidReconfigurationIfAlreadyStopping) && - state_ == STOPPING) { + if (state_ == STOPPING) { // Configuration should not be set while stopping. LOG(ERROR) << "Precondition changed while stopping."; return;
diff --git a/components/sync/test/fake_cryptographer.cc b/components/sync/test/fake_cryptographer.cc index d240357fe..e0f300169 100644 --- a/components/sync/test/fake_cryptographer.cc +++ b/components/sync/test/fake_cryptographer.cc
@@ -91,7 +91,7 @@ const CrossUserSharingPublicPrivateKeyPair& FakeCryptographer::GetCrossUserSharingKeyPairForTesting( uint32_t version) const { - return cross_user_sharing_key_pair; + return cross_user_sharing_key_pair_; } } // namespace syncer
diff --git a/components/sync/test/fake_cryptographer.h b/components/sync/test/fake_cryptographer.h index 8915e3e2..24dbe69 100644 --- a/components/sync/test/fake_cryptographer.h +++ b/components/sync/test/fake_cryptographer.h
@@ -52,7 +52,7 @@ std::set<std::string> known_key_names_; // The state with no default key is encoded with an empty string. std::string default_key_name_; - CrossUserSharingPublicPrivateKeyPair cross_user_sharing_key_pair = + CrossUserSharingPublicPrivateKeyPair cross_user_sharing_key_pair_ = CrossUserSharingPublicPrivateKeyPair::GenerateNewKeyPair(); };
diff --git a/components/sync_preferences/DIR_METADATA b/components/sync_preferences/DIR_METADATA index ce059d2..4a58e65 100644 --- a/components/sync_preferences/DIR_METADATA +++ b/components/sync_preferences/DIR_METADATA
@@ -1,5 +1 @@ -monorail { - component: "Internals>Preferences" -} - -team_email: "chromium-reviews@chromium.org" +mixins: "//components/sync/COMMON_METADATA"
diff --git a/components/sync_preferences/OWNERS b/components/sync_preferences/OWNERS index 1d0a843..4c65932 100644 --- a/components/sync_preferences/OWNERS +++ b/components/sync_preferences/OWNERS
@@ -1,2 +1,3 @@ +# Prefer sending reviews to chromium-sync-reviews@google.com file://components/prefs/OWNERS file://components/sync/OWNERS
diff --git a/components/sync_preferences/pref_model_associator.cc b/components/sync_preferences/pref_model_associator.cc index 32df559f..a22ab74 100644 --- a/components/sync_preferences/pref_model_associator.cc +++ b/components/sync_preferences/pref_model_associator.cc
@@ -395,7 +395,6 @@ void PrefModelAssociator::RegisterPref(const std::string& name) { DCHECK(!base::Contains(registered_preferences_, name)); DCHECK( - !base::FeatureList::IsEnabled(syncer::kSyncEnforcePreferencesAllowlist) || !client_ || (client_->GetSyncablePrefsDatabase().IsPreferenceSyncable(name) && client_->GetSyncablePrefsDatabase()
diff --git a/components/sync_preferences/pref_model_associator_unittest.cc b/components/sync_preferences/pref_model_associator_unittest.cc index 6746840..e34e0be 100644 --- a/components/sync_preferences/pref_model_associator_unittest.cc +++ b/components/sync_preferences/pref_model_associator_unittest.cc
@@ -554,16 +554,13 @@ class SyncablePrefsDatabaseTest : public testing::Test { protected: SyncablePrefsDatabaseTest() - : feature_list_(syncer::kSyncEnforcePreferencesAllowlist), - pref_registry_( + : pref_registry_( base::MakeRefCounted<user_prefs::PrefRegistrySyncable>()) { PrefServiceMockFactory factory; factory.SetPrefModelAssociatorClient(&client_); pref_service_ = factory.CreateSyncable(pref_registry_.get()); } - base::test::ScopedFeatureList feature_list_; - TestPrefModelAssociatorClient client_; scoped_refptr<user_prefs::PrefRegistrySyncable> pref_registry_; std::unique_ptr<PrefServiceSyncable> pref_service_;
diff --git a/components/test/data/autofill/heuristics/output/008_i18n_pt.out b/components/test/data/autofill/heuristics/output/008_i18n_pt.out index b4d7ed0..bae8a109 100644 --- a/components/test/data/autofill/heuristics/output/008_i18n_pt.out +++ b/components/test/data/autofill/heuristics/output/008_i18n_pt.out
@@ -2,7 +2,7 @@ NAME_LAST | ln | Sobrenome: | | fn_1 COMPANY_NAME | cm | Empresa: | | fn_1 ADDRESS_HOME_LINE1 | a1 | Endereço: | | fn_1 -UNKNOWN_TYPE | a2 | Complemento: | | fn_1 +ADDRESS_HOME_LINE2 | a2 | Complemento: | | fn_1 ADDRESS_HOME_CITY | ct | Cidade: | | fn_1 ADDRESS_HOME_ZIP | zc | CEP: | | fn_1 ADDRESS_HOME_STATE | st | Estado: | | fn_1
diff --git a/components/viz/service/display/output_surface.cc b/components/viz/service/display/output_surface.cc index 7c045a7..23ca02f 100644 --- a/components/viz/service/display/output_surface.cc +++ b/components/viz/service/display/output_surface.cc
@@ -25,7 +25,7 @@ OutputSurface::Capabilities& OutputSurface::Capabilities::operator=( const Capabilities& capabilities) = default; -OutputSurface::OutputSurface(Type type) : type_(type) {} +OutputSurface::OutputSurface() : type_(Type::kSkia) {} OutputSurface::OutputSurface( std::unique_ptr<SoftwareOutputDevice> software_device)
diff --git a/components/viz/service/display/output_surface.h b/components/viz/service/display/output_surface.h index f4f5c66d..b87f0d1 100644 --- a/components/viz/service/display/output_surface.h +++ b/components/viz/service/display/output_surface.h
@@ -50,8 +50,7 @@ public: enum Type { kSoftware = 0, - kOpenGL = 1, - kVulkan = 2, + kSkia = 1, }; enum class OrientationMode { @@ -150,7 +149,7 @@ }; // Constructor for skia-based compositing. - explicit OutputSurface(Type type); + OutputSurface(); // Constructor for software compositing. explicit OutputSurface(std::unique_ptr<SoftwareOutputDevice> software_device);
diff --git a/components/viz/service/display/skia_output_surface.cc b/components/viz/service/display/skia_output_surface.cc index 48c1d277..5c02fc1 100644 --- a/components/viz/service/display/skia_output_surface.cc +++ b/components/viz/service/display/skia_output_surface.cc
@@ -6,8 +6,7 @@ namespace viz { -SkiaOutputSurface::SkiaOutputSurface(OutputSurface::Type type) - : OutputSurface(type) {} +SkiaOutputSurface::SkiaOutputSurface() = default; SkiaOutputSurface::~SkiaOutputSurface() = default;
diff --git a/components/viz/service/display/skia_output_surface.h b/components/viz/service/display/skia_output_surface.h index 0ba0e77..43bf966 100644 --- a/components/viz/service/display/skia_output_surface.h +++ b/components/viz/service/display/skia_output_surface.h
@@ -53,7 +53,7 @@ public: using OverlayList = std::vector<OverlayCandidate>; - explicit SkiaOutputSurface(OutputSurface::Type type); + SkiaOutputSurface(); SkiaOutputSurface(const SkiaOutputSurface&) = delete; SkiaOutputSurface& operator=(const SkiaOutputSurface&) = delete; @@ -219,6 +219,10 @@ virtual void DestroySharedImage(const gpu::Mailbox& mailbox) = 0; virtual bool SupportsBGRA() const = 0; + + // TODO(crbug.com/1449764): Remove after Graphite bottom left origin image + // flip Y workaround is removed from SkiaRenderer. + virtual bool IsUsingGraphite() const = 0; }; } // namespace viz
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index 098e9f8..fbf2dff 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -863,9 +863,7 @@ can_skip_render_pass_overlay_( base::FeatureList::IsEnabled(features::kCanSkipRenderPassOverlay)), #endif - is_using_raw_draw_(features::IsUsingRawDraw()), - is_using_graphite_( - base::FeatureList::IsEnabled(features::kSkiaGraphite)) { + is_using_raw_draw_(features::IsUsingRawDraw()) { DCHECK(skia_output_surface_); lock_set_for_external_use_.emplace(resource_provider, skia_output_surface_); @@ -1634,7 +1632,7 @@ bool SkiaRenderer::NeedsFlipY(const DrawQuad* quad) const { // TODO(crbug.com/1449764): remove this workaround when bottom left origin // image is supported by graphite. - if (!is_using_graphite_) { + if (!skia_output_surface_->IsUsingGraphite()) { return false; } switch (quad->material) {
diff --git a/components/viz/service/display/skia_renderer.h b/components/viz/service/display/skia_renderer.h index 2759c4a7..afeb088b 100644 --- a/components/viz/service/display/skia_renderer.h +++ b/components/viz/service/display/skia_renderer.h
@@ -490,7 +490,6 @@ #endif // BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_OZONE) const bool is_using_raw_draw_; - const bool is_using_graphite_; gfx::ColorConversionSkFilterCache color_filter_cache_;
diff --git a/components/viz/service/display_embedder/output_presenter_gl.cc b/components/viz/service/display_embedder/output_presenter_gl.cc index c1409cd..9c9d959f 100644 --- a/components/viz/service/display_embedder/output_presenter_gl.cc +++ b/components/viz/service/display_embedder/output_presenter_gl.cc
@@ -293,7 +293,8 @@ if (acquire_fence && !acquire_fence->GetGpuFenceHandle().is_null()) { CHECK(access); - CHECK_EQ(gpu::GrContextType::kGL, dependency_->gr_context_type()); + CHECK_EQ(gpu::GrContextType::kGL, + dependency_->GetSharedContextState()->gr_context_type()); CHECK(features::IsDelegatedCompositingEnabled()); CHECK(access->representation()->usage() & gpu::SHARED_IMAGE_USAGE_RASTER_DELEGATED_COMPOSITING);
diff --git a/components/viz/service/display_embedder/skia_output_surface_dependency.h b/components/viz/service/display_embedder/skia_output_surface_dependency.h index e31734b0..2677eb71 100644 --- a/components/viz/service/display_embedder/skia_output_surface_dependency.h +++ b/components/viz/service/display_embedder/skia_output_surface_dependency.h
@@ -16,7 +16,6 @@ #include "components/viz/service/viz_service_export.h" #include "gpu/command_buffer/common/constants.h" #include "gpu/command_buffer/service/sequence_id.h" -#include "gpu/config/gpu_preferences.h" #include "gpu/ipc/common/surface_handle.h" #include "ui/gl/gl_surface_format.h" @@ -38,6 +37,7 @@ class SingleTaskSequence; class SyncPointManager; struct GpuFeatureInfo; +struct GpuPreferences; namespace raster { class GrShaderCache; @@ -109,14 +109,6 @@ // This returns true if CompositorGpuThread(aka DrDc thread) is enabled. virtual bool IsUsingCompositorGpuThread() = 0; - - gpu::GrContextType gr_context_type() const { - return GetGpuPreferences().gr_context_type; - } - - bool IsUsingVulkan() const { - return gr_context_type() == gpu::GrContextType::kVulkan; - } }; } // namespace viz
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 24b756f8..fbb2169 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -131,12 +131,6 @@ return *active_url; } -OutputSurface::Type GetOutputSurfaceType(SkiaOutputSurfaceDependency* deps) { - // TODO(penghuang): Support more types. - return deps->IsUsingVulkan() ? OutputSurface::Type::kVulkan - : OutputSurface::Type::kOpenGL; -} - } // namespace SkiaOutputSurfaceImpl::ScopedPaint::ScopedPaint( @@ -259,9 +253,7 @@ DisplayCompositorMemoryAndTaskController* display_controller, const RendererSettings& renderer_settings, const DebugRendererSettings* debug_settings) - : SkiaOutputSurface( - GetOutputSurfaceType(display_controller->skia_dependency())), - dependency_(display_controller->skia_dependency()), + : dependency_(display_controller->skia_dependency()), renderer_settings_(renderer_settings), debug_settings_(debug_settings), display_compositor_controller_(display_controller), @@ -478,7 +470,7 @@ // CopyDst usage. So don't treat it like a root surface which generally // won't have or support those usages. skgpu::graphite::TextureInfo texture_info = - gpu::GetGraphiteTextureInfo(dependency_->gr_context_type(), format_); + gpu::GetGraphiteTextureInfo(gr_context_type_, format_); CHECK(texture_info.isValid()); current_paint_.emplace(graphite_recorder_, image_info, texture_info); } else { @@ -557,11 +549,11 @@ // NOTE: We don't have promises for individual planes, but still need // texture info for fallback. Fallback textures are not considered YUV // planes since they are allocated separately and need write usage. - context->SetImage(nullptr, {gpu::GetGraphiteTextureInfo( - dependency_->gr_context_type(), format)}); + context->SetImage( + nullptr, {gpu::GetGraphiteTextureInfo(gr_context_type_, format)}); texture_infos[i] = - gpu::GetGraphiteTextureInfo(dependency_->gr_context_type(), format, + gpu::GetGraphiteTextureInfo(gr_context_type_, format, /*plane_index=*/0, /*is_yuv_plane=*/true); fulfills[i] = new FulfillForPlane(context); } @@ -616,9 +608,9 @@ ? gpu::ToClosestSkColorTypeExternalSampler(format) : ToClosestSkColorType(/*gpu_compositing=*/true, format); if (graphite_recorder_) { - skgpu::graphite::TextureInfo texture_info = gpu::GetGraphiteTextureInfo( - dependency_->gr_context_type(), format, /*plane_index=*/0, - /*is_yuv_plane=*/false, mipmap); + skgpu::graphite::TextureInfo texture_info = + gpu::GetGraphiteTextureInfo(gr_context_type_, format, /*plane_index=*/0, + /*is_yuv_plane=*/false, mipmap); SkColorInfo color_info(color_type, image_context->alpha_type(), image_context->color_space()); auto image = SkImages::PromiseTextureFrom( @@ -663,8 +655,8 @@ plane_index++) { CHECK_EQ(image_context->origin(), kTopLeft_GrSurfaceOrigin); fulfills[plane_index] = new FulfillForPlane(image_context, plane_index); - texture_infos.emplace_back(gpu::GetGraphiteTextureInfo( - dependency_->gr_context_type(), format, plane_index)); + texture_infos.emplace_back( + gpu::GetGraphiteTextureInfo(gr_context_type_, format, plane_index)); } skgpu::graphite::YUVABackendTextureInfo yuva_backend_info( @@ -825,7 +817,7 @@ SkImageInfo::Make(gfx::SizeToSkISize(surface_size), color_type, kPremul_SkAlphaType, color_space); skgpu::graphite::TextureInfo texture_info = gpu::GetGraphiteTextureInfo( - dependency_->gr_context_type(), format, /*plane_index=*/0, + gr_context_type_, format, /*plane_index=*/0, /*is_yuv_plane=*/false, mipmap, scanout_dcomp_surface); if (!texture_info.isValid()) { DLOG(ERROR) << "BeginPaintRenderPass: invalid Graphite TextureInfo"; @@ -1135,6 +1127,7 @@ capabilities_ = impl_on_gpu_->capabilities(); is_displayed_as_overlay_ = impl_on_gpu_->IsDisplayedAsOverlay(); + gr_context_type_ = dependency_->GetSharedContextState()->gr_context_type(); if (auto* gr_context = dependency_->GetSharedContextState()->gr_context()) { gr_context_thread_safe_ = gr_context->threadSafeProxy(); } @@ -1168,7 +1161,7 @@ DCHECK(backend_format.isValid()); #if BUILDFLAG(IS_APPLE) if (is_overlay) { - DCHECK_EQ(dependency_->gr_context_type(), gpu::GrContextType::kGL); + DCHECK_EQ(gr_context_type_, gpu::GrContextType::kGL); // For overlay, IOSurface will be used, and we may need using // GL_TEXTURE_RECTANGLE_ARB as texture target. backend_format = GrBackendFormats::MakeGL( @@ -1215,7 +1208,7 @@ auto backend_format = gr_context_thread_safe_->defaultBackendFormat( color_type, GrRenderable::kYes); #if BUILDFLAG(IS_MAC) - DCHECK_EQ(dependency_->gr_context_type(), gpu::GrContextType::kGL); + DCHECK_EQ(gr_context_type_, gpu::GrContextType::kGL); // For root rander pass, IOSurface will be used, and we may need using // GL_TEXTURE_RECTANGLE_ARB as texture target. backend_format = @@ -1232,7 +1225,7 @@ 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) || + gr_context_type_ == gpu::GrContextType::kGL) || !capabilities_.uses_default_gl_framebuffer); // Skia doesn't support set desired MSAA count for default gl framebuffer. if (capabilities_.uses_default_gl_framebuffer) { @@ -1439,7 +1432,7 @@ uint32_t gl_texture_target, const absl::optional<gpu::VulkanYCbCrInfo>& ycbcr_info) { #if BUILDFLAG(ENABLE_VULKAN) - if (dependency_->gr_context_type() == gpu::GrContextType::kVulkan) { + if (gr_context_type_ == gpu::GrContextType::kVulkan) { if (!ycbcr_info) { return GrBackendFormat::MakeVk(gpu::ToVkFormat(si_format, plane_index)); } @@ -1462,7 +1455,7 @@ #else { #endif // BUILDFLAG(ENABLE_VULKAN) - CHECK_EQ(dependency_->gr_context_type(), gpu::GrContextType::kGL); + CHECK_EQ(gr_context_type_, gpu::GrContextType::kGL); // Convert internal format from GLES2 to platform GL. bool use_angle_rgbx_format = impl_on_gpu_->GetFeatureInfo() ->feature_flags() @@ -1651,4 +1644,8 @@ .isValid(); } +bool SkiaOutputSurfaceImpl::IsUsingGraphite() const { + return !!graphite_recorder_; +} + } // namespace viz
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 43885d80..85d5c2ab 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -168,6 +168,7 @@ const gfx::ColorSpace& color_space) override; void DestroySharedImage(const gpu::Mailbox& mailbox) override; bool SupportsBGRA() const override; + bool IsUsingGraphite() const override; // ExternalUseClient implementation: gpu::SyncToken ReleaseImageContexts( @@ -408,6 +409,7 @@ // SkiaOutputSurfaceImpl. std::unique_ptr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu_; + gpu::GrContextType gr_context_type_ = gpu::GrContextType::kGL; sk_sp<GrContextThreadSafeProxy> gr_context_thread_safe_; raw_ptr<skgpu::graphite::Recorder> graphite_recorder_ = nullptr;
diff --git a/components/viz/test/fake_skia_output_surface.cc b/components/viz/test/fake_skia_output_surface.cc index 4c38c39..f64169d2 100644 --- a/components/viz/test/fake_skia_output_surface.cc +++ b/components/viz/test/fake_skia_output_surface.cc
@@ -42,8 +42,7 @@ FakeSkiaOutputSurface::FakeSkiaOutputSurface( scoped_refptr<ContextProvider> context_provider) - : SkiaOutputSurface(SkiaOutputSurface::Type::kOpenGL), - context_provider_(std::move(context_provider)) {} + : context_provider_(std::move(context_provider)) {} FakeSkiaOutputSurface::~FakeSkiaOutputSurface() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); @@ -422,4 +421,8 @@ return true; } +bool FakeSkiaOutputSurface::IsUsingGraphite() const { + return false; +} + } // namespace viz
diff --git a/components/viz/test/fake_skia_output_surface.h b/components/viz/test/fake_skia_output_surface.h index 3e6c4b1..963537d1 100644 --- a/components/viz/test/fake_skia_output_surface.h +++ b/components/viz/test/fake_skia_output_surface.h
@@ -116,6 +116,7 @@ const gfx::ColorSpace& color_space) override; void DestroySharedImage(const gpu::Mailbox& mailbox) override {} bool SupportsBGRA() const override; + bool IsUsingGraphite() const override; // ExternalUseClient implementation: gpu::SyncToken ReleaseImageContexts(
diff --git a/content/browser/media/session/media_session_browsertest.cc b/content/browser/media/session/media_session_browsertest.cc index c00f6bb1..72e223f 100644 --- a/content/browser/media/session/media_session_browsertest.cc +++ b/content/browser/media/session/media_session_browsertest.cc
@@ -23,6 +23,7 @@ #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/media_start_stop_observer.h" +#include "content/public/test/test_media_session_client.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "media/base/media_switches.h" @@ -33,6 +34,10 @@ #include "services/media_session/public/cpp/test/mock_media_session.h" #include "third_party/abseil-cpp/absl/types/optional.h" +namespace { +int hidden_metadata_placeholder_thumbnail_size = 42; +} // namespace + namespace content { namespace { @@ -138,20 +143,24 @@ return base::Contains(visited_urls_, url); } - MediaSession* SetupMediaImageTest() { + MediaSession* SetupMediaImageTest(bool expect_media_image = true) { EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL(kMediaSessionImageTestURL))); StartPlaybackAndWait(shell(), kMediaSessionImageTestPageVideoElement); MediaSession* media_session = MediaSession::Get(shell()->web_contents()); - std::vector<media_session::MediaImage> expected_images; - expected_images.push_back(CreateTestImageWithSize(1)); - expected_images.push_back(CreateTestImageWithSize(10)); + if (expect_media_image) { + std::vector<media_session::MediaImage> expected_images; - media_session::test::MockMediaSessionMojoObserver observer(*media_session); - observer.WaitForExpectedImagesOfType( - media_session::mojom::MediaSessionImageType::kArtwork, expected_images); + expected_images.push_back(CreateTestImageWithSize(1)); + expected_images.push_back(CreateTestImageWithSize(10)); + media_session::test::MockMediaSessionMojoObserver observer( + *media_session); + observer.WaitForExpectedImagesOfType( + media_session::mojom::MediaSessionImageType::kArtwork, + expected_images); + } return media_session; } @@ -188,6 +197,23 @@ feature_list_.InitAndEnableFeature(media::kInternalMediaSession); } + void SetUp() override { + SetupMediaSessionClient(); + + MediaSessionBrowserTestBase::SetUp(); + } + + protected: + void SetupMediaSessionClient() { + SkBitmap placeholder_bitmap; + placeholder_bitmap.allocN32Pixels( + hidden_metadata_placeholder_thumbnail_size, + hidden_metadata_placeholder_thumbnail_size); + client_.SetThumbnailPlaceholder(placeholder_bitmap); + } + + TestMediaSessionClient client_; + private: base::test::ScopedFeatureList feature_list_; }; @@ -342,10 +368,55 @@ MediaSession* media_session = SetupMediaImageTest(); ASSERT_NE(nullptr, media_session); - media_session::MediaImage image; - image.src = embedded_test_server()->GetURL("/media/session/test_image.jpg"); - image.type = u"image/jpeg"; - image.sizes.push_back(gfx::Size(1, 1)); + MediaImageGetterHelper helper(media_session, CreateTestImageWithSize(1), 0, + 10); + helper.Wait(); + + // The test image is a 1x1 test image. + EXPECT_EQ(1, helper.bitmap().width()); + EXPECT_EQ(1, helper.bitmap().height()); + EXPECT_EQ(kRGBA_8888_SkColorType, helper.bitmap().colorType()); + + EXPECT_TRUE(WasURLVisited(GetTestImageURL())); +} + +// We hide the media image from CrOS' media controls by replacing the image in +// the MediaSessionImpl with a placeholder image. These changes are gated to +// only affect ChromeOS, hence why the testing for this is also ChromeOS only. +#if BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, HideMediaMetadataImageInCrOS) { + client_.SetShouldHideMetadata(true); + + ASSERT_TRUE(embedded_test_server()->Start()); + + // We don't expect a media image because of the way the image will be replaced + // with its placeholder in MediaSessionImpl. + MediaSession* media_session = + SetupMediaImageTest(/*expect_media_image=*/false); + ASSERT_NE(nullptr, media_session); + + MediaImageGetterHelper helper(media_session, CreateTestImageWithSize(1), 0, + 10); + + helper.Wait(); + + EXPECT_EQ(hidden_metadata_placeholder_thumbnail_size, + helper.bitmap().width()); + EXPECT_EQ(hidden_metadata_placeholder_thumbnail_size, + helper.bitmap().height()); + + // As we are replacing the image, we should not visit the original's URL. + EXPECT_FALSE(WasURLVisited(GetTestImageURL())); +} +#else // !BUILDFLAG(IS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, + DontHideMediaMetadataImageInNonCrOS) { + client_.SetShouldHideMetadata(true); + + ASSERT_TRUE(embedded_test_server()->Start()); + + MediaSession* media_session = SetupMediaImageTest(); + ASSERT_NE(nullptr, media_session); MediaImageGetterHelper helper(media_session, CreateTestImageWithSize(1), 0, 10); @@ -358,6 +429,7 @@ EXPECT_TRUE(WasURLVisited(GetTestImageURL())); } +#endif IN_PROC_BROWSER_TEST_F(MediaSessionBrowserTest, GetMediaImageBitmap_ImageTooSmall) {
diff --git a/content/browser/media/session/media_session_impl.cc b/content/browser/media/session/media_session_impl.cc index d44c114..cf9f50b 100644 --- a/content/browser/media/session/media_session_impl.cc +++ b/content/browser/media/session/media_session_impl.cc
@@ -1275,6 +1275,15 @@ int minimum_size_px, int desired_size_px, GetMediaImageBitmapCallback callback) { +// We want to hide the media image from ChromeOS' media controls. +#if BUILDFLAG(IS_CHROMEOS) + if (session_info_ && session_info_->hide_metadata) { + std::move(callback).Run( + MediaSessionClient::Get()->GetThumbnailPlaceholder()); + return; + } +#endif + // We should make sure |image| is in |images_|. bool found = false; bool source_icon = false; @@ -1695,6 +1704,69 @@ std::vector<media_session::MediaImage> artwork; media_session::MediaMetadata metadata; + bool images_changed = false; + + // We may want to hide metadata only from ChromeOS' media controls here. For + // other platforms, metadata is hidden in the SystemMediaControlsNotifier. We + // can't hide the metadata for other platforms here because it would affect + // their respective global media controls, which we don't want to do. +#if BUILDFLAG(IS_CHROMEOS) + if (session_info_ && session_info_->hide_metadata) { + BuildPlaceholderMetadata(metadata); + + // If hiding the image metadata, we need to manually notify the observers + // that the image has changed. This is because we aren't directly changing + // the artwork, but instead it's being changed in the + // MediaSessionImpl::GetMediaImageBitmap method. + images_changed = true; + } else { + BuildMetadata(metadata, artwork); + } +#else + BuildMetadata(metadata, artwork); +#endif + + // If we have no artwork in |images_| or the arwork has changed then we should + // update it with the latest artwork from the routed service. + auto it = images_.find(MediaSessionImageType::kArtwork); + images_changed = + images_changed || it == images_.end() || it->second != artwork; + if (images_changed) { + images_.insert_or_assign(MediaSessionImageType::kArtwork, artwork); + } + bool metadata_changed = metadata_ != metadata; + if (metadata_changed) { + metadata_ = metadata; + } + + if (!images_changed && !metadata_changed) { + return; + } + for (auto& observer : observers_) { + if (metadata_changed) { + observer->MediaSessionMetadataChanged(this->metadata_); + } + + if (images_changed) { + observer->MediaSessionImagesChanged(this->images_); + } + } +} + +#if BUILDFLAG(IS_CHROMEOS) +void MediaSessionImpl::BuildPlaceholderMetadata( + media_session::MediaMetadata& metadata) { + MediaSessionClient* media_session_client = MediaSessionClient::Get(); + metadata.title = media_session_client->GetTitlePlaceholder(); + metadata.artist = media_session_client->GetArtistPlaceholder(); + metadata.album = media_session_client->GetAlbumPlaceholder(); + metadata.source_title = media_session_client->GetSourceTitlePlaceholder(); +} +#endif + +void MediaSessionImpl::BuildMetadata( + media_session::MediaMetadata& metadata, + std::vector<media_session::MediaImage>& artwork) { if (routed_service_ && routed_service_->metadata()) { metadata.title = routed_service_->metadata()->title; metadata.artist = routed_service_->metadata()->artist; @@ -1702,14 +1774,15 @@ artwork = routed_service_->metadata()->artwork; } - if (metadata.title.empty()) + if (metadata.title.empty()) { metadata.title = SanitizeMediaTitle(web_contents()->GetTitle()); + } ContentClient* content_client = content::GetContentClient(); const GURL& url = web_contents()->GetLastCommittedURL(); - // If |url| wraps a chrome extension ID or System Web App, we can display the - // extension or app name instead, which is more human-readable. + // If |url| wraps a chrome extension ID or System Web App, we can display + // the extension or app name instead, which is more human-readable. std::u16string source_title; WebContentsDelegate* delegate = web_contents()->GetDelegate(); if (delegate) { @@ -1731,27 +1804,6 @@ } metadata.source_title = source_title; - - // If we have no artwork in |images_| or the arwork has changed then we should - // update it with the latest artwork from the routed service. - auto it = images_.find(MediaSessionImageType::kArtwork); - bool images_changed = it == images_.end() || it->second != artwork; - if (images_changed) - images_.insert_or_assign(MediaSessionImageType::kArtwork, artwork); - - bool metadata_changed = metadata_ != metadata; - if (metadata_changed) - metadata_ = metadata; - - if (!images_changed && !metadata_changed) - return; - for (auto& observer : observers_) { - if (metadata_changed) - observer->MediaSessionMetadataChanged(this->metadata_); - - if (images_changed) - observer->MediaSessionImagesChanged(this->images_); - } } bool MediaSessionImpl::IsPictureInPictureAvailable() const {
diff --git a/content/browser/media/session/media_session_impl.h b/content/browser/media/session/media_session_impl.h index 327c1db..c770c09 100644 --- a/content/browser/media/session/media_session_impl.h +++ b/content/browser/media/session/media_session_impl.h
@@ -456,6 +456,13 @@ // changed. void RebuildAndNotifyMetadataChanged(); +#if BUILDFLAG(IS_CHROMEOS) + void BuildPlaceholderMetadata(media_session::MediaMetadata&); +#endif + + void BuildMetadata(media_session::MediaMetadata& metadata, + std::vector<media_session::MediaImage>& artwork); + bool IsPictureInPictureAvailable() const; // Returns the device ID for the audio output device being used by all of the
diff --git a/content/browser/media/session/media_session_impl_service_routing_unittest.cc b/content/browser/media/session/media_session_impl_service_routing_unittest.cc index 1927e85..c1d1993 100644 --- a/content/browser/media/session/media_session_impl_service_routing_unittest.cc +++ b/content/browser/media/session/media_session_impl_service_routing_unittest.cc
@@ -7,6 +7,7 @@ #include <map> #include <memory> +#include <string> #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" @@ -14,6 +15,7 @@ #include "base/time/time.h" #include "content/browser/media/session/media_session_player_observer.h" #include "content/browser/media/session/mock_media_session_service_impl.h" +#include "content/public/test/test_media_session_client.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "media/base/media_content_type.h" @@ -33,6 +35,14 @@ using media_session::mojom::MediaSessionAction; using media_session::mojom::MediaSessionImageType; +namespace { +std::u16string hidden_metadata_placeholder_title = u"placeholder_title"; +std::u16string hidden_metadata_placeholder_source_title = + u"placeholder_source_title"; +std::u16string hidden_metadata_placeholder_artist = u"placeholder_artist"; +std::u16string hidden_metadata_placeholder_album = u"placeholder_album"; +} // namespace + namespace content { namespace { @@ -145,6 +155,8 @@ empty_metadata_.source_title = u"example.com"; GetMediaSession()->SetShouldThrottleDurationUpdateForTest(false); + + SetupMediaSessionClient(); } void TearDown() override { @@ -154,6 +166,13 @@ } protected: + void SetupMediaSessionClient() { + client_.SetTitlePlaceholder(hidden_metadata_placeholder_title); + client_.SetSourceTitlePlaceholder(hidden_metadata_placeholder_source_title); + client_.SetArtistPlaceholder(hidden_metadata_placeholder_artist); + client_.SetAlbumPlaceholder(hidden_metadata_placeholder_album); + } + void CreateServiceForFrame(TestRenderFrameHost* frame) { services_[frame] = std::make_unique<NiceMock<MockMediaSessionServiceImpl>>(frame); @@ -239,6 +258,8 @@ std::unique_ptr<MockMediaSessionPlayerObserver>>; PlayerMap players_; + TestMediaSessionClient client_; + private: media_session::MediaMetadata empty_metadata_; @@ -743,6 +764,68 @@ } } +// We hide the media metadata from CrOS' media controls by replacing the +// metadata in the MediaSessionImpl with some placeholder metadata. These +// changes are gated to only affect ChromeOS, hence why the testing for this is +// also ChromeOS only. +#if BUILDFLAG(IS_CHROMEOS) +TEST_F(MediaSessionImplServiceRoutingTest, HideMediaMetadataInCrOS) { + client_.SetShouldHideMetadata(true); + + media_session::MediaMetadata expected_metadata; + expected_metadata.title = hidden_metadata_placeholder_title; + expected_metadata.artist = hidden_metadata_placeholder_artist; + expected_metadata.album = hidden_metadata_placeholder_album; + expected_metadata.source_title = hidden_metadata_placeholder_source_title; + + CreateServiceForFrame(main_frame_); + StartPlayerForFrame(main_frame_); + + { + media_session::test::MockMediaSessionMojoObserver observer( + *GetMediaSession()); + + blink::mojom::SpecMediaMetadataPtr spec_metadata( + blink::mojom::SpecMediaMetadata::New()); + spec_metadata->title = u"title"; + spec_metadata->artist = u"artist"; + spec_metadata->album = u"album"; + + services_[main_frame_]->SetMetadata(std::move(spec_metadata)); + + observer.WaitForExpectedMetadata(expected_metadata); + } +} +#else // !BUILDFLAG(IS_CHROMEOS) +TEST_F(MediaSessionImplServiceRoutingTest, DontHideMediaMetadataInNonCrOS) { + client_.SetShouldHideMetadata(true); + + media_session::MediaMetadata expected_metadata; + expected_metadata.title = u"title"; + expected_metadata.artist = u"artist"; + expected_metadata.album = u"album"; + expected_metadata.source_title = GetSourceTitleForNonEmptyMetadata(); + + CreateServiceForFrame(main_frame_); + StartPlayerForFrame(main_frame_); + + { + media_session::test::MockMediaSessionMojoObserver observer( + *GetMediaSession()); + + blink::mojom::SpecMediaMetadataPtr spec_metadata( + blink::mojom::SpecMediaMetadata::New()); + spec_metadata->title = u"title"; + spec_metadata->artist = u"artist"; + spec_metadata->album = u"album"; + + services_[main_frame_]->SetMetadata(std::move(spec_metadata)); + + observer.WaitForExpectedMetadata(expected_metadata); + } +} +#endif + TEST_F(MediaSessionImplServiceRoutingTest, NotifyObserverMetadataEmptyWhenControllable) { CreateServiceForFrame(main_frame_);
diff --git a/content/browser/service_worker/service_worker_main_resource_loader.cc b/content/browser/service_worker/service_worker_main_resource_loader.cc index a48b4ba..569e2c5d 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader.cc
@@ -314,6 +314,9 @@ case blink::ServiceWorkerRouterSource::SourceType::kFetchEvent: race_network_request_mode = kSkipped; break; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + NOTIMPLEMENTED(); + break; } } }
diff --git a/content/common/service_worker/service_worker_router_evaluator.cc b/content/common/service_worker/service_worker_router_evaluator.cc index 845a466a..cfb6f36d 100644 --- a/content/common/service_worker/service_worker_router_evaluator.cc +++ b/content/common/service_worker/service_worker_router_evaluator.cc
@@ -211,6 +211,13 @@ return false; } break; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + if (!s.cache_source) { + RecordSetupError( + ServiceWorkerRouterEvaluatorErrorEnums::kInvalidSource); + return false; + } + break; } } return true; @@ -538,6 +545,15 @@ case blink::ServiceWorkerRouterSource::SourceType::kFetchEvent: source.Append("fetch-event"); break; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + if (s.cache_source->cache_name) { + base::Value::Dict out_s; + out_s.Set("cache_name", *s.cache_source->cache_name); + source.Append(std::move(out_s)); + } else { + source.Append("cache"); + } + break; } } rule.Set("condition", std::move(condition));
diff --git a/content/common/service_worker/service_worker_router_evaluator_unittest.cc b/content/common/service_worker/service_worker_router_evaluator_unittest.cc index 8af84cb..d69bf62 100644 --- a/content/common/service_worker/service_worker_router_evaluator_unittest.cc +++ b/content/common/service_worker/service_worker_router_evaluator_unittest.cc
@@ -1126,6 +1126,20 @@ source.fetch_event_source.emplace(); rule.sources.push_back(source); } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + source.cache_source.emplace(); + rule.sources.push_back(source); + } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + blink::ServiceWorkerRouterCacheSource cache_source; + cache_source.cache_name = "example_cache_name"; + source.cache_source = cache_source; + rule.sources.push_back(source); + } rules.rules.push_back(rule); } ASSERT_EQ(1U, rules.rules.size()); @@ -1183,6 +1197,12 @@ sources.Append("network"); sources.Append("race-network-and-fetch-handler"); sources.Append("fetch-event"); + sources.Append("cache"); + { + base::Value::Dict source; + source.Set("cache_name", "example_cache_name"); + sources.Append(std::move(source)); + } rule.Set("source", std::move(sources)); } }
diff --git a/content/public/browser/media_session_client.h b/content/public/browser/media_session_client.h index a210288..6a1da30a 100644 --- a/content/public/browser/media_session_client.h +++ b/content/public/browser/media_session_client.h
@@ -36,6 +36,7 @@ virtual bool ShouldHideMetadata(BrowserContext* browser_context) const = 0; virtual std::u16string GetTitlePlaceholder() const = 0; + virtual std::u16string GetSourceTitlePlaceholder() const = 0; virtual std::u16string GetArtistPlaceholder() const = 0; virtual std::u16string GetAlbumPlaceholder() const = 0; virtual SkBitmap GetThumbnailPlaceholder() const = 0;
diff --git a/content/public/test/test_media_session_client.cc b/content/public/test/test_media_session_client.cc index ebdf2d5..3c5593b 100644 --- a/content/public/test/test_media_session_client.cc +++ b/content/public/test/test_media_session_client.cc
@@ -19,6 +19,10 @@ return placeholder_title_; } +std::u16string TestMediaSessionClient::GetSourceTitlePlaceholder() const { + return placeholder_source_title_; +} + std::u16string TestMediaSessionClient::GetArtistPlaceholder() const { return placeholder_artist_; } @@ -36,15 +40,20 @@ } void TestMediaSessionClient::SetTitlePlaceholder(std::u16string title) { - placeholder_title_ = title; + placeholder_title_ = std::move(title); +} + +void TestMediaSessionClient::SetSourceTitlePlaceholder( + std::u16string source_title) { + placeholder_source_title_ = std::move(source_title); } void TestMediaSessionClient::SetArtistPlaceholder(std::u16string artist) { - placeholder_artist_ = artist; + placeholder_artist_ = std::move(artist); } void TestMediaSessionClient::SetAlbumPlaceholder(std::u16string album) { - placeholder_album_ = album; + placeholder_album_ = std::move(album); } void TestMediaSessionClient::SetThumbnailPlaceholder(SkBitmap thumbnail) {
diff --git a/content/public/test/test_media_session_client.h b/content/public/test/test_media_session_client.h index f1c6c04..3e96ea6 100644 --- a/content/public/test/test_media_session_client.h +++ b/content/public/test/test_media_session_client.h
@@ -24,12 +24,14 @@ content::BrowserContext* browser_context) const override; std::u16string GetTitlePlaceholder() const override; + std::u16string GetSourceTitlePlaceholder() const override; std::u16string GetArtistPlaceholder() const override; std::u16string GetAlbumPlaceholder() const override; SkBitmap GetThumbnailPlaceholder() const override; void SetShouldHideMetadata(bool value); void SetTitlePlaceholder(std::u16string title); + void SetSourceTitlePlaceholder(std::u16string source_title); void SetArtistPlaceholder(std::u16string artist); void SetAlbumPlaceholder(std::u16string album); void SetThumbnailPlaceholder(SkBitmap thumbnail); @@ -37,6 +39,7 @@ private: bool should_hide_metadata_ = false; std::u16string placeholder_title_; + std::u16string placeholder_source_title_; std::u16string placeholder_artist_; std::u16string placeholder_album_; SkBitmap placeholder_thumbnail_;
diff --git a/content/renderer/service_worker/service_worker_subresource_loader.cc b/content/renderer/service_worker/service_worker_subresource_loader.cc index c19d95b..5eab9616 100644 --- a/content/renderer/service_worker/service_worker_subresource_loader.cc +++ b/content/renderer/service_worker/service_worker_subresource_loader.cc
@@ -374,6 +374,9 @@ case blink::ServiceWorkerRouterSource::SourceType::kFetchEvent: race_network_request_mode = kSkipped; break; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + NOTIMPLEMENTED(); + break; } }
diff --git a/docs/updating_clang_format_binaries.md b/docs/updating_clang_format_binaries.md index 2e1f1c7..93b1035a 100644 --- a/docs/updating_clang_format_binaries.md +++ b/docs/updating_clang_format_binaries.md
@@ -74,12 +74,12 @@ # use old clang-format find base -name '*.cc' -o -name '*.c' -o -name '*.h' -o -name '*.mm' | xargs ./buildtools/linux64/clang-format -i git commit -a -git cl upload +git cl upload --bypass-hooks ## New patchset on gerrit CL with results of new clang-format. # update to new clang-format find base -name '*.cc' -o -name '*.c' -o -name '*.h' -o -name '*.mm' | xargs ./buildtools/linux64/clang-format -i git commit -a --amend --no-edit -git cl upload +git cl upload --bypass-hooks ``` If there are any unexpected diffs, file a bug upstream (and fix it if you can :)).
diff --git a/extensions/common/api/declarative_net_request.idl b/extensions/common/api/declarative_net_request.idl index cca180f5..c8e969d 100644 --- a/extensions/common/api/declarative_net_request.idl +++ b/extensions/common/api/declarative_net_request.idl
@@ -689,7 +689,7 @@ // |callback|: Called once the update is complete. In case of an error, // $(ref:runtime.lastError) will be set and no change will be made to the // enabled static rules. - [nodoc, supportsPromises] static void updateStaticRules( + [supportsPromises] static void updateStaticRules( UpdateStaticRulesOptions options, optional EmptyCallback callback); @@ -698,7 +698,7 @@ // |options|: Specifies the ruleset to query. // |callback|: Called with a list of ids that correspond to the disabled // rules in that ruleset. - [nodoc, supportsPromises] static void getDisabledRuleIds( + [supportsPromises] static void getDisabledRuleIds( GetDisabledRuleIdsOptions options, GetDisabledRuleIdsCallback callback);
diff --git a/gpu/ipc/service/gpu_channel_manager.cc b/gpu/ipc/service/gpu_channel_manager.cc index 7aef1c1..d1aebd6 100644 --- a/gpu/ipc/service/gpu_channel_manager.cc +++ b/gpu/ipc/service/gpu_channel_manager.cc
@@ -972,15 +972,26 @@ return nullptr; } + auto gr_context_type = gpu_preferences_.gr_context_type; +#if BUILDFLAG(IS_APPLE) + const bool want_graphite = gr_context_type == GrContextType::kGraphiteDawn || + gr_context_type == GrContextType::kGraphiteMetal; + const bool is_angle_metal = + gl::GetANGLEImplementation() == gl::ANGLEImplementation::kMetal; + // Fallback from Graphite to Ganesh/GL if ANGLE is not using Metal too. + if (want_graphite && !is_angle_metal) { + gr_context_type = GrContextType::kGL; + } +#endif + // TODO(penghuang): https://crbug.com/899735 Handle device lost for Vulkan. auto shared_context_state = base::MakeRefCounted<SharedContextState>( std::move(share_group), std::move(surface), std::move(context), use_virtualized_gl_contexts, base::BindOnce(&GpuChannelManager::OnContextLost, base::Unretained(this), context_lost_count_ + 1), - gpu_preferences_.gr_context_type, vulkan_context_provider_, - metal_context_provider_, dawn_context_provider_, - peak_memory_monitor_.GetWeakPtr()); + gr_context_type, vulkan_context_provider_, metal_context_provider_, + dawn_context_provider_, peak_memory_monitor_.GetWeakPtr()); // Initialize GL context, so Vulkan and GL interop can work properly. auto feature_info = base::MakeRefCounted<gles2::FeatureInfo>(
diff --git a/ios/chrome/browser/commerce/price_notifications/price_notifications_tab_helper.mm b/ios/chrome/browser/commerce/price_notifications/price_notifications_tab_helper.mm index 3c01118..7ff3658e 100644 --- a/ios/chrome/browser/commerce/price_notifications/price_notifications_tab_helper.mm +++ b/ios/chrome/browser/commerce/price_notifications/price_notifications_tab_helper.mm
@@ -38,7 +38,7 @@ void OnProductInfoUrl( WeakPriceNotificationsPresenter* presenter, const GURL& product_url, - const absl::optional<commerce::ProductInfo>& product_info) { + const absl::optional<const commerce::ProductInfo>& product_info) { DCHECK(presenter); if (!product_info) { return;
diff --git a/ios/chrome/browser/infobars/overlays/translate_overlay_tab_helper.h b/ios/chrome/browser/infobars/overlays/translate_overlay_tab_helper.h index ed5cbcc..7a984d8e 100644 --- a/ios/chrome/browser/infobars/overlays/translate_overlay_tab_helper.h +++ b/ios/chrome/browser/infobars/overlays/translate_overlay_tab_helper.h
@@ -45,7 +45,7 @@ TranslateOverlayTabHelper(web::WebState* web_state); // Observers to listen to translation completions. - base::ObserverList<Observer> observers_; + base::ObserverList<Observer, true> observers_; private: friend class web::WebStateUserData<TranslateOverlayTabHelper>;
diff --git a/ios/chrome/browser/shared/ui/table_view/cells/table_view_illustrated_item.mm b/ios/chrome/browser/shared/ui/table_view/cells/table_view_illustrated_item.mm index 229f87a..d220f1a2 100644 --- a/ios/chrome/browser/shared/ui/table_view/cells/table_view_illustrated_item.mm +++ b/ios/chrome/browser/shared/ui/table_view/cells/table_view_illustrated_item.mm
@@ -130,6 +130,8 @@ buttonConfiguration.contentInsets = NSDirectionalEdgeInsetsMake( kButtonTitleVerticalContentInset, kButtonTitleHorizontalContentInset, kButtonTitleVerticalContentInset, kButtonTitleHorizontalContentInset); + buttonConfiguration.baseForegroundColor = + [UIColor colorNamed:kSolidButtonTextColor]; buttonConfiguration.background.backgroundColor = [UIColor colorNamed:kBlueColor]; _button.configuration = buttonConfiguration;
diff --git a/ios/chrome/browser/signin/fake_system_identity_interaction_manager.mm b/ios/chrome/browser/signin/fake_system_identity_interaction_manager.mm index 8377e83..8cf893d 100644 --- a/ios/chrome/browser/signin/fake_system_identity_interaction_manager.mm +++ b/ios/chrome/browser/signin/fake_system_identity_interaction_manager.mm
@@ -143,6 +143,10 @@ _signinCompletion = completion; _authActivityViewController = [[FakeAuthActivityViewController alloc] initWithManager:self]; + BOOL isIPad = + UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad; + _authActivityViewController.modalPresentationStyle = + isIPad ? UIModalPresentationFormSheet : UIModalPresentationFullScreen; __weak FakeSystemIdentityInteractionManager* weakSelf = self; [viewController presentViewController:_authActivityViewController
diff --git a/ios/chrome/browser/supervised_user/ios_web_content_handler_impl.h b/ios/chrome/browser/supervised_user/ios_web_content_handler_impl.h index 7fa9a1fd..f9ba477 100644 --- a/ios/chrome/browser/supervised_user/ios_web_content_handler_impl.h +++ b/ios/chrome/browser/supervised_user/ios_web_content_handler_impl.h
@@ -5,7 +5,7 @@ #ifndef IOS_CHROME_BROWSER_SUPERVISED_USER_IOS_WEB_CONTENT_HANDLER_IMPL_H_ #define IOS_CHROME_BROWSER_SUPERVISED_USER_IOS_WEB_CONTENT_HANDLER_IMPL_H_ -#import "base/allocator/partition_allocator/pointers/raw_ptr.h" +#import "base/memory/raw_ptr.h" #import "base/memory/weak_ptr.h" #import "components/supervised_user/core/browser/web_content_handler.h" #import "url/gurl.h"
diff --git a/ios/chrome/browser/ui/autofill/autofill_profile_edit_table_view_constants.h b/ios/chrome/browser/ui/autofill/autofill_profile_edit_table_view_constants.h index 3d21ee7..b12675fb 100644 --- a/ios/chrome/browser/ui/autofill/autofill_profile_edit_table_view_constants.h +++ b/ios/chrome/browser/ui/autofill/autofill_profile_edit_table_view_constants.h
@@ -17,7 +17,6 @@ AutofillProfileDetailsSectionIdentifierFields = kSectionIdentifierEnumZero, AutofillProfileDetailsSectionIdentifierErrorFooter, AutofillProfileDetailsSectionIdentifierFooter, - AutofillProfileDetailsSectionIdentifierMigrationToAccount }; // Identifier for item types for autofill profile edit views.
diff --git a/ios/chrome/browser/ui/autofill/branding/branding_mediator.mm b/ios/chrome/browser/ui/autofill/branding/branding_mediator.mm index 0e85bd9..125d022b 100644 --- a/ios/chrome/browser/ui/autofill/branding/branding_mediator.mm +++ b/ios/chrome/browser/ui/autofill/branding/branding_mediator.mm
@@ -4,7 +4,7 @@ #import "ios/chrome/browser/ui/autofill/branding/branding_mediator.h" -#import "base/allocator/partition_allocator/pointers/raw_ptr.h" +#import "base/memory/raw_ptr.h" #import "base/metrics/user_metrics.h" #import "components/prefs/pref_service.h" #import "ios/chrome/browser/shared/model/prefs/pref_names.h"
diff --git a/ios/chrome/browser/ui/bookmarks/home/bookmarks_home_view_controller.mm b/ios/chrome/browser/ui/bookmarks/home/bookmarks_home_view_controller.mm index 2156201..fc0e90a 100644 --- a/ios/chrome/browser/ui/bookmarks/home/bookmarks_home_view_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/home/bookmarks_home_view_controller.mm
@@ -144,11 +144,6 @@ UITableViewDataSource, UITableViewDelegate> -// The Browser in which bookmarks are presented -// TODO(crbug.com/1423926): Need to convert this property into: -// base::WeakPtr<Browser> _browser. -@property(nonatomic, assign) Browser* browser; - // The user's browser state model used. @property(nonatomic, assign) ChromeBrowserState* browserState; @@ -217,6 +212,8 @@ @implementation BookmarksHomeViewController { // The localOrSyncable bookmark model used. base::WeakPtr<bookmarks::BookmarkModel> _localOrSyncableBookmarkModel; + // The Browser in which bookmarks are presented + base::WeakPtr<Browser> _browser; // The account bookmark model used. base::WeakPtr<bookmarks::BookmarkModel> _accountBookmarkModel; // Bridge to register for bookmark changes in the localOrSyncable model. @@ -238,10 +235,9 @@ UITableViewStyle style = ChromeTableViewStyle(); self = [super initWithStyle:style]; if (self) { - _browser = browser; - _browserState = - _browser->GetBrowserState()->GetOriginalChromeBrowserState(); - _webStateList = _browser->GetWebStateList(); + _browser = browser->AsWeakPtr(); + _browserState = browser->GetBrowserState()->GetOriginalChromeBrowserState(); + _webStateList = browser->GetWebStateList(); _faviconLoader = IOSChromeFaviconLoaderFactory::GetForBrowserState(_browserState); @@ -272,7 +268,7 @@ [self.mediator disconnect]; self.mediator.consumer = nil; self.mediator = nil; - self.browser = nullptr; + _browser = nullptr; self.browserState = nullptr; [self.searchController dismissViewControllerAnimated:YES completion:nil]; [self dismissActionSheetCoordinator]; @@ -513,7 +509,7 @@ // Create the mediator and hook up the table view. self.mediator = [[BookmarksHomeMediator alloc] - initWithBrowser:_browser + initWithBrowser:_browser.get() baseViewController:self.navigationController localOrSyncableBookmarkModel:_localOrSyncableBookmarkModel.get() accountBookmarkModel:_accountBookmarkModel.get() @@ -682,7 +678,7 @@ // Record that this context menu was shown to the user. RecordMenuShown(MenuScenarioHistogram::kBookmarkEntry); BrowserActionFactory* actionFactory = [[BrowserActionFactory alloc] - initWithBrowser:self.browser + initWithBrowser:_browser.get() scenario:MenuScenarioHistogram::kBookmarkEntry]; NSMutableArray<UIMenuElement*>* menuElements = [[NSMutableArray alloc] init]; __weak __typeof(self) weakSelf = self; @@ -801,7 +797,7 @@ const BookmarkNode* selectedFolder = editedNode->parent(); _folderChooserCoordinator = [[BookmarksFolderChooserCoordinator alloc] initWithBaseViewController:self.navigationController - browser:_browser + browser:_browser.get() hiddenNodes:nodes]; [_folderChooserCoordinator setSelectedFolder:selectedFolder]; _folderChooserCoordinator.delegate = self; @@ -841,7 +837,7 @@ - (void)ensureBookmarksCoordinator { if (!self.bookmarksCoordinator) { self.bookmarksCoordinator = - [[BookmarksCoordinator alloc] initWithBrowser:self.browser]; + [[BookmarksCoordinator alloc] initWithBrowser:_browser.get()]; self.bookmarksCoordinator.baseViewController = self; self.bookmarksCoordinator.delegate = self; } @@ -886,7 +882,7 @@ newTab:(BOOL)newTab { if (inIncognito) { IncognitoReauthSceneAgent* reauthAgent = [IncognitoReauthSceneAgent - agentFromScene:SceneStateBrowserAgent::FromBrowser(self.browser) + agentFromScene:SceneStateBrowserAgent::FromBrowser(_browser.get()) ->GetSceneState()]; if (reauthAgent.authenticationRequired) { __weak BookmarksHomeViewController* weakSelf = self; @@ -1383,7 +1379,7 @@ UrlLoadParams params = UrlLoadParams::InCurrentTab(url); params.web_params.transition_type = ui::PAGE_TRANSITION_AUTO_BOOKMARK; - UrlLoadingBrowserAgent::FromBrowser(self.browser)->Load(params); + UrlLoadingBrowserAgent::FromBrowser(_browser.get())->Load(params); } - (void)addNewFolder { @@ -1427,7 +1423,7 @@ - (BookmarksHomeViewController*)createControllerWithDisplayedFolderNode: (const bookmarks::BookmarkNode*)displayedFolderNode { BookmarksHomeViewController* controller = - [[BookmarksHomeViewController alloc] initWithBrowser:self.browser]; + [[BookmarksHomeViewController alloc] initWithBrowser:_browser.get()]; controller.displayedFolderNode = displayedFolderNode; controller.homeDelegate = self.homeDelegate; controller.applicationCommandsHandler = self.applicationCommandsHandler; @@ -1664,7 +1660,7 @@ UIView* cellView = [self.tableView cellForRowAtIndexPath:indexPath]; self.sharingCoordinator = [[SharingCoordinator alloc] initWithBaseViewController:self - browser:self.browser + browser:_browser.get() params:params originView:cellView]; [self.sharingCoordinator start]; @@ -1672,12 +1668,13 @@ // Returns whether the incognito mode is forced. - (BOOL)isIncognitoForced { - return IsIncognitoModeForced(self.browser->GetBrowserState()->GetPrefs()); + return IsIncognitoModeForced(_browser.get()->GetBrowserState()->GetPrefs()); } // Returns whether the incognito mode is available. - (BOOL)isIncognitoAvailable { - return !IsIncognitoModeDisabled(self.browser->GetBrowserState()->GetPrefs()); + return !IsIncognitoModeDisabled( + _browser.get()->GetBrowserState()->GetPrefs()); } #pragma mark - Loading and Empty States @@ -1814,7 +1811,7 @@ self.actionSheetCoordinator = [[ActionSheetCoordinator alloc] initWithBaseViewController:self - browser:_browser + browser:_browser.get() title:nil message:nil barButtonItem:self.moreButton]; @@ -2264,7 +2261,7 @@ self.actionSheetCoordinator = [[ActionSheetCoordinator alloc] initWithBaseViewController:self - browser:_browser + browser:_browser.get() title:nil message:nil rect:CGRectMake(touchPoint.x, touchPoint.y, 1, 1)
diff --git a/ios/chrome/browser/ui/first_run/first_run_coordinator.mm b/ios/chrome/browser/ui/first_run/first_run_coordinator.mm index 7b391122..2d7fcd9 100644 --- a/ios/chrome/browser/ui/first_run/first_run_coordinator.mm +++ b/ios/chrome/browser/ui/first_run/first_run_coordinator.mm
@@ -11,7 +11,6 @@ #import "base/notreached.h" #import "base/time/time.h" #import "components/signin/public/base/signin_metrics.h" -#import "components/signin/public/base/signin_switches.h" #import "ios/chrome/browser/first_run/first_run_metrics.h" #import "ios/chrome/browser/shared/model/browser/browser.h" #import "ios/chrome/browser/shared/model/browser_state/chrome_browser_state.h" @@ -55,10 +54,6 @@ } - (void)start { - bool isFinchFreEnabled = base::FeatureList::IsEnabled(switches::kFinchIosFre); - // TODO(crbug.com/1447028): Remove this histogram when the finch experiment - // is finished. - base::UmaHistogramBoolean("FirstRun.iOSFreFinchEnabled", isFinchFreEnabled); [self presentScreen:[self.screenProvider nextScreenType]]; void (^completion)(void) = ^{ base::UmaHistogramEnumeration("FirstRun.Stage", first_run::kStart);
diff --git a/ios/chrome/browser/ui/first_run/first_run_egtest.mm b/ios/chrome/browser/ui/first_run/first_run_egtest.mm index 36fede33..93b7fb0 100644 --- a/ios/chrome/browser/ui/first_run/first_run_egtest.mm +++ b/ios/chrome/browser/ui/first_run/first_run_egtest.mm
@@ -21,6 +21,7 @@ #import "ios/chrome/browser/shared/ui/elements/elements_constants.h" #import "ios/chrome/browser/signin/capabilities_types.h" #import "ios/chrome/browser/signin/fake_system_identity.h" +#import "ios/chrome/browser/signin/test_constants.h" #import "ios/chrome/browser/ui/authentication/signin/signin_constants.h" #import "ios/chrome/browser/ui/authentication/signin_earl_grey.h" #import "ios/chrome/browser/ui/authentication/signin_earl_grey_app_interface.h" @@ -172,7 +173,8 @@ // Relaunch app at each test to rewind the startup state. config.relaunch_policy = ForceRelaunchByKilling; - if ([self isRunningTest:@selector(testHistorySyncSkipIfNoSignIn)] || + if ([self isRunningTest:@selector(testSignInWithNoAccount)] || + [self isRunningTest:@selector(testHistorySyncSkipIfNoSignIn)] || [self isRunningTest:@selector(testHistorySyncShownAfterSignIn)] || [self isRunningTest:@selector (testSignInSubtitleIfHistorySyncOptInEnabled)] || @@ -901,7 +903,48 @@ [SigninEarlGrey verifySyncUIEnabled:YES]; } -#pragma mark - History Sync Opt-in +#pragma mark - Sync UI Disabled + +// Tests sign-in with FRE when there's no account on the device. +// See https://crbug.com/1471972. +- (void)testSignInWithNoAccount { + // Add account. + [[self + elementInteractionWithGreyMatcher:PromoStylePrimaryActionButtonMatcher() + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + FakeSystemIdentity* fakeIdentity = [FakeSystemIdentity fakeIdentity1]; + [SigninEarlGrey addFakeIdentityForSSOAuthAddAccountFlow:fakeIdentity]; + [[EarlGrey + selectElementWithMatcher:grey_allOf( + grey_accessibilityID( + kFakeAuthAddAccountButtonIdentifier), + grey_sufficientlyVisible(), nil)] + performAction:grey_tap()]; + // Verify that the primary button text is correct. + NSString* continueAsText = l10n_util::GetNSStringF( + IDS_IOS_FIRST_RUN_SIGNIN_CONTINUE_AS, + base::SysNSStringToUTF16(fakeIdentity.userGivenName)); + [[EarlGrey + selectElementWithMatcher:grey_allOf( + PromoStylePrimaryActionButtonMatcher(), + grey_descendant(grey_text(continueAsText)), + nil)] assertWithMatcher:grey_notNil()]; + // Sign-in. + [[self + elementInteractionWithGreyMatcher:PromoStylePrimaryActionButtonMatcher() + scrollViewIdentifier: + kPromoStyleScrollViewAccessibilityIdentifier] + performAction:grey_tap()]; + // Verify that the History Sync Opt-In screen is shown. + [[EarlGrey + selectElementWithMatcher:grey_accessibilityID( + kHistorySyncViewAccessibilityIdentifier)] + assertWithMatcher:grey_sufficientlyVisible()]; + // Check signed in. + [SigninEarlGrey verifySignedInWithFakeIdentity:fakeIdentity]; +} // Tests if the user skip the Sign-in step, the History Sync Opt-in screen is // skipped and the default browser screen is shown.
diff --git a/ios/chrome/browser/ui/price_notifications/price_notifications_price_tracking_mediator.mm b/ios/chrome/browser/ui/price_notifications/price_notifications_price_tracking_mediator.mm index 593f34d..578286b 100644 --- a/ios/chrome/browser/ui/price_notifications/price_notifications_price_tracking_mediator.mm +++ b/ios/chrome/browser/ui/price_notifications/price_notifications_price_tracking_mediator.mm
@@ -294,7 +294,7 @@ item.entryURL, base::BindOnce(^( const GURL& productURL, - const absl::optional<commerce::ProductInfo>& productInfo) { + const absl::optional<const commerce::ProductInfo>& productInfo) { PriceNotificationsPriceTrackingMediator* strongSelf = weakSelf; if (!strongSelf) { return; @@ -368,7 +368,7 @@ currentSiteURL, base::BindOnce( ^(const GURL& productURL, - const absl::optional<commerce::ProductInfo>& productInfo) { + const absl::optional<const commerce::ProductInfo>& productInfo) { PriceNotificationsPriceTrackingMediator* strongSelf = weakSelf; if (!strongSelf) { return;
diff --git a/ios/chrome/browser/ui/reading_list/BUILD.gn b/ios/chrome/browser/ui/reading_list/BUILD.gn index 9c035dbd..b070687 100644 --- a/ios/chrome/browser/ui/reading_list/BUILD.gn +++ b/ios/chrome/browser/ui/reading_list/BUILD.gn
@@ -279,7 +279,6 @@ "//base", "//base/test:test_support", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui/popup_menu:constants", "//ios/chrome/test/earl_grey:eg_test_support+eg2", "//ios/testing/earl_grey:eg_test_support+eg2", "//ui/base",
diff --git a/ios/chrome/browser/ui/reading_list/DEPS b/ios/chrome/browser/ui/reading_list/DEPS index ac4b905..320dc09d 100644 --- a/ios/chrome/browser/ui/reading_list/DEPS +++ b/ios/chrome/browser/ui/reading_list/DEPS
@@ -3,7 +3,6 @@ "+ios/chrome/browser/ui/incognito_reauth", "+ios/chrome/browser/ui/menu", "+ios/chrome/browser/ui/keyboard/UIKeyCommand+Chrome.h", - "+ios/chrome/browser/ui/popup_menu", "+ios/chrome/browser/ui/settings/cells/sync_switch_item.h", "+ios/chrome/browser/ui/sharing", ]
diff --git a/ios/chrome/browser/ui/reading_list/reading_list_egtest_utils.mm b/ios/chrome/browser/ui/reading_list/reading_list_egtest_utils.mm index 352670b9..677be05 100644 --- a/ios/chrome/browser/ui/reading_list/reading_list_egtest_utils.mm +++ b/ios/chrome/browser/ui/reading_list/reading_list_egtest_utils.mm
@@ -4,7 +4,6 @@ #import "ios/chrome/browser/ui/reading_list/reading_list_egtest_utils.h" -#import "ios/chrome/browser/ui/popup_menu/popup_menu_constants.h" #import "ios/chrome/browser/ui/reading_list/reading_list_app_interface.h" #import "ios/chrome/browser/ui/reading_list/reading_list_constants.h" #import "ios/chrome/grit/ios_strings.h" @@ -52,18 +51,6 @@ [ChromeEarlGrey waitForPageToFinishLoading]; // Add the page to the Reading List. [ChromeEarlGreyUI openToolsMenu]; - - // TODO(crbug.com/1473383): Remove workaround when tapping works properly. - if (@available(iOS 17.0, *)) { - // The button is manually tappable which is why tests that use this method - // are not disabled. Instead, we implement this workaround for the tools - // menu action item not being tappable after being tapped in a separate - // instance during EG tests. - [[EarlGrey selectElementWithMatcher:grey_accessibilityID( - kPopupMenuToolsMenuActionListId)] - performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)]; - } - [ChromeEarlGreyUI tapToolsMenuAction:chrome_test_util::ButtonWithAccessibilityLabelId( IDS_IOS_SHARE_MENU_READING_LIST_ACTION)];
diff --git a/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller.mm b/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller.mm index 50ebd4df..d7c3f20 100644 --- a/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller.mm
@@ -85,14 +85,10 @@ TableViewModel* model = self.tableViewModel; if (self.showMigrateToAccountSection) { - [model addSectionWithIdentifier: - AutofillProfileDetailsSectionIdentifierMigrationToAccount]; [model addItem:[self migrateToAccountRecommendationItem] - toSectionWithIdentifier: - AutofillProfileDetailsSectionIdentifierMigrationToAccount]; + toSectionWithIdentifier:AutofillProfileDetailsSectionIdentifierFields]; [model addItem:[self migrateToAccountButtonItem] - toSectionWithIdentifier: - AutofillProfileDetailsSectionIdentifierMigrationToAccount]; + toSectionWithIdentifier:AutofillProfileDetailsSectionIdentifierFields]; } [self.handler loadFooterForSettings]; @@ -129,13 +125,6 @@ [self loadModel]; [self.handler reconfigureCells]; - if (self.showMigrateToAccountSection) { - [self - reconfigureCellsForItems: - [self.tableViewModel - itemsInSectionWithIdentifier: - AutofillProfileDetailsSectionIdentifierMigrationToAccount]]; - } } #pragma mark - UITableViewDataSource @@ -172,11 +161,11 @@ void (^completion)(BOOL) = ^(BOOL) { [weakSelf showPostMigrationToast]; }; - [self removeMigrateButtonSection:completion]; + [self removeMigrateButton:completion]; } else { // Show the profile in the edit mode. self.editIncompleteProfileForAccountView = YES; - [self removeMigrateButtonSection:nil]; + [self removeMigrateButton:nil]; [self editButtonPressed]; [self.handler setMoveToAccountFromSettings:YES]; } @@ -253,29 +242,39 @@ #pragma mark - Private // Removes the migrate button section from the view. -- (void)removeMigrateButtonSection:(void (^)(BOOL finished))onCompletion { +- (void)removeMigrateButton:(void (^)(BOOL finished))onCompletion { + __weak AutofillSettingsProfileEditTableViewController* weakSelf = self; [self performBatchTableViewUpdates:^{ - [self removeSectionWithIdentifier: - AutofillProfileDetailsSectionIdentifierMigrationToAccount - withRowAnimation:UITableViewRowAnimationFade]; + TableViewModel* model = weakSelf.tableViewModel; + NSIndexPath* indexPathForMigrateRecommendationItem = [model + indexPathForItemType: + AutofillProfileDetailsItemTypeMigrateToAccountRecommendation + sectionIdentifier:AutofillProfileDetailsSectionIdentifierFields]; + NSIndexPath* indexPathForMigrateButton = [model + indexPathForItemType: + AutofillProfileDetailsItemTypeMigrateToAccountButton + sectionIdentifier:AutofillProfileDetailsSectionIdentifierFields]; + + [model removeItemWithType: + AutofillProfileDetailsItemTypeMigrateToAccountRecommendation + fromSectionWithIdentifier: + AutofillProfileDetailsSectionIdentifierFields]; + [model removeItemWithType: + AutofillProfileDetailsItemTypeMigrateToAccountButton + fromSectionWithIdentifier: + AutofillProfileDetailsSectionIdentifierFields]; + + [weakSelf.tableView + deleteRowsAtIndexPaths:@[ + indexPathForMigrateRecommendationItem, indexPathForMigrateButton + ] + withRowAnimation:UITableViewRowAnimationAutomatic]; } completion:onCompletion]; self.showMigrateToAccountSection = NO; } -// Removes the given section if it exists. -- (void)removeSectionWithIdentifier:(NSInteger)sectionIdentifier - withRowAnimation:(UITableViewRowAnimation)animation { - TableViewModel* model = self.tableViewModel; - if ([model hasSectionForSectionIdentifier:sectionIdentifier]) { - NSInteger section = [model sectionForSectionIdentifier:sectionIdentifier]; - [model removeSectionWithIdentifier:sectionIdentifier]; - [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:section] - withRowAnimation:animation]; - } -} - - (void)showPostMigrationToast { CHECK(self.snackbarCommandsHandler); CHECK(_userEmail.length)
diff --git a/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller_unittest.mm index 70c8400..2d88f3f2 100644 --- a/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/autofill/autofill_settings_profile_edit_table_view_controller_unittest.mm
@@ -243,21 +243,20 @@ int rowCnt = base::FeatureList::IsEnabled( autofill::features::kAutofillEnableSupportForHonorificPrefixes) - ? 11 - : 10; + ? 13 + : 12; - EXPECT_EQ(2, [model numberOfSections]); + EXPECT_EQ(1, [model numberOfSections]); EXPECT_EQ(rowCnt, [model numberOfItemsInSection:0]); - EXPECT_EQ(2, [model numberOfItemsInSection:1]); NSString* migrateButtonDescription = l10n_util::GetNSStringF( IDS_IOS_SETTINGS_AUTOFILL_MIGRATE_ADDRESS_TO_ACCOUNT_BUTTON_DESCRIPTION, kTestSyncingEmail); - TableViewItem* descriptionItem = GetTableViewItem(1, 0); + TableViewItem* descriptionItem = GetTableViewItem(0, rowCnt - 2); EXPECT_NSEQ( static_cast<SettingsImageDetailTextItem*>(descriptionItem).detailText, migrateButtonDescription); EXPECT_NSEQ( - static_cast<TableViewTextItem*>(GetTableViewItem(1, 1)).text, + static_cast<TableViewTextItem*>(GetTableViewItem(0, rowCnt - 1)).text, l10n_util::GetNSString( IDS_IOS_SETTINGS_AUTOFILL_MIGRATE_ADDRESS_TO_ACCOUNT_BUTTON_TITLE)); }
diff --git a/ios/chrome/browser/ui/settings/cells/search_engine_item.mm b/ios/chrome/browser/ui/settings/cells/search_engine_item.mm index d3c420f..d31c2f818 100644 --- a/ios/chrome/browser/ui/settings/cells/search_engine_item.mm +++ b/ios/chrome/browser/ui/settings/cells/search_engine_item.mm
@@ -66,4 +66,10 @@ [cell configureUILayout]; } +- (BOOL)isEqual:(SearchEngineItem*)otherItem { + return (self.text == otherItem.text) && + (self.detailText == otherItem.detailText) && + (self.URL == otherItem.URL); +} + @end
diff --git a/ios/chrome/browser/ui/settings/cells/search_engine_item_unittest.mm b/ios/chrome/browser/ui/settings/cells/search_engine_item_unittest.mm index cb23b92..44f5688 100644 --- a/ios/chrome/browser/ui/settings/cells/search_engine_item_unittest.mm +++ b/ios/chrome/browser/ui/settings/cells/search_engine_item_unittest.mm
@@ -47,3 +47,46 @@ EXPECT_EQ(item.uniqueIdentifier, URLCell.cellUniqueIdentifier); EXPECT_EQ(UITableViewCellAccessoryCheckmark, URLCell.accessoryType); } + +TEST_F(SearchEngineItemTest, isEqual) { + NSString* text = @"Title text"; + NSString* detailText = @"www.google.com"; + GURL URL = net::GURLWithNSURL([NSURL URLWithString:detailText]); + NSString* otherText = @"Other Title text"; + NSString* otherDetailText = @"www.notGoogle.com"; + GURL otherURL = net::GURLWithNSURL([NSURL URLWithString:otherDetailText]); + + SearchEngineItem* item = [[SearchEngineItem alloc] initWithType:0]; + item.text = text; + item.detailText = detailText; + item.URL = URL; + + SearchEngineItem* sameItem = [[SearchEngineItem alloc] initWithType:0]; + sameItem.text = text; + sameItem.detailText = detailText; + sameItem.URL = URL; + + EXPECT_TRUE([item isEqual:sameItem]); + + SearchEngineItem* itemWithDifferentText = + [[SearchEngineItem alloc] initWithType:0]; + itemWithDifferentText.text = otherText; + itemWithDifferentText.detailText = item.detailText; + itemWithDifferentText.URL = item.URL; + + EXPECT_FALSE([item isEqual:itemWithDifferentText]); + + SearchEngineItem* itemWithDifferentDetailText = + [[SearchEngineItem alloc] initWithType:0]; + itemWithDifferentDetailText.text = item.text; + itemWithDifferentDetailText.detailText = otherDetailText; + itemWithDifferentDetailText.URL = item.URL; + + EXPECT_FALSE([item isEqual:itemWithDifferentDetailText]); + + SearchEngineItem* itemWithDifferentURL = + [[SearchEngineItem alloc] initWithType:0]; + itemWithDifferentURL.text = item.text; + itemWithDifferentURL.detailText = item.detailText; + itemWithDifferentURL.URL = otherURL; +}
diff --git a/ios/chrome/browser/ui/settings/password/password_details/password_details_coordinator.mm b/ios/chrome/browser/ui/settings/password/password_details/password_details_coordinator.mm index 17b5765..6a631759 100644 --- a/ios/chrome/browser/ui/settings/password/password_details/password_details_coordinator.mm +++ b/ios/chrome/browser/ui/settings/password/password_details/password_details_coordinator.mm
@@ -40,6 +40,7 @@ #import "ios/chrome/browser/ui/settings/password/password_details/password_details_table_view_controller.h" #import "ios/chrome/browser/ui/settings/password/password_manager_ui_features.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator_delegate.h" #import "ios/chrome/browser/ui/settings/password/reauthentication/reauthentication_coordinator.h" #import "ios/chrome/browser/ui/settings/utils/password_utils.h" #import "ios/chrome/common/ui/reauthentication/reauthentication_module.h" @@ -51,7 +52,8 @@ @interface PasswordDetailsCoordinator () <PasswordDetailsHandler, PasswordDetailsMediatorDelegate, - ReauthenticationCoordinatorDelegate> { + ReauthenticationCoordinatorDelegate, + PasswordSharingCoordinatorDelegate> { password_manager::AffiliatedGroup _affiliatedGroup; password_manager::CredentialUIEntry _credential; @@ -389,6 +391,7 @@ self.passwordSharingCoordinator = [[PasswordSharingCoordinator alloc] initWithBaseViewController:self.viewController browser:self.browser]; + self.passwordSharingCoordinator.delegate = self; [self.passwordSharingCoordinator start]; } @@ -459,6 +462,17 @@ [self dismissPasswordSharingCoordinator]; } +#pragma mark - PasswordSharingCoordinatorDelegate + +- (void)passwordSharingCoordinatorDidRemove: + (PasswordSharingCoordinator*)coordinator { + if (self.passwordSharingCoordinator == coordinator) { + [self.passwordSharingCoordinator stop]; + self.passwordSharingCoordinator.delegate = nil; + self.passwordSharingCoordinator = nil; + } +} + #pragma mark - Private - (void)dismissActionSheetCoordinator {
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/BUILD.gn b/ios/chrome/browser/ui/settings/password/password_sharing/BUILD.gn index 0199f3d..e2e700a 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/BUILD.gn +++ b/ios/chrome/browser/ui/settings/password/password_sharing/BUILD.gn
@@ -6,12 +6,14 @@ sources = [ "family_picker_coordinator.h", "family_picker_coordinator.mm", + "family_picker_coordinator_delegate.h", "family_picker_mediator.h", "family_picker_mediator.mm", "password_picker_coordinator.h", "password_picker_coordinator.mm", "password_sharing_coordinator.h", "password_sharing_coordinator.mm", + "password_sharing_coordinator_delegate.h", "password_sharing_mediator.h", "password_sharing_mediator.mm", "password_sharing_mediator_delegate.h", @@ -35,6 +37,7 @@ "family_picker_consumer.h", "family_picker_view_controller.h", "family_picker_view_controller.mm", + "family_picker_view_controller_presentation_delegate.h", "password_picker_view_controller.h", "password_picker_view_controller.mm", "password_sharing_view_controller.h",
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.h b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.h index d8451ba..2ca7813 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.h +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.h
@@ -7,6 +7,7 @@ #import "ios/chrome/browser/shared/coordinator/chrome_coordinator/chrome_coordinator.h" +@protocol FamilyPickerCoordinatorDelegate; @class RecipientInfoForIOSDisplay; // This coordinator presents a list of Google Family members of a user that @@ -22,6 +23,9 @@ - (instancetype)initWithBaseViewController:(UIViewController*)viewController browser:(Browser*)browser NS_UNAVAILABLE; +// Delegate handling coordinator dismissal. +@property(nonatomic, weak) id<FamilyPickerCoordinatorDelegate> delegate; + @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.mm b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.mm index 5f23c17..b53e6b83 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.mm +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.mm
@@ -6,11 +6,14 @@ #import "ios/chrome/browser/shared/ui/table_view/table_view_navigation_controller.h" #import "ios/chrome/browser/shared/ui/table_view/table_view_utils.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator_delegate.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_mediator.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller_presentation_delegate.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/recipient_info.h" -@interface FamilyPickerCoordinator () { +@interface FamilyPickerCoordinator () < + FamilyPickerViewControllerPresentationDelegate> { NSArray<RecipientInfoForIOSDisplay*>* _recipients; } @@ -45,6 +48,7 @@ self.viewController = [[FamilyPickerViewController alloc] initWithStyle:ChromeTableViewStyle()]; + self.viewController.delegate = self; self.mediator = [[FamilyPickerMediator alloc] initWithRecipients:_recipients]; self.mediator.consumer = self.viewController; self.navigationController = @@ -73,4 +77,10 @@ self.mediator = nil; } +#pragma mark - FamilyPickerViewControllerPresentationDelegate + +- (void)familyPickerWasDismissed:(FamilyPickerViewController*)controller { + [self.delegate familyPickerCoordinatorWasDismissed:self]; +} + @end
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator_delegate.h b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator_delegate.h new file mode 100644 index 0000000..111cb52 --- /dev/null +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator_delegate.h
@@ -0,0 +1,19 @@ +// Copyright 2023 The Chromium Authors +// 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_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_COORDINATOR_DELEGATE_H_ +#define IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_COORDINATOR_DELEGATE_H_ + +@class FamilyPickerCoordinator; + +// Delegate for FamilyPickerCoordinator. +@protocol FamilyPickerCoordinatorDelegate + +// Called when the user cancels or dismisses the family recipient selection. +- (void)familyPickerCoordinatorWasDismissed: + (FamilyPickerCoordinator*)coordinator; + +@end + +#endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_COORDINATOR_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.h b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.h index 23c043e..6b7ca10d 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.h +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.h
@@ -8,9 +8,16 @@ #import "ios/chrome/browser/shared/ui/table_view/chrome_table_view_controller.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_consumer.h" +@protocol FamilyPickerViewControllerPresentationDelegate; + // Presents the list of Google Family members of a user. @interface FamilyPickerViewController : ChromeTableViewController <FamilyPickerConsumer> + +// Delegate for handling dismissal of the view. +@property(nonatomic, weak) id<FamilyPickerViewControllerPresentationDelegate> + delegate; + @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.mm b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.mm index 6ca2502..f40daa9 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller.mm
@@ -8,6 +8,7 @@ #import "ios/chrome/browser/shared/ui/table_view/cells/table_view_link_header_footer_item.h" #import "ios/chrome/browser/ui/authentication/authentication_constants.h" #import "ios/chrome/browser/ui/settings/cells/settings_image_detail_text_item.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller_presentation_delegate.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/recipient_info.h" #import "ios/chrome/common/string_util.h" #import "ios/chrome/common/ui/colors/semantic_color_names.h" @@ -77,6 +78,11 @@ } } +- (void)viewDidDisappear:(BOOL)animated { + [self.delegate familyPickerWasDismissed:self]; + [super viewDidDisappear:animated]; +} + #pragma mark - UITableViewDelegate - (void)tableView:(UITableView*)tableView @@ -222,7 +228,7 @@ } - (void)cancelButtonTapped { - // TODO(crbug.com/1463882): Handle cancel tap. + [self.delegate familyPickerWasDismissed:self]; } - (void)shareButtonTapped {
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller_presentation_delegate.h b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller_presentation_delegate.h new file mode 100644 index 0000000..6b5dc12a --- /dev/null +++ b/ios/chrome/browser/ui/settings/password/password_sharing/family_picker_view_controller_presentation_delegate.h
@@ -0,0 +1,18 @@ +// Copyright 2023 The Chromium Authors +// 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_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_VIEW_CONTROLLER_PRESENTATION_DELEGATE_H_ +#define IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_VIEW_CONTROLLER_PRESENTATION_DELEGATE_H_ + +@class FamilyPickerViewController; + +// Delegate for FamilyPickerViewController. +@protocol FamilyPickerViewControllerPresentationDelegate <NSObject> + +// Called when the user clicks cancel button or dismisses the view by swiping. +- (void)familyPickerWasDismissed:(FamilyPickerViewController*)controller; + +@end + +#endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_FAMILY_PICKER_VIEW_CONTROLLER_PRESENTATION_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.h b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.h index f39790b4..2625e73 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.h +++ b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.h
@@ -7,6 +7,8 @@ #import "ios/chrome/browser/shared/coordinator/chrome_coordinator/chrome_coordinator.h" +@protocol PasswordSharingCoordinatorDelegate; + // This is the main coordinator for the password sharing flow initiated from a // password details view. It coordinates the whole flow including fetching // recipient candidates, dispatching child coordinators (e.g. family picker, @@ -16,6 +18,10 @@ - (instancetype)initWithBaseViewController:(UIViewController*)viewController browser:(Browser*)browser NS_DESIGNATED_INITIALIZER; + +// Delegate handling coordinator dismissal. +@property(nonatomic, weak) id<PasswordSharingCoordinatorDelegate> delegate; + @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_PASSWORD_SHARING_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.mm b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.mm index 876a4eb3..dc40814 100644 --- a/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.mm +++ b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator.mm
@@ -11,6 +11,8 @@ #import "ios/chrome/browser/shared/ui/table_view/table_view_utils.h" #import "ios/chrome/browser/signin/identity_manager_factory.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/family_picker_coordinator_delegate.h" +#import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator_delegate.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_mediator.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_mediator_delegate.h" #import "ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_view_controller.h" @@ -19,7 +21,8 @@ using password_manager::FetchFamilyMembersRequestStatus; -@interface PasswordSharingCoordinator () <PasswordSharingMediatorDelegate> +@interface PasswordSharingCoordinator () <FamilyPickerCoordinatorDelegate, + PasswordSharingMediatorDelegate> // The navigation controller displaying the view controller. @property(nonatomic, strong) @@ -81,6 +84,19 @@ self.viewController = nil; self.navigationController = nil; self.mediator = nil; + + [self stopFamilyPickerCoordinator]; +} + +#pragma mark - FamilyPickerCoordinatorDelegate + +- (void)familyPickerCoordinatorWasDismissed: + (FamilyPickerCoordinator*)coordinator { + if (self.familyPickerCoordinator == coordinator) { + [self stopFamilyPickerCoordinator]; + } + + [self.delegate passwordSharingCoordinatorDidRemove:self]; } #pragma mark - PasswordSharingMediatorDelegate @@ -97,6 +113,7 @@ initWithBaseViewController:self.viewController browser:self.browser recipients:familyMembers]; + self.familyPickerCoordinator.delegate = self; [self.familyPickerCoordinator start]; break; case FetchFamilyMembersRequestStatus::kNoFamily: @@ -110,4 +127,12 @@ } } +#pragma mark - Private + +- (void)stopFamilyPickerCoordinator { + [self.familyPickerCoordinator stop]; + self.familyPickerCoordinator.delegate = nil; + self.familyPickerCoordinator = nil; +} + @end
diff --git a/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator_delegate.h b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator_delegate.h new file mode 100644 index 0000000..972fd55 --- /dev/null +++ b/ios/chrome/browser/ui/settings/password/password_sharing/password_sharing_coordinator_delegate.h
@@ -0,0 +1,19 @@ +// Copyright 2023 The Chromium Authors +// 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_SETTINGS_PASSWORD_PASSWORD_SHARING_PASSWORD_SHARING_COORDINATOR_DELEGATE_H_ +#define IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_PASSWORD_SHARING_COORDINATOR_DELEGATE_H_ + +@class PasswordSharingCoordinator; + +// Delegate for PasswordSharingCoordinator. +@protocol PasswordSharingCoordinatorDelegate + +// Called when the view controller was removed from navigation controller. +- (void)passwordSharingCoordinatorDidRemove: + (PasswordSharingCoordinator*)coordinator; + +@end + +#endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_SHARING_PASSWORD_SHARING_COORDINATOR_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm index e59f4ad5..365d09e 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm
@@ -731,14 +731,9 @@ browser:nil]; _toolbarsCoordinator.searchDelegate = self.baseViewController; _toolbarsCoordinator.actionWrangler = self.baseViewController; - _toolbarsCoordinator.delegateWrangler = self.baseViewController; [_toolbarsCoordinator start]; self.baseViewController.topToolbar = _toolbarsCoordinator.topToolbar; self.baseViewController.bottomToolbar = _toolbarsCoordinator.bottomToolbar; - // TODO(crbug.com/1457146): To remove when -updateToolbarButtons function call - // is not needed anymore. - self.baseViewController.toolbarCommandsWrangler = - _toolbarsCoordinator.commandsWrangler; self.regularTabsMediator = [[RegularGridMediator alloc] initWithConsumer:baseViewController.regularTabsConsumer];
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_mediator.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_mediator.h index 7c6950b8..1ebf7e1 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_mediator.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_mediator.h
@@ -34,6 +34,7 @@ @property(nonatomic, weak) id<TabGridPageMutator> incognitoPageMutator; // Mutator for remote Tabs. @property(nonatomic, weak) id<TabGridPageMutator> remotePageMutator; + // Consumer for state changes in tab grid. @property(nonatomic, weak) id<TabGridConsumer> consumer; // Delegate allowing the mediator to update the incognito tab grid.
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.h index 1382af1e..510e4a1 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.h
@@ -12,7 +12,6 @@ #import "ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_consumer.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_paging.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_action_wrangler.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/transitions/legacy_grid_transition_animation_layout_providing.h" @protocol ApplicationCommands; @@ -91,7 +90,6 @@ LegacyGridTransitionAnimationLayoutProviding, TabGridPaging, TabGridToolbarsActionWrangler, - TabGridToolbarsDelegateWrangler, UISearchBarDelegate> @property(nonatomic, weak) id<ApplicationCommands> handler;
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.mm index fea7c7b3..c9ad4f04 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_view_controller.mm
@@ -50,7 +50,6 @@ #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_bottom_toolbar.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_new_tab_button.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_page_control.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_top_toolbar.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/transitions/legacy_grid_transition_layout.h" #import "ios/chrome/common/ui/colors/semantic_color_names.h" @@ -701,12 +700,6 @@ [self updateSelectionModeToolbars]; } -#pragma mark - TabGridToolbarsDelegateWrangler - -- (BOOL)isCurrentGridEmpty { - return [self gridViewControllerForPage:self.currentPage].gridEmpty; -} - #pragma mark - Private // Records the idle page status for the current `currentPage`. @@ -983,7 +976,6 @@ [self.pinnedTabsViewController pinnedTabsAvailable:pinnedTabsAvailable]; } [self updateToolbarsAppearance]; - [self.toolbarCommandsWrangler updateToolbarButtons]; // Make sure the current page becomes the first responder, so that it can // register and handle key commands. [self.currentPageViewController becomeFirstResponder]; @@ -2148,7 +2140,6 @@ crash_keys::SetIncognitoTabCount(count); [self handleTabCountChangeWithTabCount:count]; } - [self.toolbarCommandsWrangler updateToolbarButtons]; } - (void)gridViewController:(GridViewController*)gridViewController
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/BUILD.gn b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/BUILD.gn index bf4b4a9..bf3d031 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/BUILD.gn +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/BUILD.gn
@@ -30,8 +30,6 @@ "tab_grid_page_control.mm", "tab_grid_toolbars_action_wrangler.h", "tab_grid_toolbars_buttons_delegate.h", - "tab_grid_toolbars_commands_wrangler.h", - "tab_grid_toolbars_delegate_wrangler.h", "tab_grid_toolbars_utils.h", "tab_grid_toolbars_utils.mm", "tab_grid_top_toolbar.h",
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h deleted file mode 100644 index ef3756f..0000000 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Chromium Authors -// 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_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_COMMANDS_WRANGLER_H_ -#define IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_COMMANDS_WRANGLER_H_ - -#import <Foundation/Foundation.h> - -// Temporary protocol to send commands to the toolbar. This should be removed in -// a future refactoring and implemented as TabGridToolbarDelegate for the Grid. -// TODO(crbug.com/1456659): Remove this class. -@protocol TabGridToolbarsCommandsWrangler - -- (void)updateToolbarButtons; - -@end - -#endif // IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_COMMANDS_WRANGLER_H_
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.h index dad37e4..23f3ddf 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.h
@@ -10,7 +10,6 @@ @protocol GridToolbarsMutator; @class TabGridBottomToolbar; @protocol TabGridToolbarsActionWrangler; -@protocol TabGridToolbarsDelegateWrangler; @class TabGridTopToolbar; @protocol TabGridToolbarsCommandsWrangler; @@ -27,18 +26,11 @@ // Mutator to handle toolbars modification. @property(nonatomic, readonly, weak) id<GridToolbarsMutator> toolbarsMutator; -// Sends commands to the toolbar. -// TODO(crbug.com/1456659): Should be removed once -updateToolbarButtons -// function is not needed anymore. -@property(nonatomic, readonly, weak) id<TabGridToolbarsCommandsWrangler> - commandsWrangler; - // Wrangler to manage actions/delegate, should be removed in a future // refactoring. Those should be moved to the Grid once the grid has a direct // connection to the toolbars. // TODO(crbug.com/1456659): Remove those. @property(nonatomic, weak) id<TabGridToolbarsActionWrangler> actionWrangler; -@property(nonatomic, weak) id<TabGridToolbarsDelegateWrangler> delegateWrangler; @end
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.mm index fdf0e3ca..3c38165f 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_coordinator.mm
@@ -11,7 +11,6 @@ #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_bottom_toolbar.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_page_control.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_action_wrangler.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_top_toolbar.h" @@ -22,7 +21,6 @@ - (void)start { _mediator = [[TabGridToolbarsMediator alloc] init]; - _mediator.delegateWrangler = self.delegateWrangler; [self setupTopToolbar]; [self setupBottomToolbar]; @@ -39,12 +37,6 @@ return _mediator; } -- (id<TabGridToolbarsCommandsWrangler>)commandsWrangler { - CHECK(_mediator) - << "TabGridToolbarsCoordinator's -start should be called before."; - return _mediator; -} - #pragma mark - Private - (void)setupTopToolbar {
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h deleted file mode 100644 index 90265790..0000000 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2023 The Chromium Authors -// 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_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_DELEGATE_WRANGLER_H_ -#define IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_DELEGATE_WRANGLER_H_ - -#import <Foundation/Foundation.h> - -// Delegate for the toolbars. This is a temporary class that should be removed -// in future refactoring. -// TODO(crbug.com/1456659): Remove this class. -@protocol TabGridToolbarsDelegateWrangler - -// Returns whether the current grid is empty or not (doesn't include inactive -// nor pinned tabs). -- (BOOL)isCurrentGridEmpty; - -@end - -#endif // IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_GRID_TOOLBARS_TAB_GRID_TOOLBARS_DELEGATE_WRANGLER_H_
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h index 7a1bda27..223a943 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h
@@ -8,18 +8,12 @@ #import <Foundation/Foundation.h> #import "ios/chrome/browser/ui/tab_switcher/tab_grid/grid/grid_toolbars_mutator.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h" @class TabGridBottomToolbar; -@protocol TabGridToolbarsDelegateWrangler; @class TabGridTopToolbar; // Mediates between model layer and top and bottom toolbar UI layer. -@interface TabGridToolbarsMediator - : NSObject <GridToolbarsMutator, TabGridToolbarsCommandsWrangler> - -// TODO(crbug.com/1456659): Remove it. -@property(nonatomic, weak) id<TabGridToolbarsDelegateWrangler> delegateWrangler; +@interface TabGridToolbarsMediator : NSObject <GridToolbarsMutator> // The toolbars consumer. // TODO(crbug.com/1456659): Modify it to be consumers instead of being the full
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.mm index 22495de..3947f57 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.mm
@@ -5,12 +5,10 @@ #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_mediator.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_buttons_delegate.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_commands_wrangler.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_configuration.h" #import "ios/chrome/browser/ui/menu/action_factory.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_bottom_toolbar.h" -#import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_toolbars_delegate_wrangler.h" #import "ios/chrome/browser/ui/tab_switcher/tab_grid/toolbars/tab_grid_top_toolbar.h" @implementation TabGridToolbarsMediator { @@ -35,35 +33,6 @@ self.bottomToolbarConsumer.buttonsDelegate = delegate; } -#pragma mark - TabGridToolbarsCommandsWrangler - -// TODO(crbug.com/1457146): To refactor. This function should not be needed as -// `_configuration` should have the info on which button should be added, the -// logic itself will be implemented directly in the grid object itself. -- (void)updateToolbarButtons { - ActionFactory* actionFactory = [[ActionFactory alloc] - initWithScenario:MenuScenarioHistogram::kTabGridEdit]; - __weak id<TabGridToolbarsButtonsDelegate> weakButtonDelegate = - _buttonsDelegate; - NSMutableArray<UIMenuElement*>* menuElements = - [@[ [actionFactory actionToCloseAllTabsWithBlock:^{ - [weakButtonDelegate closeAllButtonTapped:nil]; - }] ] mutableCopy]; - // Disable the "Select All" option from the edit button when there are no tabs - // in the regular tab grid. "Close All" can still be called if there are - // inactive tabs. - BOOL disabledSelectAll = [self.delegateWrangler isCurrentGridEmpty]; - if (!disabledSelectAll) { - [menuElements addObject:[actionFactory actionToSelectTabsWithBlock:^{ - [weakButtonDelegate selectTabsButtonTapped:nil]; - }]]; - } - - UIMenu* menu = [UIMenu menuWithChildren:menuElements]; - [self.topToolbarConsumer setEditButtonMenu:menu]; - [self.bottomToolbarConsumer setEditButtonMenu:menu]; -} - #pragma mark - Private // Helpers to determine which button should be selected between "Edit" or "Undo" @@ -84,8 +53,35 @@ BOOL shouldEnableEditButton = _configuration.closeAllButton || _configuration.selectTabsButton; + if (shouldEnableEditButton) { + [self configureEditButtons]; + } [self.bottomToolbarConsumer setEditButtonEnabled:shouldEnableEditButton]; [self.topToolbarConsumer setEditButtonEnabled:shouldEnableEditButton]; } +// Configures buttons that are available under the edit menu. +- (void)configureEditButtons { + ActionFactory* actionFactory = [[ActionFactory alloc] + initWithScenario:MenuScenarioHistogram::kTabGridEdit]; + __weak id<TabGridToolbarsButtonsDelegate> weakButtonDelegate = + _buttonsDelegate; + NSMutableArray<UIMenuElement*>* menuElements = + [@[ [actionFactory actionToCloseAllTabsWithBlock:^{ + [weakButtonDelegate closeAllButtonTapped:nil]; + }] ] mutableCopy]; + // Disable the "Select All" option from the edit button when there are no tabs + // in the regular tab grid. "Close All" can still be called if there are + // inactive tabs. + if (_configuration.selectTabsButton) { + [menuElements addObject:[actionFactory actionToSelectTabsWithBlock:^{ + [weakButtonDelegate selectTabsButtonTapped:nil]; + }]]; + } + + UIMenu* menu = [UIMenu menuWithChildren:menuElements]; + [self.topToolbarConsumer setEditButtonMenu:menu]; + [self.bottomToolbarConsumer setEditButtonMenu:menu]; +} + @end
diff --git a/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm b/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm index 45c7686..d59f6332 100644 --- a/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm +++ b/ios/chrome/common/ui/promo_style/promo_style_view_controller.mm
@@ -492,15 +492,12 @@ - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; - // Reset `didReachBottom` to make sure that its value is correctly updated - // to reflect the scrolling state when the view reappears and is refreshed - // (e.g., when getting back from a full screen view that was hidding this - // view controller underneath). - // // Set `didReachBottom` to YES when `scrollToEndMandatory` is NO, since the // screen can already be considered as fully scrolled when scrolling to the // end isn't mandatory. - self.didReachBottom = !self.scrollToEndMandatory; + if (!self.scrollToEndMandatory) { + self.didReachBottom = YES; + } // Only add the scroll view delegate after all the view layouts are fully // done.
diff --git a/media/filters/ffmpeg_demuxer_unittest.cc b/media/filters/ffmpeg_demuxer_unittest.cc index e1a193e..a71c678 100644 --- a/media/filters/ffmpeg_demuxer_unittest.cc +++ b/media/filters/ffmpeg_demuxer_unittest.cc
@@ -1348,15 +1348,6 @@ TEST_F(FFmpegDemuxerTest, Read_AC3_Audio) { CreateDemuxer("bear-ac3-only-frag.mp4"); #if BUILDFLAG(ENABLE_PLATFORM_AC3_EAC3_AUDIO) - // AC3 is not supported by default media platform. Embedders who add support - // must declare it via MediaClient. - MockMediaClient media_client; - SetMediaClient(&media_client); - - AudioType ac3_type = {AudioCodec::kAC3}; - EXPECT_CALL(media_client, IsSupportedAudioType(Eq(ac3_type))) - .WillRepeatedly(Return(true)); - InitializeDemuxer(); // Attempt a read from the audio stream and run the message loop until done. @@ -1365,8 +1356,6 @@ // Read the first two frames and check that we are getting expected data Read(audio, FROM_HERE, 834, 0, true); Read(audio, FROM_HERE, 836, 34830, true); - - SetMediaClient(nullptr); #else InitializeDemuxerAndExpectPipelineStatus(DEMUXER_ERROR_NO_SUPPORTED_STREAMS); #endif @@ -1375,15 +1364,6 @@ TEST_F(FFmpegDemuxerTest, Read_EAC3_Audio) { CreateDemuxer("bear-eac3-only-frag.mp4"); #if BUILDFLAG(ENABLE_PLATFORM_AC3_EAC3_AUDIO) - // EAC3 is not supported by default media platform. Embedders who add support - // must declare it via MediaClient. - MockMediaClient media_client; - SetMediaClient(&media_client); - - AudioType eac3_type = {AudioCodec::kEAC3}; - EXPECT_CALL(media_client, IsSupportedAudioType(Eq(eac3_type))) - .WillRepeatedly(Return(true)); - InitializeDemuxer(); // Attempt a read from the audio stream and run the message loop until done. @@ -1392,8 +1372,6 @@ // Read the first two frames and check that we are getting expected data Read(audio, FROM_HERE, 870, 0, true); Read(audio, FROM_HERE, 872, 34830, true); - - SetMediaClient(nullptr); #else InitializeDemuxerAndExpectPipelineStatus(DEMUXER_ERROR_NO_SUPPORTED_STREAMS); #endif
diff --git a/services/accessibility/android/ax_tree_source_android.h b/services/accessibility/android/ax_tree_source_android.h index 43e64ec..de3a897 100644 --- a/services/accessibility/android/ax_tree_source_android.h +++ b/services/accessibility/android/ax_tree_source_android.h
@@ -10,7 +10,6 @@ #include <string> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/containers/flat_map.h" #include "base/memory/raw_ptr.h" #include "extensions/browser/api/automation_internal/automation_event_router.h"
diff --git a/services/accessibility/features/devtools/os_devtools_unittest.cc b/services/accessibility/features/devtools/os_devtools_unittest.cc index 8a5afd1..917e261d 100644 --- a/services/accessibility/features/devtools/os_devtools_unittest.cc +++ b/services/accessibility/features/devtools/os_devtools_unittest.cc
@@ -5,11 +5,11 @@ #include <memory> #include <string> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" #include "base/functional/callback_forward.h" #include "base/json/json_reader.h" #include "base/location.h" +#include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h"
diff --git a/services/media_session/public/cpp/test/mock_media_session.cc b/services/media_session/public/cpp/test/mock_media_session.cc index 66b020e..4f9ba82 100644 --- a/services/media_session/public/cpp/test/mock_media_session.cc +++ b/services/media_session/public/cpp/test/mock_media_session.cc
@@ -67,6 +67,10 @@ expected_controllable_ == session_info_->is_controllable) { run_loop_->Quit(); expected_controllable_.reset(); + } else if (expected_hide_metadata_.has_value() && + expected_hide_metadata_ == session_info_->hide_metadata) { + run_loop_->Quit(); + expected_hide_metadata_.reset(); } else { if (wanted_state_ == session_info_->state || session_info_->playback_state == wanted_playback_state_ || @@ -197,6 +201,16 @@ StartWaiting(); } +void MockMediaSessionMojoObserver::WaitForExpectedHideMetadata( + bool hide_metadata) { + if (session_info_ && session_info_->hide_metadata == hide_metadata) { + return; + } + + expected_hide_metadata_ = hide_metadata; + StartWaiting(); +} + void MockMediaSessionMojoObserver::WaitForEmptyMetadata() { if (session_metadata_.has_value() || !session_metadata_->has_value()) return;
diff --git a/services/media_session/public/cpp/test/mock_media_session.h b/services/media_session/public/cpp/test/mock_media_session.h index 3b2675d..da4b1da 100644 --- a/services/media_session/public/cpp/test/mock_media_session.h +++ b/services/media_session/public/cpp/test/mock_media_session.h
@@ -59,6 +59,7 @@ const std::vector<mojom::MediaAudioVideoState>& wanted_states); void WaitForControllable(bool is_controllable); + void WaitForExpectedHideMetadata(bool hide_metadata); void WaitForEmptyMetadata(); void WaitForExpectedMetadata(const MediaMetadata& metadata); @@ -114,6 +115,7 @@ absl::optional<MediaMetadata> expected_metadata_; absl::optional<std::set<mojom::MediaSessionAction>> expected_actions_; absl::optional<bool> expected_controllable_; + absl::optional<bool> expected_hide_metadata_; absl::optional< std::pair<mojom::MediaSessionImageType, std::vector<MediaImage>>> expected_images_of_type_;
diff --git a/services/network/network_service_proxy_allow_list.cc b/services/network/network_service_proxy_allow_list.cc index d4bea9b..92c3e90 100644 --- a/services/network/network_service_proxy_allow_list.cc +++ b/services/network/network_service_proxy_allow_list.cc
@@ -9,18 +9,12 @@ #include "base/command_line.h" #include "base/strings/strcat.h" #include "components/privacy_sandbox/masked_domain_list/masked_domain_list.pb.h" +#include "net/base/schemeful_site.h" #include "net/proxy_resolution/proxy_bypass_rules.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/network_switches.h" namespace network { -namespace { - -std::string NormalizeHost(std::string s) { - return s.substr(0, 4) == "www." ? s.substr(4) : s; -} - -} // namespace NetworkServiceProxyAllowList::NetworkServiceProxyAllowList() { custom_proxy_config_ = network::mojom::CustomProxyConfig::New(); @@ -125,18 +119,19 @@ return false; } - std::string resource_host = NormalizeHost(request_url.host()); + net::SchemefulSite request_site(request_url); + net::SchemefulSite top_site(top_frame_url); - // Same site requests should not be proxied. - if (resource_host == NormalizeHost(top_frame_url.host())) { + // First-party requests should not be proxied. + if (request_site == top_site) { return false; } - auto resource_host_suffix = PartitionMapKey(resource_host); + auto partition_map_key = PartitionMapKey(request_url.host()); - if (allow_list_with_bypass_map_.contains(resource_host_suffix)) { + if (allow_list_with_bypass_map_.contains(partition_map_key)) { for (const auto& [rule, bypass_rules] : - allow_list_with_bypass_map_.at(resource_host_suffix)) { + allow_list_with_bypass_map_.at(partition_map_key)) { auto result = rule->Evaluate(request_url); if (result == net::SchemeHostPortMatcherResult::kInclude) { return bypass_rules.Matches(top_frame_url, true);
diff --git a/services/network/network_service_proxy_allow_list_unittest.cc b/services/network/network_service_proxy_allow_list_unittest.cc index fa4c949..e4c9bcf2 100644 --- a/services/network/network_service_proxy_allow_list_unittest.cc +++ b/services/network/network_service_proxy_allow_list_unittest.cc
@@ -148,13 +148,15 @@ MatchTest{"1PPropHost", "bbco-pb.co.uk", "bbco-pb.co.uk", false}, MatchTest{"1POtherHost", "somehost.com", "somehost.com", false}, - // "First-party" is defined by having the same hostname, possibly with - // a "www" prefix. - // TODO: Use SchemefulSite to compare instead of stripping `www.`. + // "First-party" is defined as schemefully same-site. MatchTest{"1PSameSiteOther1", "www.somehost.com", "somehost.com", false}, MatchTest{"1PSameSiteOther2", "somehost.com", "www.somehost.com", false}, MatchTest{"1PSameSiteRsrc1", "www.acme-ra.com", "acme-ra.com", false}, MatchTest{"1PSameSiteRsrc2", "acme-ra.com", "www.acme-ra.com", false}, + MatchTest{"1PSameSiteRsrcSub1", "sub.sub.acme-ra.com", "acme-ra.com", + false}, + MatchTest{"1PSameSiteRsrcSub2", "acme-ra.com", "sub.sub.acme-ra.com", + false}, MatchTest{"1PSameSiteProp1", "www.bbco-pb.co.uk", "bbco-pb.co.uk", false}, MatchTest{"1PSameSiteProp2", "bbco-pb.co.uk", "www.bbco-pb.co.uk", false},
diff --git a/testing/buildbot/filters/ozone-linux.interactive_ui_tests_wayland.filter b/testing/buildbot/filters/ozone-linux.interactive_ui_tests_wayland.filter index 69ceeec1..697072a 100644 --- a/testing/buildbot/filters/ozone-linux.interactive_ui_tests_wayland.filter +++ b/testing/buildbot/filters/ozone-linux.interactive_ui_tests_wayland.filter
@@ -1,6 +1,12 @@ # TODO(crbug.com/1195712): implement the feature for Wayland. -GlobalCommandsApiTest.GlobalCommand +# TODO(crbug.com/1474372): This test relies on popups being destroyed when the user clicks on the +# desktop. This currently only works in Chromium when passing `--use-wayland-explicit-grab` (see +# crbug.com/1220274 for more context). Re-enable the test once the default popup dismissal behaviour +# is fixed. +-BookmarkBarViewTest2.HideOnDesktopClick + # Failing interactive ui tests -BookmarkBarViewTest12.CloseWithModalDialog -BookmarkBarViewTest13.ClickOnContextMenuSeparator
diff --git a/third_party/android_deps/libs/com_google_errorprone_error_prone_check_api/README.chromium b/third_party/android_deps/libs/com_google_errorprone_error_prone_check_api/README.chromium index 5618cd2..4c7f7e5 100644 --- a/third_party/android_deps/libs/com_google_errorprone_error_prone_check_api/README.chromium +++ b/third_party/android_deps/libs/com_google_errorprone_error_prone_check_api/README.chromium
@@ -1,6 +1,6 @@ Name: error-prone check api Short Name: error_prone_check_api -URL: +URL: https://errorprone.info/ Version: 2.11.0 License: Apache 2.0 License File: LICENSE
diff --git a/third_party/android_deps/libs/com_google_errorprone_error_prone_core/README.chromium b/third_party/android_deps/libs/com_google_errorprone_error_prone_core/README.chromium index 8957672..0879b8d 100644 --- a/third_party/android_deps/libs/com_google_errorprone_error_prone_core/README.chromium +++ b/third_party/android_deps/libs/com_google_errorprone_error_prone_core/README.chromium
@@ -1,6 +1,6 @@ Name: error-prone library Short Name: error_prone_core -URL: +URL: https://errorprone.info/ Version: 2.11.0 License: Apache 2.0 License File: LICENSE
diff --git a/third_party/android_deps/libs/com_google_errorprone_error_prone_type_annotations/README.chromium b/third_party/android_deps/libs/com_google_errorprone_error_prone_type_annotations/README.chromium index 3158d76..d2327cd 100644 --- a/third_party/android_deps/libs/com_google_errorprone_error_prone_type_annotations/README.chromium +++ b/third_party/android_deps/libs/com_google_errorprone_error_prone_type_annotations/README.chromium
@@ -1,6 +1,6 @@ Name: error-prone type annotations Short Name: error_prone_type_annotations -URL: +URL: https://errorprone.info/ Version: 2.11.0 License: Apache 2.0 License File: LICENSE
diff --git a/third_party/aosp_dalvik/README.chromium b/third_party/aosp_dalvik/README.chromium index 14c88f63..71f438f 100644 --- a/third_party/aosp_dalvik/README.chromium +++ b/third_party/aosp_dalvik/README.chromium
@@ -1,6 +1,6 @@ Name: platform/dalvik dx Short Name: dalvik-dx -URL: +URL: https://android.googlesource.com/platform/dalvik/+/main/dx/README.txt Version: 13.0.0_r24 License: Apache License Version 2.0 License File: LICENSE
diff --git a/third_party/blink/common/service_worker/service_worker_router_rule.cc b/third_party/blink/common/service_worker/service_worker_router_rule.cc index c7e2f8f..02efb93 100644 --- a/third_party/blink/common/service_worker/service_worker_router_rule.cc +++ b/third_party/blink/common/service_worker/service_worker_router_rule.cc
@@ -29,6 +29,11 @@ } } +bool ServiceWorkerRouterCacheSource::operator==( + const ServiceWorkerRouterCacheSource& other) const { + return cache_name == other.cache_name; +} + bool ServiceWorkerRouterSource::operator==( const ServiceWorkerRouterSource& other) const { if (type != other.type) { @@ -41,6 +46,8 @@ return race_source == other.race_source; case SourceType::kFetchEvent: return fetch_event_source == other.fetch_event_source; + case SourceType::kCache: + return cache_source == other.cache_source; } }
diff --git a/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits.cc b/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits.cc index dd2308c..dfcf1d6 100644 --- a/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits.cc +++ b/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits.cc
@@ -77,6 +77,16 @@ return false; } +bool StructTraits<blink::mojom::ServiceWorkerRouterCacheSourceDataView, + blink::ServiceWorkerRouterCacheSource>:: + Read(blink::mojom::ServiceWorkerRouterCacheSourceDataView data, + blink::ServiceWorkerRouterCacheSource* out) { + if (!data.ReadCacheName(&out->cache_name)) { + return false; + } + return true; +} + blink::mojom::ServiceWorkerRouterSourceDataView::Tag UnionTraits<blink::mojom::ServiceWorkerRouterSourceDataView, blink::ServiceWorkerRouterSource>:: @@ -88,6 +98,8 @@ return blink::mojom::ServiceWorkerRouterSource::Tag::kRaceSource; case blink::ServiceWorkerRouterSource::SourceType::kFetchEvent: return blink::mojom::ServiceWorkerRouterSource::Tag::kFetchEventSource; + case blink::ServiceWorkerRouterSource::SourceType::kCache: + return blink::mojom::ServiceWorkerRouterSource::Tag::kCacheSource; } } @@ -108,6 +120,12 @@ out->type = blink::ServiceWorkerRouterSource::SourceType::kFetchEvent; out->fetch_event_source.emplace(); return true; + case blink::mojom::ServiceWorkerRouterSource::Tag::kCacheSource: + out->type = blink::ServiceWorkerRouterSource::SourceType::kCache; + if (!data.ReadCacheSource(&out->cache_source)) { + return false; + } + return true; } return false; }
diff --git a/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits_unittest.cc b/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits_unittest.cc index c0f7daa..f41bac9 100644 --- a/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits_unittest.cc +++ b/third_party/blink/common/service_worker/service_worker_router_rule_mojom_traits_unittest.cc
@@ -90,6 +90,20 @@ source.fetch_event_source.emplace(); rule.sources.push_back(source); } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + source.cache_source.emplace(); + rule.sources.push_back(source); + } + { + blink::ServiceWorkerRouterSource source; + source.type = blink::ServiceWorkerRouterSource::SourceType::kCache; + blink::ServiceWorkerRouterCacheSource cache_source; + cache_source.cache_name = "example cache name"; + source.cache_source = cache_source; + rule.sources.push_back(source); + } rules.rules.push_back(rule); } TestRoundTrip(rules);
diff --git a/third_party/blink/public/common/service_worker/service_worker_router_rule.h b/third_party/blink/public/common/service_worker/service_worker_router_rule.h index 3f9e805..5a6ea7d 100644 --- a/third_party/blink/public/common/service_worker/service_worker_router_rule.h +++ b/third_party/blink/public/common/service_worker/service_worker_router_rule.h
@@ -101,6 +101,16 @@ } }; +// Cache source structure. +struct BLINK_COMMON_EXPORT ServiceWorkerRouterCacheSource { + // A name of the Cache object. + // If the field is not set, any of the Cache objects that the CacheStorage + // tracks are used for matching as if CacheStorage.match(). + absl::optional<std::string> cache_name; + + bool operator==(const ServiceWorkerRouterCacheSource& other) const; +}; + // This represents a source of the router rule. // TODO(crbug.com/1371756): implement other sources in the proposal. struct BLINK_COMMON_EXPORT ServiceWorkerRouterSource { @@ -114,14 +124,17 @@ kRace = 1, // Fetch Event is used as a source. kFetchEvent = 2, + // Cache is used as a source. + kCache = 3, - kMaxValue = kFetchEvent, + kMaxValue = kCache, }; SourceType type; absl::optional<ServiceWorkerRouterNetworkSource> network_source; absl::optional<ServiceWorkerRouterRaceSource> race_source; absl::optional<ServiceWorkerRouterFetchEventSource> fetch_event_source; + absl::optional<ServiceWorkerRouterCacheSource> cache_source; bool operator==(const ServiceWorkerRouterSource& other) const; };
diff --git a/third_party/blink/public/common/service_worker/service_worker_router_rule_mojom_traits.h b/third_party/blink/public/common/service_worker/service_worker_router_rule_mojom_traits.h index 54c116c..71a99e5 100644 --- a/third_party/blink/public/common/service_worker/service_worker_router_rule_mojom_traits.h +++ b/third_party/blink/public/common/service_worker/service_worker_router_rule_mojom_traits.h
@@ -163,6 +163,19 @@ template <> struct BLINK_COMMON_EXPORT + StructTraits<blink::mojom::ServiceWorkerRouterCacheSourceDataView, + blink::ServiceWorkerRouterCacheSource> { + static const absl::optional<std::string>& cache_name( + const blink::ServiceWorkerRouterCacheSource& data) { + return data.cache_name; + } + + static bool Read(blink::mojom::ServiceWorkerRouterCacheSourceDataView data, + blink::ServiceWorkerRouterCacheSource* out); +}; + +template <> +struct BLINK_COMMON_EXPORT UnionTraits<blink::mojom::ServiceWorkerRouterSourceDataView, blink::ServiceWorkerRouterSource> { static blink::mojom::ServiceWorkerRouterSourceDataView::Tag GetTag( @@ -183,6 +196,11 @@ return *data.fetch_event_source; } + static const blink::ServiceWorkerRouterCacheSource& cache_source( + const blink::ServiceWorkerRouterSource& data) { + return *data.cache_source; + } + static bool Read(blink::mojom::ServiceWorkerRouterSourceDataView data, blink::ServiceWorkerRouterSource* out); };
diff --git a/third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom b/third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom index c40f2e2..971811c84 100644 --- a/third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom +++ b/third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom
@@ -5,4 +5,32 @@ module blink.mojom; // ChromeOS Diagnostics API. -interface CrosDiagnostics {}; +// +// Prototype API used to retrieve diagnostics information from the system, e.g. +// CPU/memory usage statistics and OS information. +// +// This interface is used in blink by blink::CrosDiagnostics which is enabled +// when `BlinkExtensionChromeOSDiagnostics` is enabled. On the browser side this +// interface is implemented by CrosDiagnosticsImpl whose lifetime is tied to the +// document. There's a 1:1 relationship between CrosDiagnosticsImpl and the +// document. This interface is only bound if `CrosDiagnosticsApi` is enabled. +interface CrosDiagnostics { + // Retrieves diagnostics information of the CPU. + // + // The response: + // * |cpu_info| - diagnostics information of the CPU, e.g. model name, utilization and temperature. + GetCpuInfo() => (CrosCpuInfo cpu_info); +}; + +// Diagnostics information of the CPU, e.g. model name, utilization and +// temperature. +struct CrosCpuInfo { + // The architecture of the CPU, e.g. "x86", "x86_64", "ARM", "ARM_64". + string architecture_name; + + // The model name of the CPU, e.g. "AMD Ryzen 7 7840U", "Intel Core i7-1370P". + string model_name; + + // The number of logical processors available. + int32 num_of_processors; +};
diff --git a/third_party/blink/public/mojom/service_worker/service_worker_router_rule.mojom b/third_party/blink/public/mojom/service_worker/service_worker_router_rule.mojom index 9216052f..ba90475 100644 --- a/third_party/blink/public/mojom/service_worker/service_worker_router_rule.mojom +++ b/third_party/blink/public/mojom/service_worker/service_worker_router_rule.mojom
@@ -84,6 +84,15 @@ struct ServiceWorkerRouterFetchEventSource { }; +// This source is used when the response should be retrieved from the cache +// storage. +// https://github.com/yoshisatoyanagisawa/service-worker-static-routing-api +struct ServiceWorkerRouterCacheSource { + // The Cache object's name to be used. Unspecified means looking up from + // all Cache objects in the Cache Storage. + string? cache_name; +}; + // This represents a source of the router rule. // https://github.com/yoshisatoyanagisawa/service-worker-static-routing-api // TODO(crbug.com/1371756): implement other sources in the full picture. @@ -91,6 +100,7 @@ ServiceWorkerRouterNetworkSource network_source; ServiceWorkerRouterRaceSource race_source; ServiceWorkerRouterFetchEventSource fetch_event_source; + ServiceWorkerRouterCacheSource cache_source; }; // This represents a ServiceWorker static routing API's router rule.
diff --git a/third_party/blink/renderer/bindings/generated_in_extensions_chromeos.gni b/third_party/blink/renderer/bindings/generated_in_extensions_chromeos.gni index 196fd87..0ec14d4 100644 --- a/third_party/blink/renderer/bindings/generated_in_extensions_chromeos.gni +++ b/third_party/blink/renderer/bindings/generated_in_extensions_chromeos.gni
@@ -7,6 +7,8 @@ generated_dictionary_sources_in_extensions_chromeos = [ "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_accelerator_event_init.cc", "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_accelerator_event_init.h", + "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_cpu_info.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_cpu_info.h", "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_window_event_init.cc", "$root_gen_dir/third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_window_event_init.h", ]
diff --git a/third_party/blink/renderer/bindings/idl_in_extensions_chromeos.gni b/third_party/blink/renderer/bindings/idl_in_extensions_chromeos.gni index 83cf9cb..9250f770 100644 --- a/third_party/blink/renderer/bindings/idl_in_extensions_chromeos.gni +++ b/third_party/blink/renderer/bindings/idl_in_extensions_chromeos.gni
@@ -7,6 +7,7 @@ static_idl_files_in_extensions_chromeos = [ "//third_party/blink/renderer/extensions/chromeos/chromeos.idl", "//third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.idl", + "//third_party/blink/renderer/extensions/chromeos/diagnostics/cros_cpu_info.idl", "//third_party/blink/renderer/extensions/chromeos/system_extensions/hid/cros_hid.idl", "//third_party/blink/renderer/extensions/chromeos/system_extensions/managed_device_health_services/telemetry/cros_telemetry.idl", "//third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_accelerator_event.idl",
diff --git a/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.cc b/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.cc index 57abd40..47c87bc 100644 --- a/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.cc +++ b/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.cc
@@ -27,10 +27,10 @@ } // namespace // static -UserLevelMemoryPressureSignalGenerator& +UserLevelMemoryPressureSignalGenerator* UserLevelMemoryPressureSignalGenerator::Instance() { DCHECK(g_instance); - return *g_instance; + return g_instance; } // static @@ -194,8 +194,17 @@ } void RequestUserLevelMemoryPressureSignal() { - UserLevelMemoryPressureSignalGenerator::Instance() - .RequestMemoryPressureSignal(); + // TODO(crbug.com/1473814): AndroidWebView creates renderer processes + // without appending extra commandline switches, + // c.f. ChromeContentBrowserClient::AppendExtraCommandLineSwitches(), + // So renderer processes do not initialize user-level memory pressure + // siginal generators but the browser code expects they have already been + // initialized. So when requesting memory pressure signals, g_instance is + // nullptr and g_instance->clock_ will crash. + if (UserLevelMemoryPressureSignalGenerator* generator = + UserLevelMemoryPressureSignalGenerator::Instance()) { + generator->RequestMemoryPressureSignal(); + } } } // namespace blink
diff --git a/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.h b/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.h index f6b7a26..f8b2f742 100644 --- a/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.h +++ b/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.h
@@ -37,7 +37,7 @@ USING_FAST_MALLOC(UserLevelMemoryPressureSignalGenerator); public: - static UserLevelMemoryPressureSignalGenerator& Instance(); + static UserLevelMemoryPressureSignalGenerator* Instance(); // Returns the shared instance. static void Initialize(
diff --git a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_cpu_info.idl b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_cpu_info.idl new file mode 100644 index 0000000..f7f993a --- /dev/null +++ b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_cpu_info.idl
@@ -0,0 +1,16 @@ +// Copyright 2023 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. + +// Diagnostics information of the CPU, e.g. model name, utilization and +// temperature. +dictionary CrosCpuInfo { + // The architecture of the CPU, e.g. "x86", "x86_64", "ARM", "ARM_64". + DOMString architectureName; + + // The model name of the CPU, e.g. "AMD Ryzen 7 7840U", "Intel Core i7-1370P". + DOMString modelName; + + // The number of logical processors available. + long numOfProcessors; +};
diff --git a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.cc b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.cc index 3445df0..d2bff111 100644 --- a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.cc +++ b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.cc
@@ -6,7 +6,9 @@ #include "third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/extensions_chromeos/v8/v8_cros_cpu_info.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" namespace blink { @@ -28,13 +30,6 @@ ExecutionContextClient(&execution_context), cros_diagnostics_(&execution_context) {} -void CrosDiagnostics::Trace(Visitor* visitor) const { - visitor->Trace(cros_diagnostics_); - Supplement<ExecutionContext>::Trace(visitor); - ExecutionContextClient::Trace(visitor); - ScriptWrappable::Trace(visitor); -} - mojom::blink::CrosDiagnostics* CrosDiagnostics::GetCrosDiagnosticsOrNull() { auto* execution_context = GetExecutionContext(); if (!execution_context) { @@ -50,4 +45,36 @@ return cros_diagnostics_.get(); } +void CrosDiagnostics::Trace(Visitor* visitor) const { + visitor->Trace(cros_diagnostics_); + Supplement<ExecutionContext>::Trace(visitor); + ExecutionContextClient::Trace(visitor); + ScriptWrappable::Trace(visitor); +} + +ScriptPromise CrosDiagnostics::getCpuInfo(ScriptState* script_state) { + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + auto* cros_diagnostics = GetCrosDiagnosticsOrNull(); + + if (cros_diagnostics) { + cros_diagnostics->GetCpuInfo( + WTF::BindOnce(&CrosDiagnostics::OnGetCpuInfoResponse, + WrapPersistent(this), WrapPersistent(resolver))); + } + + return resolver->Promise(); +} + +void CrosDiagnostics::OnGetCpuInfoResponse( + ScriptPromiseResolver* resolver, + mojom::blink::CrosCpuInfoPtr cpu_info_mojom) { + auto* cpu_info_blink = MakeGarbageCollected<CrosCpuInfo>(); + + cpu_info_blink->setArchitectureName(cpu_info_mojom->architecture_name); + cpu_info_blink->setModelName(cpu_info_mojom->model_name); + cpu_info_blink->setNumOfProcessors(cpu_info_mojom->num_of_processors); + + resolver->Resolve(cpu_info_blink); +} + } // namespace blink
diff --git a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.h b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.h index dd98bdd..c430840 100644 --- a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.h +++ b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_EXTENSIONS_CHROMEOS_DIAGNOSTICS_CROS_DIAGNOSTICS_H_ #include "third_party/blink/public/mojom/chromeos/diagnostics/cros_diagnostics.mojom-blink.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" @@ -13,6 +14,8 @@ namespace blink { +class ScriptPromiseResolver; + class CrosDiagnostics : public ScriptWrappable, public Supplement<ExecutionContext>, public ExecutionContextClient { @@ -25,6 +28,8 @@ explicit CrosDiagnostics(ExecutionContext&); + ScriptPromise getCpuInfo(ScriptState* script_state); + void Trace(Visitor*) const override; private: @@ -32,6 +37,9 @@ // the ExecutionContext has been deleted. mojom::blink::CrosDiagnostics* GetCrosDiagnosticsOrNull(); + void OnGetCpuInfoResponse(ScriptPromiseResolver* resolver, + mojom::blink::CrosCpuInfoPtr cpu_info_mojom); + HeapMojoRemote<mojom::blink::CrosDiagnostics> cros_diagnostics_; };
diff --git a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.idl b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.idl index 7612986..836cf00 100644 --- a/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.idl +++ b/third_party/blink/renderer/extensions/chromeos/diagnostics/cros_diagnostics.idl
@@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// ChromeOS Diagnostics API. +// // Prototype API used to retrieve diagnostics information from the system, e.g. // CPU/memory usage statistics and OS information. -// Available to window and service worker LaCrOS main frames when enabled. -interface CrosDiagnostics {}; +// +// Available to window LaCrOS main frames when enabled. +interface CrosDiagnostics { + // Retrieves diagnostics information of the CPU. + // + // Returns a promise containing diagnostics information + // of the CPU, e.g. model name, utilization and temperature. + [CallWith=ScriptState] Promise<CrosCpuInfo> getCpuInfo(); +};
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc index 91b0e61e..e022eee 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
@@ -212,7 +212,7 @@ } RTCDataChannel::Observer::~Observer() { - DCHECK(!blink_channel_) << "Reference to blink channel hasn't been released."; + CHECK(!is_registered()) << "Reference to blink channel hasn't been released."; } const rtc::scoped_refptr<webrtc::DataChannelInterface>& @@ -220,6 +220,11 @@ return webrtc_channel_; } +bool RTCDataChannel::Observer::is_registered() const { + DCHECK(main_thread_->BelongsToCurrentThread()); + return blink_channel_ != nullptr; +} + void RTCDataChannel::Observer::Unregister() { DCHECK(main_thread_->BelongsToCurrentThread()); webrtc_channel_->UnregisterObserver(); @@ -303,7 +308,10 @@ IncrementCounters(*channel().get()); } -RTCDataChannel::~RTCDataChannel() = default; +RTCDataChannel::~RTCDataChannel() { + // `Dispose()` must have been called to clear up webrtc references. + CHECK(!observer_->is_registered()); +} String RTCDataChannel::label() const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h index 6b5f040..50aae72 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
@@ -132,6 +132,11 @@ // the signaling thread (safe because the call is synchronous). const rtc::scoped_refptr<webrtc::DataChannelInterface>& channel() const; + // Returns true if a valid `blink_channel_` is held and `Unregister()` + // hasn't been called. A return value of false indicates that the `Observer` + // can be safely discarded. + bool is_registered() const; + // Clears the |blink_channel_| reference, disassociates this observer from // the |webrtc_channel_| and releases the |webrtc_channel_| pointer. Must be // called on the main thread.
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 36a1e50..edf04ec0 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1037,7 +1037,7 @@ { // https://drafts.csswg.org/css-cascade-6/#scoped-styles name: "CSSScope", - status: "experimental", + status: "stable", }, { // https://drafts.csswg.org/css-scroll-snap-2
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 0a91a04..8131bb54 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -657,6 +657,9 @@ # Temporarily disabled to unblock https://crrev.com/c/4417276 crbug.com/1427397 http/tests/devtools/elements/styles-4/style-update-during-selector-edit.js [ Failure Pass ] +# Temporarily disabled to unblock https://crrev.com/c/4793886 +crbug.com/1473886 http/tests/devtools/profiler/agents-disabled-check.js [ Failure Pass ] + # Subpixel rounding differences that are incorrect. crbug.com/997202 compositing/overflow/scaled-overflow.html [ Failure ] # Flaky subpixel AA difference (not necessarily incorrect, but flaky) @@ -4237,8 +4240,9 @@ # Sheriff 2019-09-30 crbug.com/1003715 [ Win ] http/tests/notifications/serviceworker-notification-properties.html [ Failure Pass Timeout ] - - +# Temporarily disabled to land https://crrev.com/c/4797648 +crbug.com/1468875 http/tests/devtools/network/network-search.js [ Failure Pass ] +crbug.com/1468875 http/tests/devtools/search/sources-search-scope-in-files.js [ Failure Pass ] # Sheriff 2019-10-18 crbug.com/1015975 media/video-currentTime.html [ Failure Pass ]
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 eea5adf..d79c9439 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
@@ -212094,7 +212094,7 @@ ] ], "transform3d-preserve3d-001.html": [ - "dbebc64139a27824ab212316015c52928db2df53", + "9459381760a51d3266a8fff068261dbf527e54e0", [ null, [ @@ -279161,16 +279161,6 @@ } }, "support": { - ".cache": { - "gitignore2.json": [ - "64c5f3a556619f10708e0382419cdb71d0512bf7", - [] - ], - "mtime.json": [ - "077553c15237e27f4bdcbb16c556f2448e0fb4c8", - [] - ] - }, ".gitignore": [ "d93e645d547894b50149d3726de2654957b6e06f", [] @@ -350054,7 +350044,7 @@ [] ], "transform3d-preserve3d-001-ref.html": [ - "383bc7a63eb55053bf17948c1c973d80f8f2d352", + "63dce0180ae19554c820b05aa23b09e87908ce29", [] ], "transform3d-preserve3d-012.html.ini": [ @@ -405960,7 +405950,7 @@ [] ], "test-helper.js": [ - "0737f719bfbabea673e279f29697aca9181d2daa", + "20729c98a4baa9a2c55e3152654fdfad30315085", [] ] }, @@ -473882,6 +473872,13 @@ {} ] ], + "content-visibility-086.html": [ + "51c1586098e4a1c54aa7095a9d7d70c2107c5f47", + [ + null, + {} + ] + ], "content-visibility-auto-first-observation-immediate.html": [ "5a177d6ea98f15315db595d6bc7b0e8f2da5ac4e", [ @@ -476569,7 +476566,7 @@ ] ], "percentage-heights-013.html": [ - "2410e0a5fdff5861f8dbd21e65137c50943cc9c8", + "f39e83c19f9597963c4cec95ae0c2adc5260767d", [ null, {} @@ -605928,6 +605925,15 @@ } ] ], + "loaf-callback-after-promise.html": [ + "f7048072fa84dd52a10858141ba400c12f0917c0", + [ + null, + { + "timeout": "long" + } + ] + ], "loaf-desired-exec-time.html": [ "dd350078b6024d41e25e663acbfa6a2b03aea789", [ @@ -616630,7 +616636,7 @@ ], "not-restored-reasons": { "performance-navigation-timing-attributes.tentative.window.js": [ - "95ca3dd6b4daaf177e716d74b95b27064637bc6f", + "b0afb5c018a7ceb63a0e4ed16610aada3db36537", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-attributes.tentative.window.html", { @@ -616677,7 +616683,7 @@ ] ], "performance-navigation-timing-bfcache-reasons-stay.tentative.window.js": [ - "36c1b92dca43b1d6ebff2ea0804ea57f7f61d009", + "f053efdd8afbc9be792bc15db5e33b432996454f", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-bfcache-reasons-stay.tentative.window.html", { @@ -616767,7 +616773,7 @@ ] ], "performance-navigation-timing-cross-origin-bfcache.tentative.window.js": [ - "80adec007a2e4a80daf33e2752fb2e04ea902668", + "851dd8c650833a49f58610d875edfb1cf556f925", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-cross-origin-bfcache.tentative.window.html", { @@ -616814,7 +616820,7 @@ ] ], "performance-navigation-timing-not-bfcached.tentative.window.js": [ - "3afce4b97557bc9ba0c2309306403556f38fed28", + "fbf22fa5b76df626dff4db7cc2fb53c330ced1b6", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-not-bfcached.tentative.window.html", { @@ -616908,7 +616914,7 @@ ] ], "performance-navigation-timing-reload.tentative.window.js": [ - "3e94c3a4487bd7bbbf02925f35e2520b816e0503", + "b51d81d047bcedc4ceb8ec53dd7da1edf58f9d57", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-reload.tentative.window.html", { @@ -616955,7 +616961,7 @@ ] ], "performance-navigation-timing-same-origin-bfcache.tentative.window.js": [ - "26fea56bbbc00bc92c8e11f0b82000f5911240e9", + "a83db30a4148de8f14a9f3fa73afbcfa05dc662b", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-bfcache.tentative.window.html", { @@ -617002,7 +617008,7 @@ ] ], "performance-navigation-timing-same-origin-replace.tentative.window.js": [ - "e1bfafd77988245bdd50effbb1ddf712034efb49", + "bc05d39f2ef5a670c3f953fd8a6f0319df6d7797", [ "performance-timeline/not-restored-reasons/performance-navigation-timing-same-origin-replace.tentative.window.html", {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/content-visibility/content-visibility-086.html b/third_party/blink/web_tests/external/wpt/css/css-contain/content-visibility/content-visibility-086.html new file mode 100644 index 0000000..51c1586 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/content-visibility/content-visibility-086.html
@@ -0,0 +1,43 @@ +<!doctype HTML> +<html> +<meta charset="utf8"> +<title>Content Visibility: innerText</title> +<link rel="author" title="Rob Buis" href="mailto:rbuis@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-contain/#content-visibility"> +<meta name="assert" content="innerText is empty for skipped content due to content-visibility auto"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/utils.js"></script> + +<div id="container"> +This text should be visible. +<div style="content-visibility: auto"> + This text should be visible. + <div id="inner">This text is also visible.<br/> + </div> +</div> +<div id=spacer style="height: 300vh"></div> +<div style="content-visibility: auto"> + This text should not be visible. + <div id="inner2"> + This text is also not visible. + </div> +</div> +</div> + +<script> +async_test((t) => { + function step1() { + t.step(() => { + assert_equals(document.getElementById("container").innerText, "This text should be visible.\nThis text should be visible.\nThis text is also visible.\n"); + assert_equals(document.getElementById("inner").innerText, "This text is also visible.\n"); + assert_equals(document.getElementById("inner2").innerText, ""); + }); + t.done(); + } + + requestAnimationFrame(() => requestAnimationFrame(step1)); +}); +</script> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-heights-013.html b/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-heights-013.html index 2410e0a..f39e83c 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-heights-013.html +++ b/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-heights-013.html
@@ -34,6 +34,6 @@ <div class="flexbox" style="width: 100px; height: 150px; outline: 5px solid black;"> <div style="background: red;"> - <embed style="height: 100%; width: 100%;" type="application/x-webkit-test-webplugin" data-expected-height="150"></embed> + <embed style="display:inline-block; height: 100%; width: 100%;" type="application/x-webkit-test-webplugin" data-expected-height="150"></embed> </div> </div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001-ref.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001-ref.html index 383bc7a..63dce01 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001-ref.html
@@ -4,10 +4,16 @@ <title>CSS Reftest Reference</title> <link rel="author" title="Matt Woodrow" href="mailto:mwoodrow@mozilla.com"> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> + <link rel="stylesheet" href="/fonts/ahem.css"> + <style> + div { + font: 25px/1 Ahem; + } + </style> </head> <body> <div style="transform: rotatex(180deg); width: 100px; height: 100px;"> - Test Text + XXpp </div> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001.html b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001.html index dbebc64..9459381 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transforms/transform3d-preserve3d-001.html
@@ -5,16 +5,22 @@ <link rel="author" title="Matt Woodrow" href="mailto:mwoodrow@mozilla.com"> <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name"> <link rel="help" href="http://www.w3.org/TR/css-transforms-2/#transform-style-property"> + <link rel="stylesheet" href="/fonts/ahem.css"> <meta name="assert" content="This tests that if preserve-3d is specified, four 45deg rotations equal one 180deg rotation."> <link rel="match" href="transform3d-preserve3d-001-ref.html"> + <style> + div { + font: 25px/1 Ahem; + } + </style> </head> <body> <div style="transform: rotatex(45deg); transform-style: preserve-3d;"> <div style="transform: rotatex(45deg); transform-style: preserve-3d;"> <div style="transform: rotatex(45deg); transform-style: preserve-3d;"> <div style="transform: rotatex(45deg); width: 100px; height: 100px;"> - Test Text + XXpp </div> </div> </div>
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-origin-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-origin-a11y-test.js index 3c6eff2..4176710 100644 --- a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-origin-a11y-test.js +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-origin-a11y-test.js
@@ -6,10 +6,12 @@ import {SecurityTestRunner} from 'security_test_runner'; import {AxeCoreTestRunner} from 'axe_core_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.showPanel('security'); - const request1 = new SDK.NetworkRequest(0, 'https://foo.test/', 'https://foo.test', 0, 0, null); + const request1 = new SDK.NetworkRequest.NetworkRequest(0, 'https://foo.test/', 'https://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Secure); const securityDetails = { protocol : 'TLS 1.2',
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-overview-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-overview-a11y-test.js index 7869131..62e9ffd 100644 --- a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-overview-a11y-test.js +++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/security/security-overview-a11y-test.js
@@ -6,6 +6,8 @@ import {SecurityTestRunner} from 'security_test_runner'; import {AxeCoreTestRunner} from 'axe_core_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.showPanel('security'); @@ -14,7 +16,7 @@ /* safetyTipsInfo= */ null, /* securityStateIssueIds= */ []); TestRunner.mainTarget.model(Security.SecurityModel).dispatchEventToListeners( Security.SecurityModel.Events.VisibleSecurityStateChanged, pageVisibleSecurityState); - const request = new SDK.NetworkRequest(0, 'http://foo.test', 'https://foo.test', 0, 0, null); + const request = new SDK.NetworkRequest.NetworkRequest(0, 'http://foo.test', 'https://foo.test', 0, 0, null); request.setBlockedReason(Protocol.Network.BlockedReason.MixedContent); request.mixedContentType = 'blockable'; SecurityTestRunner.dispatchRequestFinished(request);
diff --git a/third_party/blink/web_tests/http/tests/devtools/application-panel/resources-panel-resource-preview.js b/third_party/blink/web_tests/http/tests/devtools/application-panel/resources-panel-resource-preview.js index af4a837..bc927de 100644 --- a/third_party/blink/web_tests/http/tests/devtools/application-panel/resources-panel-resource-preview.js +++ b/third_party/blink/web_tests/http/tests/devtools/application-panel/resources-panel-resource-preview.js
@@ -6,6 +6,8 @@ import {ApplicationTestRunner} from 'application_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests Application Panel preview for resources of different types.\n`); await TestRunner.loadLegacyModule('console'); @@ -54,8 +56,8 @@ } async function revealResourceWithDisplayName(name) { - var target = SDK.targetManager.primaryPageTarget(); - var model = target.model(SDK.ResourceTreeModel); + var target = SDK.TargetManager.TargetManager.instance().primaryPageTarget(); + var model = target.model(SDK.ResourceTreeModel.ResourceTreeModel); var resource = null; for (var r of model.mainFrame.resources()) { if (r.displayName !== name)
diff --git a/third_party/blink/web_tests/http/tests/devtools/bindings/ignore-listed-sourcemap-detach.js b/third_party/blink/web_tests/http/tests/devtools/bindings/ignore-listed-sourcemap-detach.js index 54bb613..f00dc4e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/bindings/ignore-listed-sourcemap-detach.js +++ b/third_party/blink/web_tests/http/tests/devtools/bindings/ignore-listed-sourcemap-detach.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.loadLegacyModule('console'); TestRunner.addResult(`Tests that ignore-listed sourcemaps properly detach on reload crbug.com/888688`); @@ -23,7 +25,7 @@ await ConsoleTestRunner.waitForConsoleMessagesPromise(1); await TestRunner.reloadPagePromise(); - TestRunner.addResult(`After reload, Console message count: ${SDK.ConsoleModel.allMessagesUnordered().length}`); + TestRunner.addResult(`After reload, Console message count: ${SDK.ConsoleModel.ConsoleModel.allMessagesUnordered().length}`); TestRunner.completeTest(); } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/bindings/inline-styles-binding.js b/third_party/blink/web_tests/http/tests/devtools/bindings/inline-styles-binding.js index 3dc704b..34212663 100644 --- a/third_party/blink/web_tests/http/tests/devtools/bindings/inline-styles-binding.js +++ b/third_party/blink/web_tests/http/tests/devtools/bindings/inline-styles-binding.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Editing inline styles should play nice with inline scripts.\n`); @@ -30,7 +32,7 @@ i = 0; for (const styleSheetId of styleSheets) { const header = TestRunner.cssModel.styleSheetHeaderForId(styleSheetId); - const rawLocation = new SDK.CSSLocation(header, header.startLine, header.startColumn); + const rawLocation = new SDK.CSSModel.CSSLocation(header, header.startLine, header.startColumn); await Bindings.cssWorkspaceBinding.createLiveLocation( rawLocation, updateDelegate.bind(null, 'style' + i), locationPool); i++;
diff --git a/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-bindings.js b/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-bindings.js index 9ef611d..f6c4033 100644 --- a/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-bindings.js +++ b/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-bindings.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that bindings handle target suspension as expected.\n`); @@ -21,7 +23,7 @@ snapshot = BindingsTestRunner.dumpWorkspace(snapshot); TestRunner.markStep('Suspending targets.'); - await SDK.targetManager.suspendAllTargets(); + await SDK.TargetManager.TargetManager.instance().suspendAllTargets(); snapshot = BindingsTestRunner.dumpWorkspace(snapshot); TestRunner.markStep('detachFrame'); @@ -31,7 +33,7 @@ TestRunner.markStep('Resuming targets.'); await Promise.all([ - SDK.targetManager.resumeAllTargets(), BindingsTestRunner.waitForSourceMap('sourcemap-script.js.map'), + SDK.TargetManager.TargetManager.instance().resumeAllTargets(), BindingsTestRunner.waitForSourceMap('sourcemap-script.js.map'), BindingsTestRunner.waitForSourceMap('sourcemap-style.css.map') ]); snapshot = BindingsTestRunner.dumpWorkspace(snapshot);
diff --git a/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-navigator.js b/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-navigator.js index d1c9acfa..aaf140c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-navigator.js +++ b/third_party/blink/web_tests/http/tests/devtools/bindings/suspendtarget-navigator.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that navigator is rendered properly when targets are suspended and resumed.\n`); await TestRunner.loadLegacyModule('sources'); @@ -30,7 +32,7 @@ SourcesTestRunner.dumpNavigatorView(sourcesNavigator, false); TestRunner.markStep('Suspending targets.'); - await SDK.targetManager.suspendAllTargets(); + await SDK.TargetManager.TargetManager.instance().suspendAllTargets(); SourcesTestRunner.dumpNavigatorView(sourcesNavigator, false); TestRunner.markStep('detachFrame'); @@ -40,7 +42,7 @@ TestRunner.markStep('Resuming targets.'); await Promise.all([ - SDK.targetManager.resumeAllTargets(), + SDK.TargetManager.TargetManager.instance().resumeAllTargets(), BindingsTestRunner.waitForSourceMap('sourcemap-script.js.map'), BindingsTestRunner.waitForSourceMap('sourcemap-style.css.map'), ]);
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-data.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-data.js index ac24cd6b..13b9470 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-data.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-data.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cache data is correctly populated in the Inspector.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); function errorAndExit(error) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-deletion.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-deletion.js index b285b73..591e786 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-deletion.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-deletion.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cache data is correctly deleted by the inspector.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); function errorAndExit(error) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-entry-deletion.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-entry-deletion.js index 7cf946d..9204e3d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-entry-deletion.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-entry-deletion.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cache entry data is correctly deleted by the inspector.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); function errorAndExit(error) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-cache-content.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-cache-content.js index d3350da9..407a0c7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-cache-content.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-cache-content.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cache view updates when the cache is changed.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); await ApplicationTestRunner.clearAllCaches();
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-list.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-list.js index 1d1210c..5194712 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-list.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-live-update-list.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the cache storage list live updates.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,24 +15,24 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); cacheStorageModel.setThrottlerSchedulesAsSoonAsPossibleForTest(); await ApplicationTestRunner.clearAllCaches(); await ApplicationTestRunner.dumpCacheTree(); - var promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.prototype, 'cacheAdded'); + var promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel.prototype, 'cacheAdded'); ApplicationTestRunner.createCache('testCache1'); await promise; await ApplicationTestRunner.dumpCacheTreeNoRefresh(); - promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.prototype, 'cacheAdded'); + promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel.prototype, 'cacheAdded'); ApplicationTestRunner.createCache('testCache2'); await promise; await ApplicationTestRunner.dumpCacheTreeNoRefresh(); - promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.prototype, 'cacheRemoved'); + promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel.prototype, 'cacheRemoved'); ApplicationTestRunner.deleteCache('testCache1'); await promise; await ApplicationTestRunner.dumpCacheTreeNoRefresh();
diff --git a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-names.js b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-names.js index f022911..9fe47138 100644 --- a/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-names.js +++ b/third_party/blink/web_tests/http/tests/devtools/cache-storage/cache-names.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cache names are correctly loaded and displayed in the inspector.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ await TestRunner.showPanel('resources'); - var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel); + var cacheStorageModel = TestRunner.mainTarget.model(SDK.ServiceWorkerCacheModel.ServiceWorkerCacheModel); cacheStorageModel.enable(); function errorAndExit(error) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/changes/changes-sidebar.js b/third_party/blink/web_tests/http/tests/devtools/changes/changes-sidebar.js index 21b4808..0d117fa 100644 --- a/third_party/blink/web_tests/http/tests/devtools/changes/changes-sidebar.js +++ b/third_party/blink/web_tests/http/tests/devtools/changes/changes-sidebar.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests that the changes sidebar contains the changed uisourcecodes.\n`); await TestRunner.loadLegacyModule('workspace_diff'); @@ -65,6 +67,6 @@ function addUISourceCode(url, content) { return project.addContentProvider( - url, TextUtils.StaticContentProvider.fromString(url, Common.resourceTypes.Stylesheet, content)); + url, TextUtils.StaticContentProvider.fromString(url, Common.ResourceType.resourceTypes.Stylesheet, content)); } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/command-line-api-inspect.js b/third_party/blink/web_tests/http/tests/devtools/command-line-api-inspect.js index 9184e6c..7f54d90 100644 --- a/third_party/blink/web_tests/http/tests/devtools/command-line-api-inspect.js +++ b/third_party/blink/web_tests/http/tests/devtools/command-line-api-inspect.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that inspect() command line api works.\n`); await TestRunner.loadLegacyModule('console'); @@ -13,7 +15,7 @@ </p> `); - TestRunner.addSniffer(SDK.RuntimeModel.prototype, 'inspectRequested', sniffInspect, true); + TestRunner.addSniffer(SDK.RuntimeModel.RuntimeModel.prototype, 'inspectRequested', sniffInspect, true); function sniffInspect(objectId, hints) { TestRunner.addResult('WebInspector.inspect called with: ' + objectId.description); @@ -33,7 +35,7 @@ TestRunner.runTestSuite([function testRevealElement(next) { const originalReveal = Common.Revealer.reveal; Common.Revealer.setRevealForTest((node) => { - if (!(node instanceof SDK.RemoteObject)) { + if (!(node instanceof SDK.RemoteObject.RemoteObject)) { return Promise.resolve(); } return originalReveal(node).then(step3);
diff --git a/third_party/blink/web_tests/http/tests/devtools/components/cookies-table.js b/third_party/blink/web_tests/http/tests/devtools/components/cookies-table.js index d3aea19..cabc70d3 100644 --- a/third_party/blink/web_tests/http/tests/devtools/components/cookies-table.js +++ b/third_party/blink/web_tests/http/tests/devtools/components/cookies-table.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests inspector cookies table\n`); @@ -79,7 +81,7 @@ } function createCookie(data) { - const cookie = new SDK.Cookie(data.name, data.value); + const cookie = new SDK.Cookie.Cookie(data.name, data.value); for (let key in data) { if (key === 'name' || key === 'value') continue; @@ -90,7 +92,7 @@ } function createSortAndDumpCookies(cookieData, sortColumn, isAsc) { - const table = new CookieTable.CookiesTable(SDK.targetManager.rootTarget(), true); + const table = new CookieTable.CookiesTable(SDK.TargetManager.TargetManager.instance().rootTarget(), true); const cookies = cookieData.map(createCookie); table.dataGrid = mockDataGrid({sortColumn, isAsc}); table.sortCookies(cookies); @@ -99,7 +101,7 @@ } function createBuildAndDumpTable(cookieData, selectedNode, isAsc, lastEditedColumn) { - const table = new CookieTable.CookiesTable(SDK.targetManager.rootTarget(), true); + const table = new CookieTable.CookiesTable(SDK.TargetManager.TargetManager.instance().rootTarget(), true); const cookies = cookieData && cookieData.map(createCookie); const rootNode = mockNode({}); table.lastEditedColumnId = lastEditedColumn || null;
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-bad-stacktrace.js b/third_party/blink/web_tests/http/tests/devtools/console/console-bad-stacktrace.js index 3e841b16..2e0259ec 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-bad-stacktrace.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-bad-stacktrace.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult('Tests that console messages with invalid stacktraces will still be rendered, crbug.com/826210\n'); @@ -26,14 +28,14 @@ } ] }; - var badStackTraceMessage = new SDK.ConsoleMessage( + var badStackTraceMessage = new SDK.ConsoleModel.ConsoleMessage( TestRunner.runtimeModel, - SDK.ConsoleMessage.FrontendMessageSource.ConsoleAPI, + SDK.ConsoleModel.FrontendMessageSource.ConsoleAPI, Protocol.Log.LogEntryLevel.Error, 'This should be visible', { type: Protocol.Runtime.ConsoleAPICalledEventType.Error, stackTrace: badStackTrace, }); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addMessage(badStackTraceMessage); await ConsoleTestRunner.dumpConsoleMessages();
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-eval-throw.js b/third_party/blink/web_tests/http/tests/devtools/console/console-eval-throw.js index c6650527..f9b384d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-eval-throw.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-eval-throw.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that evaluating 'throw undefined|1|string|object|Error' in the console won't crash the browser and correctly reported. Bug 59611.\n`); @@ -14,7 +16,7 @@ async function dumpMessages(next, message) { await ConsoleTestRunner.dumpConsoleMessagesIgnoreErrorStackFrames(); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared, afterCleared); Console.ConsoleView.clearConsole();
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-group-similar.js b/third_party/blink/web_tests/http/tests/devtools/console/console-group-similar.js index 46f071c..dcfb9ca 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-group-similar.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-group-similar.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that console correctly groups similar messages.\n`); @@ -47,10 +49,10 @@ * @param {string} level */ function addViolationMessage(text, url, level) { - var message = new SDK.ConsoleMessage( + var message = new SDK.ConsoleModel.ConsoleMessage( null, Protocol.Log.LogEntrySource.Violation, level, text, {type: Protocol.Runtime.ConsoleAPICalledEventType.Log, url}); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addMessage(message); } @@ -59,11 +61,11 @@ * @param {string} url */ function addConsoleAPIMessage(text, url) { - var message = new SDK.ConsoleMessage( - null, SDK.ConsoleMessage.FrontendMessageSource.ConsoleAPI, + var message = new SDK.ConsoleModel.ConsoleMessage( + null, SDK.ConsoleModel.FrontendMessageSource.ConsoleAPI, Protocol.Log.LogEntryLevel.Info, text, {type: Protocol.Runtime.ConsoleAPICalledEventType.Log, url}); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addMessage(message); } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-links-on-messages-before-inspection.js b/third_party/blink/web_tests/http/tests/devtools/console/console-links-on-messages-before-inspection.js index ee1130a9..4891e68 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-links-on-messages-before-inspection.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-links-on-messages-before-inspection.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests a handling of a click on the link in a message, which had been shown before its originating script was added.\n`); @@ -23,12 +25,12 @@ `); - var message = new SDK.ConsoleMessage( + var message = new SDK.ConsoleModel.ConsoleMessage( TestRunner.runtimeModel, Protocol.Log.LogEntrySource.JS, Protocol.Log.LogEntryLevel.Info, 'hello?', {url: 'http://127.0.0.1:8000/devtools/resources/source2.js'}); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addMessage(message); TestRunner.debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource, onScriptAdded); await ConsoleTestRunner.dumpConsoleMessages();
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-preserve-log.js b/third_party/blink/web_tests/http/tests/devtools/console/console-preserve-log.js index 99ca948..b8f742e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-preserve-log.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-preserve-log.js
@@ -5,13 +5,15 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the console can preserve log messages across navigations. Bug 53359\n`); await TestRunner.loadLegacyModule('console'); await TestRunner.showPanel('console'); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); - consoleModel.addMessage(new SDK.ConsoleMessage( + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); + consoleModel.addMessage(new SDK.ConsoleModel.ConsoleMessage( TestRunner.runtimeModel, Protocol.Log.LogEntrySource.Other, Protocol.Log.LogEntryLevel.Info, 'PASS')); Common.settingForTest('preserveConsoleLog').set(true);
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error-in-worker.js b/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error-in-worker.js index 6fe8f49..8ed006e0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error-in-worker.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error-in-worker.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that console revokes lazily handled promise rejections.\n`); await TestRunner.loadLegacyModule('console'); @@ -23,8 +25,8 @@ } `); - SDK.targetManager.addModelListener(SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, messageAdded); - SDK.targetManager.addModelListener(SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageUpdated, messageUpdated); + SDK.TargetManager.TargetManager.instance().addModelListener(SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, messageAdded); + SDK.TargetManager.TargetManager.instance().addModelListener(SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageUpdated, messageUpdated); Console.ConsoleView.instance().setImmediatelyFilterMessagesForTest(); TestRunner.addResult('Creating worker with promise');
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error.js b/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error.js index a404e4c..2df6849 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-revoke-error.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that console revokes lazily handled promise rejections.\n`); await TestRunner.loadLegacyModule('console'); @@ -26,7 +28,7 @@ `); var messageAddedListener = ConsoleTestRunner.wrapListener(messageAdded); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, messageAddedListener); Console.ConsoleView.instance().setImmediatelyFilterMessagesForTest(); Common.settings.moduleSetting('consoleGroupSimilar').set(false);
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-save-to-temp-var.js b/third_party/blink/web_tests/http/tests/devtools/console/console-save-to-temp-var.js index 75432b3..65b3ded2 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-save-to-temp-var.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-save-to-temp-var.js
@@ -6,6 +6,8 @@ import {ConsoleTestRunner} from 'console_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests saving objects to temporary variables.\n`); await TestRunner.loadLegacyModule('console'); @@ -34,12 +36,12 @@ function didEvaluate(result) { TestRunner.assertTrue(!result.exceptionDetails, 'FAIL: was thrown. Expression: ' + expression); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); - consoleModel.saveToTempVariable(UI.context.flavor(SDK.ExecutionContext), result.object); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); + consoleModel.saveToTempVariable(UI.context.flavor(SDK.RuntimeModel.ExecutionContext), result.object); ConsoleTestRunner.waitUntilNthMessageReceived(2, evaluateNext); } - UI.context.flavor(SDK.ExecutionContext) + UI.context.flavor(SDK.RuntimeModel.ExecutionContext) .evaluate({expression: expression, objectGroup: 'console'}) .then(didEvaluate); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/console-timestamp.js b/third_party/blink/web_tests/http/tests/devtools/console/console-timestamp.js index 7f4e7543..d161466 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/console-timestamp.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/console-timestamp.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests the console timestamp setting.\n`); await TestRunner.loadLegacyModule('console'); @@ -19,7 +21,7 @@ Common.settingForTest('consoleGroupSimilar').set(false); function addMessageWithFixedTimestamp(messageText, timestamp, type) { - var message = new SDK.ConsoleMessage( + var message = new SDK.ConsoleModel.ConsoleMessage( TestRunner.runtimeModel, Protocol.Log.LogEntrySource.Other, // source Protocol.Log.LogEntryLevel.Info, // level @@ -28,26 +30,26 @@ // timestamp: 2014-05-13T16:53:20.123Z timestamp: timestamp || baseTimestamp + 123, }); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addMessage(message, true); // allowGrouping } TestRunner.addResult('Console messages with timestamps disabled:'); addMessageWithFixedTimestamp( '<Before> First Command', baseTimestamp + 789, - SDK.ConsoleMessage.FrontendMessageType.Command); + SDK.ConsoleModel.FrontendMessageType.Command); addMessageWithFixedTimestamp( '<Before> First Result', baseTimestamp + 789, - SDK.ConsoleMessage.FrontendMessageType.Result); + SDK.ConsoleModel.FrontendMessageType.Result); addMessageWithFixedTimestamp('<Before>'); addMessageWithFixedTimestamp('<Before>', baseTimestamp + 456); addMessageWithFixedTimestamp('<Before>'); addMessageWithFixedTimestamp( '<Before> Command', baseTimestamp, - SDK.ConsoleMessage.FrontendMessageType.Command); + SDK.ConsoleModel.FrontendMessageType.Command); addMessageWithFixedTimestamp( '<Before> Result', baseTimestamp + 1, - SDK.ConsoleMessage.FrontendMessageType.Result); + SDK.ConsoleModel.FrontendMessageType.Result); await ConsoleTestRunner.dumpConsoleMessages();
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/nested-worker-eval-contains-stack.js b/third_party/blink/web_tests/http/tests/devtools/console/nested-worker-eval-contains-stack.js index 7c1a9c0..5c654ae 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/nested-worker-eval-contains-stack.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/nested-worker-eval-contains-stack.js
@@ -1,6 +1,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; + +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult(`Tests exception message from eval on nested worker context in console contains stack trace.\n`); await TestRunner.loadLegacyModule('console'); @@ -12,14 +14,14 @@ } `); - TestRunner.addSniffer(SDK.RuntimeModel.prototype, 'executionContextCreated', contextCreated); + TestRunner.addSniffer(SDK.RuntimeModel.RuntimeModel.prototype, 'executionContextCreated', contextCreated); TestRunner.evaluateInPage('startWorker()'); var contexts_still_loading = 2; function contextCreated() { contexts_still_loading--; if (contexts_still_loading > 0) { - TestRunner.addSniffer(SDK.RuntimeModel.prototype, 'executionContextCreated', contextCreated); + TestRunner.addSniffer(SDK.RuntimeModel.RuntimeModel.prototype, 'executionContextCreated', contextCreated); return; }
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/paintworklet-console-selector.js b/third_party/blink/web_tests/http/tests/devtools/console/paintworklet-console-selector.js index 2e7a6d01..c994635 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/paintworklet-console-selector.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/paintworklet-console-selector.js
@@ -6,6 +6,8 @@ import {ConsoleTestRunner} from 'console_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests console execution context selector for paintworklet.\n`); await TestRunner.loadLegacyModule('console'); @@ -30,7 +32,7 @@ var selector = consoleView.consoleContextSelector; TestRunner.addResult('Console context selector:'); for (var executionContext of selector._items) { - var selected = UI.context.flavor(SDK.ExecutionContext) === executionContext; + var selected = UI.context.flavor(SDK.RuntimeModel.ExecutionContext) === executionContext; var text = '____'.repeat(selector.depthFor(executionContext)) + selector.titleFor(executionContext) + " / " + selector._subtitleFor(executionContext); var disabled = !selector.isItemSelectable(executionContext); TestRunner.addResult(`${selected ? '*' : ' '} ${text} ${disabled ? '[disabled]' : ''}`);
diff --git a/third_party/blink/web_tests/http/tests/devtools/console/worker-eval-contains-stack.js b/third_party/blink/web_tests/http/tests/devtools/console/worker-eval-contains-stack.js index 04598c8..a463804 100644 --- a/third_party/blink/web_tests/http/tests/devtools/console/worker-eval-contains-stack.js +++ b/third_party/blink/web_tests/http/tests/devtools/console/worker-eval-contains-stack.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests exception message from eval on worker context in console contains stack trace.\n`); await TestRunner.loadLegacyModule('console'); @@ -16,7 +18,7 @@ } `); - TestRunner.addSniffer(SDK.RuntimeModel.prototype, 'executionContextCreated', contextCreated); + TestRunner.addSniffer(SDK.RuntimeModel.RuntimeModel.prototype, 'executionContextCreated', contextCreated); TestRunner.evaluateInPage('startWorker()'); function contextCreated() {
diff --git a/third_party/blink/web_tests/http/tests/devtools/copy-network-request.js b/third_party/blink/web_tests/http/tests/devtools/copy-network-request.js index c5be6bb..9f0d3c4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/copy-network-request.js +++ b/third_party/blink/web_tests/http/tests/devtools/copy-network-request.js
@@ -5,6 +5,9 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; +import * as Network from 'devtools/panels/network/network.js'; + (async function() { 'use strict'; TestRunner.addResult(`Tests curl command generation\n`); @@ -15,7 +18,7 @@ const NODE_JS = 1; function newRequest(isBlob, headers, data, opt_url, method = null) { - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, (isBlob === true ? 'blob:' : '') + (opt_url || 'http://example.org/path'), @@ -35,8 +38,8 @@ async function dumpRequest(headers, data, opt_url, method) { const request = newRequest(false, headers, data, opt_url, method); - var curlWin = await Network.NetworkLogView.generateCurlCommand(request, 'win'); - var curlUnix = await Network.NetworkLogView.generateCurlCommand(request, 'unix'); + var curlWin = await Network.NetworkLogView.NetworkLogView.generateCurlCommand(request, 'win'); + var curlUnix = await Network.NetworkLogView.NetworkLogView.generateCurlCommand(request, 'unix'); var powershell = await logView.generatePowerShellCommand(request); var fetchForBrowser = await logView.generateFetchCall(request, BROWSER); var fetchForNodejs = await logView.generateFetchCall(request, NODE_JS);
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/edit/perform-undo-undo.js b/third_party/blink/web_tests/http/tests/devtools/elements/edit/perform-undo-undo.js index ea867be..80cdee4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/edit/perform-undo-undo.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/edit/perform-undo-undo.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that client can call undo multiple times with non-empty history.\n`); await TestRunner.loadLegacyModule('elements'); @@ -34,7 +36,7 @@ } async function step3() { - await SDK.domModelUndoStack.undo(); + await SDK.DOMModel.DOMModelUndoStack.instance().undo(); TestRunner.addResult('===== Undo 1 ====='); ElementsTestRunner.dumpElementsTree(containerNode);
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-restore-selection-when-node-comes-later.js b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-restore-selection-when-node-comes-later.js index c131930..eb610bb0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-restore-selection-when-node-comes-later.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-restore-selection-when-node-comes-later.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Verify that last selected element is restored properly later, even if it failed to do so once.\n`); @@ -77,7 +79,7 @@ * @param {string} pathToIgnore */ function overridePushNodeForPath(pathToIgnore) { - var original = TestRunner.override(SDK.DOMModel.prototype, 'pushNodeByPathToFrontend', override); + var original = TestRunner.override(SDK.DOMModel.DOMModel.prototype, 'pushNodeByPathToFrontend', override); function override(nodePath) { if (nodePath === pathToIgnore)
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-search.js b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-search.js index 262f38b..a1e6866 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-search.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-search.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that elements panel search is returning proper results.\n`); await TestRunner.showPanel('elements'); @@ -56,7 +58,7 @@ async function searchCallback(next, resultCount) { if (resultCount == 0) { TestRunner.addResult('Nothing found'); - SDK.DOMModel.cancelSearch(); + SDK.DOMModel.DOMModel.cancelSearch(); next(); return; } @@ -69,7 +71,7 @@ TestRunner.addResult(markupVa_lue.split('').join(' ')); } - SDK.DOMModel.cancelSearch(); + SDK.DOMModel.DOMModel.cancelSearch(); next(); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/event-listeners-framework-with-service-worker.js b/third_party/blink/web_tests/http/tests/devtools/elements/event-listeners-framework-with-service-worker.js index a0c6343..66cf16f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/event-listeners-framework-with-service-worker.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/event-listeners-framework-with-service-worker.js
@@ -8,6 +8,8 @@ import {ConsoleTestRunner} from 'console_test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests framework event listeners output in Sources panel when service worker is present.\n`); await TestRunner.loadLegacyModule('elements'); @@ -37,7 +39,7 @@ BrowserDebugger.ObjectEventListenersSidebarPane.instance(); function isServiceWorker() { - var target = UI.context.flavor(SDK.ExecutionContext).target(); + var target = UI.context.flavor(SDK.RuntimeModel.ExecutionContext).target(); return target.type() === SDK.Target.Type.ServiceWorker; } @@ -58,7 +60,7 @@ function step3() { TestRunner.addResult('Selecting main thread'); - SourcesTestRunner.selectThread(SDK.targetManager.primaryPageTarget()); + SourcesTestRunner.selectThread(SDK.TargetManager.TargetManager.instance().primaryPageTarget()); TestRunner.addResult('Context is service worker: ' + isServiceWorker()); TestRunner.addResult('Dumping listeners'); ElementsTestRunner.expandAndDumpEventListeners(objectEventListenersPane.eventListenersView, step4);
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-detached.js b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-detached.js index 4fa5d0d..7a1b7d53 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-detached.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-detached.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that highlighting a detached node does not crash. crbug.com/958958\n`); await TestRunner.loadLegacyModule('elements'); @@ -17,7 +19,7 @@ styleElement.id = 'inspected'; styleElement; `); - const domModel = remoteObject.runtimeModel().target().model(SDK.DOMModel); + const domModel = remoteObject.runtimeModel().target().model(SDK.DOMModel.DOMModel); const node = await domModel.pushObjectAsNodeToFrontend(remoteObject); node.highlight();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/inspect-pseudo-element.js b/third_party/blink/web_tests/http/tests/devtools/elements/inspect-pseudo-element.js index 47097a0..94364f4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/inspect-pseudo-element.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/inspect-pseudo-element.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Test\n`); await TestRunner.loadLegacyModule('elements'); @@ -38,7 +40,7 @@ TestRunner.overlayModel.setInspectMode(Protocol.Overlay.InspectMode.SearchForNode).then(inspectModeEnabled); function inspectModeEnabled() { - UI.context.addFlavorChangeListener(SDK.DOMNode, selectedNodeChanged); + UI.context.addFlavorChangeListener(SDK.DOMModel.DOMNode, selectedNodeChanged); TestRunner.evaluateInPage('clickPseudo()'); } @@ -48,7 +50,7 @@ TestRunner.addResult('<no selected node>'); else TestRunner.addResult('Selected node pseudo type: ' + selectedNode.pseudoType()); - UI.context.removeFlavorChangeListener(SDK.DOMNode, selectedNodeChanged); + UI.context.removeFlavorChangeListener(SDK.DOMModel.DOMNode, selectedNodeChanged); TestRunner.completeTest(); } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/selected-element-changes-execution-context.js b/third_party/blink/web_tests/http/tests/devtools/elements/selected-element-changes-execution-context.js index a330863..9c396bd 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/selected-element-changes-execution-context.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/selected-element-changes-execution-context.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the execution context is changed to match new selected node.\n`); await TestRunner.loadLegacyModule('elements'); @@ -21,7 +23,7 @@ ElementsTestRunner.expandElementsTree(onExpanded); function onExpanded() { - mainContext = UI.context.flavor(SDK.ExecutionContext); + mainContext = UI.context.flavor(SDK.RuntimeModel.ExecutionContext); dumpContextAndNext(next); } }, @@ -39,15 +41,15 @@ }, function selectIframeContentDocument(next) { - var iframe = UI.context.flavor(SDK.DOMNode); + var iframe = UI.context.flavor(SDK.DOMModel.DOMNode); var child = iframe.contentDocument(); ElementsTestRunner.selectNode(child).then(dumpContextAndNext.bind(null, next)); }, ]); function dumpContextAndNext(next) { - var context = UI.context.flavor(SDK.ExecutionContext); - var node = UI.context.flavor(SDK.DOMNode); + var context = UI.context.flavor(SDK.RuntimeModel.ExecutionContext); + var node = UI.context.flavor(SDK.DOMModel.DOMNode); var contextName = context === mainContext ? 'main' : 'iframe'; var matchesNode = context.frameId === node.frameId(); TestRunner.addResult('Execution Context: ' + contextName);
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-1.js b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-1.js index 5cae97a9..77a5f1c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-1.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-1.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that elements panel preserves selected shadow DOM node on page refresh.\n`); await TestRunner.loadLegacyModule('elements'); @@ -27,10 +29,10 @@ ]); function isOpenShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Open; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.Open; } function isClosedShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Closed; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.Closed; } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-2.js b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-2.js index 463128e..83408f1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-2.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-2.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that elements panel preserves selected shadow DOM node on page refresh.\n`); await TestRunner.loadLegacyModule('elements'); @@ -27,11 +29,11 @@ ]); function isOpenShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Open; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.Open; } function isUserAgentShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.UserAgent; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.UserAgent; } function isOpenShadowRootChild(node) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-3.js b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-3.js index a83245b0..bc245b6 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-3.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/shadow/elements-panel-shadow-selection-on-refresh-3.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that elements panel preserves selected shadow DOM node on page refresh.\n`); await TestRunner.loadLegacyModule('elements'); @@ -28,11 +30,11 @@ ]); function isClosedShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Closed; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.Closed; } function isUserAgentShadowRoot(node) { - return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.UserAgent; + return node && node.shadowRootType() === SDK.DOMModel.DOMNode.ShadowRootTypes.UserAgent; } function isClosedShadowRootChild(node) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/mixed-case-color-aware-properties.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/mixed-case-color-aware-properties.js index d4356d71..57e92fc 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/mixed-case-color-aware-properties.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/mixed-case-color-aware-properties.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that color-related mix-cased CSS properties are actually color aware.\n`); await TestRunner.loadLegacyModule('elements'); @@ -12,7 +14,7 @@ var colorAwareProperties = ['bAckground-ColoR', 'COloR', 'Border-coLoR', 'border-right-color', 'BOX-SHADOW']; for (var i = 0; i < colorAwareProperties.length; ++i) { - var isColorAware = SDK.cssMetadata().isColorAwareProperty(colorAwareProperties[i]); + var isColorAware = SDK.CSSMetadata.cssMetadata().isColorAwareProperty(colorAwareProperties[i]); TestRunner.addResult(colorAwareProperties[i] + (isColorAware ? ' is' : ' is NOT') + ' color aware'); } TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action.js index 694d187..95ebeab0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that perform-undo-perform of the mergeable action does not crash.\n`); await TestRunner.loadLegacyModule('elements'); @@ -34,7 +36,7 @@ TestRunner.addResult('After changing property'); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.waitForStyles('container', step3); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/inline-style-sourcemap.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/inline-style-sourcemap.js index 032e761..bcbdc5f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/inline-style-sourcemap.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/inline-style-sourcemap.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that inline style sourceMappingURL is resolved properly.\n`); await TestRunner.loadLegacyModule('elements'); @@ -25,7 +27,7 @@ } `); - SDK.targetManager.addModelListener(SDK.CSSModel, SDK.CSSModel.Events.StyleSheetAdded, function() {}); + SDK.TargetManager.TargetManager.instance().addModelListener(SDK.CSSModel.CSSModel, SDK.CSSModel.Events.StyleSheetAdded, function() {}); TestRunner.evaluateInPage('embedInlineStyleSheet()', onEvaluated); function onEvaluated() {
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/keyframes-source-offsets.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/keyframes-source-offsets.js index 81b5d34..abd85fb7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/keyframes-source-offsets.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/keyframes-source-offsets.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that proper data and start/end offset positions are reported for CSS keyframes.\n`); await TestRunner.loadLegacyModule('elements'); @@ -53,7 +55,7 @@ dumpRule(animation); TestRunner.addResult('\n>> Modifying keyframe rule'); - var style = new SDK.CSSStyleDeclaration( + var style = new SDK.CSSStyleDeclaration.CSSStyleDeclaration( TestRunner.cssModel, null, response.cssKeyframesRules[1].keyframes[0].style, SDK.CSSStyleDeclaration.Type.Regular); await style.setText('width: 123px');
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes.js index d33dfbc..ea39b26 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that keyframes are shown in styles pane.\n`); await TestRunner.loadLegacyModule('elements'); @@ -40,7 +42,7 @@ async function step2() { TestRunner.addResult('=== After key modification ==='); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.waitForStyles('element', step3, true); } @@ -48,7 +50,7 @@ TestRunner.addResult('=== After undo ==='); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.waitForStyles('element', step4, true); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/supported-css-properties.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/supported-css-properties.js index d3075656..45eac9d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/supported-css-properties.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/supported-css-properties.js
@@ -4,11 +4,13 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Test supported CSS properties.\n`); await TestRunner.showPanel('elements'); - var marginLonghands = SDK.cssMetadata().getLonghands('margin'); + var marginLonghands = SDK.CSSMetadata.cssMetadata().getLonghands('margin'); marginLonghands.sort(); TestRunner.addResult('Margin longhands: ' + marginLonghands.join(', ')); TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-new-rule.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-new-rule.js index 4df4b6c..b6b575b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-new-rule.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-new-rule.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that adding a new rule can be undone.\n`); await TestRunner.loadLegacyModule('elements'); @@ -33,7 +35,7 @@ } function step4() { - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.selectNodeAndWaitForStyles('other', step5); } @@ -44,7 +46,7 @@ } function step6() { - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.selectNodeAndWaitForStyles('inspected', step7); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property.js index 08922cca..20d12d1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that adding a property is undone properly.\n`); await TestRunner.loadLegacyModule('elements'); @@ -49,7 +51,7 @@ TestRunner.addResult('(After adding property)'); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.selectNodeAndWaitForStyles('other', step2); } @@ -57,7 +59,7 @@ TestRunner.addResult('(After undo)'); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.selectNodeAndWaitForStyles('container', step3); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-rule-crash.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-rule-crash.js index f0c7f00..e1a53a9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-rule-crash.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-rule-crash.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the inspected page does not crash after undoing a new rule addition. Bug 104806\n`); await TestRunner.loadLegacyModule('elements'); @@ -30,7 +32,7 @@ } function step2() { - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.waitForStyles('other', step3); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/original-content-provider.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/original-content-provider.js index 9a0b1566..5fcfd4b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/original-content-provider.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/original-content-provider.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Verifies that CSSStyleSheetHeader.originalContentProvider() indeed returns original content.\n`); @@ -39,7 +41,7 @@ `); await ElementsTestRunner.selectNodeAndWaitForStylesPromise('inspected'); - TestRunner.addSniffer(SDK.CSSModel.prototype, 'originalContentRequestedForTest', onOriginalContentRequested, true); + TestRunner.addSniffer(SDK.CSSModel.CSSModel.prototype, 'originalContentRequestedForTest', onOriginalContentRequested, true); function onOriginalContentRequested(header) { TestRunner.addResult('original content loaded for header: ' + header.sourceURL); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing.js index 148e329..cd6d5d0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verifies that cancelling property value editing doesn't affect undo stack.\n`); await TestRunner.loadLegacyModule('elements'); @@ -54,7 +56,7 @@ async function undoStyles(next) { await ElementsTestRunner.dumpSelectedElementStyles(true, false, true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.waitForStyles('inspected', next, true); },
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property.js index 855d328..20c6c880 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that changing a property is undone properly.\n`); await TestRunner.loadLegacyModule('elements'); @@ -34,7 +36,7 @@ TestRunner.addResult('After changing property'); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.selectNodeAndWaitForStyles('other', step3); } @@ -42,7 +44,7 @@ TestRunner.addResult('After undo'); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.selectNodeAndWaitForStyles('container', step4); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-property-toggle.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-property-toggle.js index 31e0e82..7145b57d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-property-toggle.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-property-toggle.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that disabling style is undone properly.\n`); await TestRunner.loadLegacyModule('elements'); @@ -30,7 +32,7 @@ var treeItem = ElementsTestRunner.getElementStylePropertyTreeItem('font-weight'); ElementsTestRunner.dumpStyleTreeItem(treeItem, ''); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.waitForStyles('container', step3); } @@ -39,7 +41,7 @@ var treeItem = ElementsTestRunner.getElementStylePropertyTreeItem('font-weight'); ElementsTestRunner.dumpStyleTreeItem(treeItem, ''); - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.waitForStyles('container', step4); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text.js index 13d33a0..f6a2e83 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that setting selector text can be undone.\n`); await TestRunner.loadLegacyModule('elements'); @@ -34,7 +36,7 @@ async function step2() { TestRunner.addResult('=== After selector modification ==='); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.undo(); + SDK.DOMModel.DOMModelUndoStack.instance().undo(); ElementsTestRunner.selectNodeAndWaitForStyles('inspected', step3); } @@ -42,7 +44,7 @@ TestRunner.addResult('=== After undo ==='); await ElementsTestRunner.dumpSelectedElementStyles(true); - SDK.domModelUndoStack.redo(); + SDK.DOMModel.DOMModelUndoStack.instance().redo(); ElementsTestRunner.selectNodeAndWaitForStyles('other', step4); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/updates-throttled.js b/third_party/blink/web_tests/http/tests/devtools/elements/styles/updates-throttled.js index 545043b..03a295b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/updates-throttled.js +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/updates-throttled.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that Styles sidebar DOM rebuilds are throttled during consecutive updates. Bug 78086.\n`); await TestRunner.loadLegacyModule('elements'); @@ -21,7 +23,7 @@ TestRunner.addSniffer(Elements.StylesSidebarPane.prototype, 'innerRebuildUpdate', sniffRebuild, true); var stylesPane = UI.panels.elements.stylesWidget; for (var i = 0; i < UPDATE_COUNT; ++i) - UI.context.setFlavor(SDK.DOMNode, stylesPane.node()); + UI.context.setFlavor(SDK.DOMModel.DOMNode, stylesPane.node()); TestRunner.deprecatedRunAfterPendingDispatches(completeCallback); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/extensions/extensions-resources.js b/third_party/blink/web_tests/http/tests/devtools/extensions/extensions-resources.js index 1cfb8af..dc08e9b9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/extensions/extensions-resources.js +++ b/third_party/blink/web_tests/http/tests/devtools/extensions/extensions-resources.js
@@ -7,6 +7,8 @@ import {ExtensionsTestRunner} from 'extensions_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests resource-related methods of WebInspector extension API\n`); await TestRunner.loadLegacyModule('console'); @@ -32,7 +34,7 @@ } TestRunner.waitForStyleSheetChangedEvent = function(reply) { - TestRunner.addSniffer(SDK.CSSModel.prototype, "fireStyleSheetChanged", reply); + TestRunner.addSniffer(SDK.CSSModel.CSSModel.prototype, "fireStyleSheetChanged", reply); } await TestRunner.evaluateInPageAnonymously(`
diff --git a/third_party/blink/web_tests/http/tests/devtools/file-system-project.js b/third_party/blink/web_tests/http/tests/devtools/file-system-project.js index 0fb71c7..1878416 100644 --- a/third_party/blink/web_tests/http/tests/devtools/file-system-project.js +++ b/third_party/blink/web_tests/http/tests/devtools/file-system-project.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests file system project.\n`); await TestRunner.loadLegacyModule('sources'); @@ -24,8 +26,8 @@ function dumpUISourceCode(uiSourceCode, callback) { TestRunner.addResult('UISourceCode: ' + uiSourceCode.url().replace(/.*(LayoutTests|web_tests)./, '')); - if (uiSourceCode.contentType() === Common.resourceTypes.Script || - uiSourceCode.contentType() === Common.resourceTypes.Document) + if (uiSourceCode.contentType() === Common.ResourceType.resourceTypes.Script || + uiSourceCode.contentType() === Common.ResourceType.resourceTypes.Document) TestRunner.addResult( 'UISourceCode is content script: ' + (uiSourceCode.project().type() === Workspace.projectTypes.ContentScripts)); @@ -143,7 +145,7 @@ }, function testExcludesSettings(next) { - Common.settings.createLocalSetting('workspaceExcludedFolders', {}).set({'file:///var/www2': ['/html/']}); + Common.Settings.Settings.instance().createLocalSetting('workspaceExcludedFolders', {}).set({'file:///var/www2': ['/html/']}); createFileSystem('/var/www2', dumpExcludes); function dumpExcludes(fs) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/input-event-warning.js b/third_party/blink/web_tests/http/tests/devtools/input-event-warning.js index 17139fe..9072afb 100644 --- a/third_party/blink/web_tests/http/tests/devtools/input-event-warning.js +++ b/third_party/blink/web_tests/http/tests/devtools/input-event-warning.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that console warnings are issued for a blocked event listener and that there is no crash when an offending listener is removed by the handler.\n`); @@ -64,7 +66,7 @@ } `); - const consoleModel = SDK.targetManager.primaryPageTarget().model(SDK.ConsoleModel); + const consoleModel = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ConsoleModel.ConsoleModel); consoleModel.addEventListener( SDK.ConsoleModel.Events.MessageAdded, TestRunner.safeWrap(onConsoleMessage)); step1();
diff --git a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js index ff8c541..d8cb1ae7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js +++ b/third_party/blink/web_tests/http/tests/devtools/inspector-backend-commands.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests correctness of promisified protocol commands.\n`); @@ -67,7 +69,7 @@ var sendMessageToBackendOriginal = InspectorFrontendHost.sendMessageToBackend; InspectorFrontendHost.sendMessageToBackend = sendMessageToBackendLoopback; - var agent = SDK.targetManager.rootTarget().profilerAgent(); + var agent = SDK.TargetManager.TargetManager.instance().rootTarget().profilerAgent(); await processResult( 'commandError', agent.commandError({'message': 'this is the error message'})); // Error: error in the protocol response
diff --git a/third_party/blink/web_tests/http/tests/devtools/local-object-properties-section.js b/third_party/blink/web_tests/http/tests/devtools/local-object-properties-section.js index 2093a89a..98a3812 100644 --- a/third_party/blink/web_tests/http/tests/devtools/local-object-properties-section.js +++ b/third_party/blink/web_tests/http/tests/devtools/local-object-properties-section.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Test that ObjectPropertiesSection works with local remote objects.\n`); await TestRunner.loadLegacyModule('ui/legacy/components/object_ui'); @@ -12,7 +14,7 @@ for (var i = 1000; i < 1256; ++i) d.push(i); var object = {a: 'b', c: d}; - var localObject = SDK.RemoteObject.fromLocalObject(object); + var localObject = SDK.RemoteObject.RemoteObject.fromLocalObject(object); var propertiesSection = new ObjectUI.ObjectPropertiesSection(localObject, 'local object'); propertiesSection.expand();
diff --git a/third_party/blink/web_tests/http/tests/devtools/local-object.js b/third_party/blink/web_tests/http/tests/devtools/local-object.js index 29ae366..e6fdcdb 100644 --- a/third_party/blink/web_tests/http/tests/devtools/local-object.js +++ b/third_party/blink/web_tests/http/tests/devtools/local-object.js
@@ -4,11 +4,13 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests callFunction on local remote objects.\n`); var object = [6, 28, 496]; - var localObject = SDK.RemoteObject.fromLocalObject(object); + var localObject = SDK.RemoteObject.RemoteObject.fromLocalObject(object); function getItem(index) { return this[index];
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/download.js b/third_party/blink/web_tests/http/tests/devtools/network/download.js index beba523..1a6a73a 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/download.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/download.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that responseReceived is called on NetworkDispatcher for downloads.\n`); await TestRunner.showPanel('network'); @@ -18,9 +20,9 @@ }; `); - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'responseReceived', responseReceived); - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFailed', loadingFailed); - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'responseReceived', responseReceived); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFailed', loadingFailed); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); TestRunner.addIframe('resources/download.zzz'); function responseReceived(event) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/json-preview.js b/third_party/blink/web_tests/http/tests/devtools/network/json-preview.js index 2670f4b3..1e92db5 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/json-preview.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/json-preview.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that resources with JSON MIME types are previewed with the JSON viewer.\n`); await TestRunner.loadLegacyModule('source_frame'); @@ -12,7 +14,7 @@ function createNetworkRequestWithJSONMIMEType(type) { TestRunner.addResult('Creating a NetworkRequest with type: ' + type); - var request = SDK.NetworkRequest.create(0, 'http://localhost'); + var request = SDK.NetworkRequest.NetworkRequest.create(0, 'http://localhost'); request.mimeType = type; request.setContentDataProvider( () => Promise.resolve(
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-choose-preview-view.js b/third_party/blink/web_tests/http/tests/devtools/network/network-choose-preview-view.js index a97e51b..338d105 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-choose-preview-view.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-choose-preview-view.js
@@ -5,6 +5,9 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as Common from 'devtools/core/common/common.js'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { 'use strict'; TestRunner.addResult(`Tests to make sure the proper view is used for the data that is received in network panel.\n`); @@ -12,7 +15,7 @@ await TestRunner.showPanel('network'); function createNetworkRequest(mimeType, content, statusCode, resourceType) { - var request = SDK.NetworkRequest.create(0, 'http://localhost'); + var request = SDK.NetworkRequest.NetworkRequest.create(0, 'http://localhost'); request.setResourceType(resourceType); request.mimeType = mimeType; request.setContentDataProvider(() => Promise.resolve({error: null, content: content, encoded: false})); @@ -33,7 +36,7 @@ async function testPreviewer(mimeType, content, statusCode) { var testResourceTypes = [ - Common.resourceTypes.XHR, Common.resourceTypes.Fetch, Common.resourceTypes.Document, Common.resourceTypes.Other + Common.ResourceType.resourceTypes.XHR, Common.ResourceType.resourceTypes.Fetch, Common.ResourceType.resourceTypes.Document, Common.ResourceType.resourceTypes.Other ]; TestRunner.addResult('Testing with MimeType: ' + mimeType + ', and StatusCode: ' + statusCode); TestRunner.addResult('Content: ' + content.replace(/\0/g, '**NULL**'));
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-close-request-view.js b/third_party/blink/web_tests/http/tests/devtools/network/network-close-request-view.js index e05e96e..c02d1be 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-close-request-view.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-close-request-view.js
@@ -4,14 +4,17 @@ import {TestRunner} from 'test_runner'; +import * as Common from 'devtools/core/common/common.js'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.showPanel('network'); var panel = UI.panels.network; var target = panel.networkLogView; - var types = Common.resourceTypes; + var types = Common.ResourceType.resourceTypes; - var requestFoo = SDK.NetworkRequest.create('', '', '', '', ''); + var requestFoo = SDK.NetworkRequest.NetworkRequest.create('', '', '', '', ''); requestFoo.setResourceType(types.XHR); requestFoo.setRequestIdForTest('foo'); TestRunner.addResult('Showing request foo');
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-domain-filter.js b/third_party/blink/web_tests/http/tests/devtools/network/network-domain-filter.js index 68853c47..c38dc2d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-domain-filter.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-domain-filter.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as Network from 'devtools/panels/network/network.js'; + (async function() { TestRunner.addResult(`Tests doamin filter.\n`); await TestRunner.showPanel('network'); @@ -12,11 +14,11 @@ function checkSubdomains(domain) { TestRunner.addResult(''); TestRunner.addResult('Domain: ' + domain); - TestRunner.addResult('Subdomains: ' + JSON.stringify(Network.NetworkLogView.subdomains(domain))); + TestRunner.addResult('Subdomains: ' + JSON.stringify(Network.NetworkLogView.NetworkLogView.subdomains(domain))); } function checkFilter(value, domains) { - var filter = Network.NetworkLogView.createRequestDomainFilter(value); + var filter = Network.NetworkLogView.NetworkLogView.createRequestDomainFilter(value); TestRunner.addResult(''); TestRunner.addResult('Filter: ' + value); for (var i = 0; i < domains.length; ++i)
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-initiator-from-console.js b/third_party/blink/web_tests/http/tests/devtools/network/network-initiator-from-console.js index 7a9dfb6..d9f468ea 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-initiator-from-console.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-initiator-from-console.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that there is no javascript error when console evaluation causes resource loading.\n`); await TestRunner.showPanel('network'); @@ -17,7 +19,7 @@ str += 'var s = document.createElement("script");'; str += 's.src = "resources/silent_script.js";'; str += 'document.head.appendChild(s);'; - UI.context.flavor(SDK.ExecutionContext).evaluate({expression: str, objectGroup: 'console'}); + UI.context.flavor(SDK.RuntimeModel.ExecutionContext).evaluate({expression: str, objectGroup: 'console'}); } function onRequest(event) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-log-service-worker-navigate.js b/third_party/blink/web_tests/http/tests/devtools/network/network-log-service-worker-navigate.js index cce1a75..371fbbf 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-log-service-worker-navigate.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-log-service-worker-navigate.js
@@ -2,6 +2,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; import {NetworkTestRunner} from 'network_test_runner'; + +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult( `Verifies that the main page request repeated by a service worker appears in the network log.`); @@ -20,7 +22,7 @@ const requests = NetworkTestRunner.networkRequests(); for (const request of requests) { - const networkManager = SDK.NetworkManager.forRequest(request); + const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request); TestRunner.addResult('request.url(): ' + request.url()); TestRunner.addResult( 'request.target.type(): ' + networkManager ?
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-request-parse-query-params.js b/third_party/blink/web_tests/http/tests/devtools/network/network-request-parse-query-params.js index 841b797..0f3f32e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-request-parse-query-params.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-request-parse-query-params.js
@@ -5,13 +5,15 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests query string parsing.\n`); await TestRunner.showPanel('network'); function checkQuery(query) { var url = 'http://webkit.org?' + query; - var request = SDK.NetworkRequest.create(url, url, '', '', ''); + var request = SDK.NetworkRequest.NetworkRequest.create(url, url, '', '', ''); TestRunner.addResult('Query: ' + request.queryString()); var params = request.queryParameters; TestRunner.addResult('Parameters: ');
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-request-query-string.js b/third_party/blink/web_tests/http/tests/devtools/network/network-request-query-string.js index 2ae7306..6684e17 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-request-query-string.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-request-query-string.js
@@ -5,12 +5,14 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests query string extraction.\n`); await TestRunner.showPanel('network'); function checkURL(url) { - var request = SDK.NetworkRequest.create(url, url, '', '', ''); + var request = SDK.NetworkRequest.NetworkRequest.create(url, url, '', '', ''); TestRunner.addResult('URL: ' + url); TestRunner.addResult('Query: ' + request.queryString()); TestRunner.addResult('');
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-serviceworker-timing-view.js b/third_party/blink/web_tests/http/tests/devtools/network/network-serviceworker-timing-view.js index 82bf8dd8..45eb3bd9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-serviceworker-timing-view.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-serviceworker-timing-view.js
@@ -6,6 +6,8 @@ import {ApplicationTestRunner} from 'application_test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { 'use strict'; TestRunner.addResult(`Tests that serviceworker timings are displayed correctly.\n`); @@ -59,7 +61,7 @@ url: 'http://example.com/inspector-test.js', lineNumber: 117 }; - var testRequest = SDK.NetworkRequest.create( + var testRequest = SDK.NetworkRequest.NetworkRequest.create( 'testRequest', 'http://example.com/inspector-test.js', 'http://example.com/fake-document-url', 1, 1, fakeInitiator); setRequestValues(testRequest);
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-update-calculator-for-all-requests.js b/third_party/blink/web_tests/http/tests/devtools/network/network-update-calculator-for-all-requests.js index 7cfca55..88f9441 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-update-calculator-for-all-requests.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-update-calculator-for-all-requests.js
@@ -5,13 +5,16 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as Common from 'devtools/core/common/common.js'; +import * as Network from 'devtools/panels/network/network.js'; + (async function() { TestRunner.addResult(`Tests that time calculator is updated for both visible and hidden requests.\n`); await TestRunner.showPanel('network'); var target = UI.panels.network.networkLogView; - target.resourceCategoryFilterUI.toggleTypeFilter(Common.resourceTypes.XHR.category().title(), false); - TestRunner.addResult('Clicked \'' + Common.resourceTypes.XHR.name() + '\' button.'); + target.resourceCategoryFilterUI.toggleTypeFilter(Common.ResourceType.resourceTypes.XHR.category().title(), false); + TestRunner.addResult('Clicked \'' + Common.ResourceType.resourceTypes.XHR.name() + '\' button.'); target.reset(); function appendRequest(id, type, startTime, endTime) {
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/network-xhr-data-received-async-response-type-blob.js b/third_party/blink/web_tests/http/tests/devtools/network/network-xhr-data-received-async-response-type-blob.js index 4c151e0..46e5fe12 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/network-xhr-data-received-async-response-type-blob.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/network-xhr-data-received-async-response-type-blob.js
@@ -5,11 +5,13 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that dataReceived is called on NetworkDispatcher for XHR with responseType="blob".\n`); await TestRunner.showPanel('network'); - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'dataReceived', dataReceived); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'dataReceived', dataReceived); NetworkTestRunner.recordNetwork(); NetworkTestRunner.makeXHR(
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/parse-form-data.js b/third_party/blink/web_tests/http/tests/devtools/network/parse-form-data.js index 1912c795..bc28a2b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/parse-form-data.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/parse-form-data.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { function getHTMLWithEncType(values, encType) { const encTypeAttribute = encType ? ` enctype="${encType}"` : ''; @@ -22,14 +24,14 @@ async function runFormTest(values, encType) { await TestRunner.loadHTML(getHTMLWithEncType(values, encType)); - const snifferPromise = TestRunner.addSnifferPromise(SDK.NetworkDispatcher.prototype, 'requestWillBeSent'); + const snifferPromise = TestRunner.addSnifferPromise(SDK.NetworkManager.NetworkDispatcher.prototype, 'requestWillBeSent'); TestRunner.evaluateInPage('document.querySelector("form").submit();'); await snifferPromise; const networkRequests = NetworkTestRunner.networkRequests(); var request = networkRequests[networkRequests.length - 1]; if (request.url().endsWith('/')) { - await TestRunner.addSnifferPromise(SDK.NetworkDispatcher.prototype, 'requestWillBeSent'); + await TestRunner.addSnifferPromise(SDK.NetworkManager.NetworkDispatcher.prototype, 'requestWillBeSent'); request = NetworkTestRunner.networkRequests().pop(); } @@ -69,7 +71,7 @@ `--${newBoundary}\r\nContent-Disposition: form-data; name=\"a\r\nb\"\r\n\r\na\r\nv\r\n` + `--${newBoundary}\r\nContent-Disposition: form-data; name=\"a\r\nc\"; filename="a.gif"\r\nContent-Type: application/octer-stream\r\n\r\na\r\nv\r\n` + `--${newBoundary}--\r\n\u0000`; - const nonURLEncodedNameFormData = SDK.NetworkRequest.prototype.parseMultipartFormDataParameters(nonURLEncodedNameRequestBody, newBoundary); + const nonURLEncodedNameFormData = SDK.NetworkRequest.NetworkRequest.prototype.parseMultipartFormDataParameters(nonURLEncodedNameRequestBody, newBoundary); TestRunner.addResult(JSON.stringify(nonURLEncodedNameFormData, ' ', 1));
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/ping.js b/third_party/blink/web_tests/http/tests/devtools/network/ping.js index 185d36c..e74fbc0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/ping.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/ping.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult('Tests that hyperlink auditing (ping) requests appear in network panel') await TestRunner.showPanel('network'); @@ -20,14 +22,14 @@ } `); - const snifferPromise = TestRunner.addSnifferPromise(SDK.NetworkDispatcher.prototype, 'requestWillBeSent'); + const snifferPromise = TestRunner.addSnifferPromise(SDK.NetworkManager.NetworkDispatcher.prototype, 'requestWillBeSent'); TestRunner.evaluateInPage('navigateLink()'); await snifferPromise; const networkRequests = NetworkTestRunner.networkRequests(); var request = networkRequests[networkRequests.length - 1]; if (request.url().endsWith('/')) { - await TestRunner.addSnifferPromise(SDK.NetworkDispatcher.prototype, 'requestWillBeSent'); + await TestRunner.addSnifferPromise(SDK.NetworkManager.NetworkDispatcher.prototype, 'requestWillBeSent'); request = NetworkTestRunner.networkRequests().pop(); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/network/preview-searchable.js b/third_party/blink/web_tests/http/tests/devtools/network/preview-searchable.js index 7e58039..db8aed1d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/network/preview-searchable.js +++ b/third_party/blink/web_tests/http/tests/devtools/network/preview-searchable.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests that resources with JSON MIME types are previewed with the JSON viewer.\n`); await TestRunner.loadLegacyModule('source_frame'); @@ -91,7 +93,7 @@ var url = 'data:' + contentType + ',' + encodeURIComponent(content); NetworkTestRunner.makeSimpleXHR('GET', url, true, function() { var request = NetworkTestRunner.findRequestsByURLPattern(new RegExp(Platform.StringUtilities.escapeForRegExp(url)))[0]; - request.setResourceType(Common.resourceTypes.Document); + request.setResourceType(Common.ResourceType.resourceTypes.Document); trySearches(request, searches, callback); }); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-cookies-refresh.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-cookies-refresh.js index 82a25e01..608a5de 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-cookies-refresh.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-cookies-refresh.js
@@ -6,6 +6,8 @@ import {ApplicationTestRunner} from 'application_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that cookies are properly shown after oopif refresh`); await TestRunner.loadLegacyModule('console'); @@ -17,7 +19,7 @@ await TestRunner.showPanel('console'); await TestRunner.showPanel('resources'); - UI.panels.resources.showCookies(SDK.targetManager.rootTarget(), 'http://127.0.0.1:8000'); + UI.panels.resources.showCookies(SDK.TargetManager.TargetManager.instance().rootTarget(), 'http://127.0.0.1:8000'); await ApplicationTestRunner.waitForCookies(); await TestRunner.navigatePromise('resources/page-out.html');
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-inspect.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-inspect.js index ad443d7..637113ca 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-inspect.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-inspect.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that inspect request works for nested OOPIF elements.\n`); await TestRunner.loadLegacyModule('elements'); @@ -15,22 +17,22 @@ TestRunner.navigatePromise('resources/page-inspect.html'); - SDK.targetManager.observeTargets({ + SDK.TargetManager.TargetManager.instance().observeTargets({ targetAdded: async function(target) { - if (target === SDK.targetManager.rootTarget() || target === SDK.targetManager.primaryPageTarget()) + if (target === SDK.TargetManager.TargetManager.instance().rootTarget() || target === SDK.TargetManager.TargetManager.instance().primaryPageTarget()) return; let complete = false; target.pageAgent().setLifecycleEventsEnabled(true); - target.model(SDK.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { + target.model(SDK.ResourceTreeModel.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { if (event.data.name === 'load' && !complete) { complete = true; - target.model(SDK.RuntimeModel).defaultExecutionContext().evaluate({ + target.model(SDK.RuntimeModel.RuntimeModel).defaultExecutionContext().evaluate({ expression: 'inspect(document.body)', includeCommandLineAPI: true }, false, false); - UI.context.addFlavorChangeListener(SDK.DOMNode, (event) => { + UI.context.addFlavorChangeListener(SDK.DOMModel.DOMNode, (event) => { const treeOutline = Elements.ElementsTreeOutline.forDOMModel(event.data.domModel()); TestRunner.addResult(`Selected node has text: ${treeOutline.selectedDOMNode().children()[0].nodeName()}`); TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-in.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-in.js index cd034c7..63e1114 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-in.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-in.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that oopif iframes are rendered inline.\n`); await TestRunner.loadLegacyModule('elements'); @@ -15,12 +17,12 @@ await TestRunner.navigatePromise('resources/page-out.html'); - SDK.targetManager.observeTargets({ + SDK.TargetManager.TargetManager.instance().observeTargets({ targetAdded: async function(target) { if (!target.name().startsWith('inner')) return; target.pageAgent().setLifecycleEventsEnabled(true); - target.model(SDK.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { + target.model(SDK.ResourceTreeModel.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { if (event.data.name !== 'load') return; @@ -28,10 +30,10 @@ await ElementsTestRunner.expandAndDump(); // Navigate iframe to in-process - let rootTarget = SDK.targetManager.rootTarget(); - await rootTarget.model(SDK.ResourceTreeModel)._agent.setLifecycleEventsEnabled(true); + let rootTarget = SDK.TargetManager.TargetManager.instance().rootTarget(); + await rootTarget.model(SDK.ResourceTreeModel.ResourceTreeModel)._agent.setLifecycleEventsEnabled(true); TestRunner.evaluateInPagePromise(`document.getElementById('page-iframe').src = 'http://127.0.0.1:8000/devtools/oopif/resources/inner-iframe.html';`); - rootTarget.model(SDK.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { + rootTarget.model(SDK.ResourceTreeModel.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { if (event.data.name === 'load') { await ElementsTestRunner.expandAndDump(); TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-out.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-out.js index a7870b2..2117d36 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-out.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-elements-navigate-out.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that oopif iframes are rendered inline.\n`); await TestRunner.loadLegacyModule('elements'); @@ -19,12 +21,12 @@ TestRunner.evaluateInPagePromise(`document.getElementById('page-iframe').src = 'http://devtools.oopif.test:8000/devtools/oopif/resources/inner-iframe.html';`); - SDK.targetManager.observeTargets({ + SDK.TargetManager.TargetManager.instance().observeTargets({ targetAdded: async function(target) { - if (!target.model(SDK.ResourceTreeModel)) return; - target.model(SDK.ResourceTreeModel).agent.setLifecycleEventsEnabled(true); + if (!target.model(SDK.ResourceTreeModel.ResourceTreeModel)) return; + target.model(SDK.ResourceTreeModel.ResourceTreeModel).agent.setLifecycleEventsEnabled(true); let loadedModels = 0; - target.model(SDK.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { + target.model(SDK.ResourceTreeModel.ResourceTreeModel).addEventListener(SDK.ResourceTreeModel.Events.LifecycleEvent, async (event) => { if (event.data.name === 'load') { loadedModels++;
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-performance-monitor.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-performance-monitor.js index cbadaeeb..58ceb696 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-performance-monitor.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-performance-monitor.js
@@ -4,10 +4,12 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests stability of performance metrics list.\n`); - const model = SDK.targetManager.primaryPageTarget().model(SDK.PerformanceMetricsModel); + const model = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.PerformanceMetricsModel.PerformanceMetricsModel); await model.enable(); let metrics = (await model.requestMetrics()).metrics;
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-presentation-console-messages.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-presentation-console-messages.js index 18b6aa1..e1d1623 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-presentation-console-messages.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-presentation-console-messages.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Test that links to UISourceCode work correctly when navigating OOPIF`); @@ -53,7 +55,7 @@ TestRunner.addResult('Revealing iframe source'); await Common.Revealer.reveal(Workspace.workspace.uiSourceCodeForURL('http://devtools.oopif.test:8000/devtools/oopif/resources/empty.html')); TestRunner.addResult('\nClearing console'); - SDK.ConsoleModel.requestClearMessages(); + SDK.ConsoleModel.ConsoleModel.requestClearMessages(); dumpMessages(); TestRunner.completeTest(); })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-targets.js b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-targets.js index fa2ada2..b83278d8 100644 --- a/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-targets.js +++ b/third_party/blink/web_tests/http/tests/devtools/oopif/oopif-targets.js
@@ -4,19 +4,21 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that targets are created for oopif iframes.\n`); TestRunner.addResult('\nTargets before navigate'); - TestRunner.addResults(SDK.targetManager.targets().map(t => t.name()).sort()); + TestRunner.addResults(SDK.TargetManager.TargetManager.instance().targets().map(t => t.name()).sort()); await TestRunner.navigatePromise('resources/page.html'); TestRunner.addResult('\nTargets after navigate'); - TestRunner.addResults(SDK.targetManager.targets().map(t => t.name()).sort()); + TestRunner.addResults(SDK.TargetManager.TargetManager.instance().targets().map(t => t.name()).sort()); await TestRunner.navigatePromise('about:blank'); TestRunner.addResult('\nTargets on about:blank'); - TestRunner.addResults(SDK.targetManager.targets().map(t => t.name()).sort()); + TestRunner.addResults(SDK.TargetManager.TargetManager.instance().targets().map(t => t.name()).sort()); TestRunner.completeTest(); })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sane.js b/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sane.js index ad05e7a..85884d1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sane.js +++ b/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sane.js
@@ -5,18 +5,20 @@ import {TestRunner} from 'test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Verify that automapping is sane.\n`); var timestamp = new Date('December 1, 1989'); var index_html = { - contentType: Common.resourceTypes.Document, + contentType: Common.ResourceType.resourceTypes.Document, content: '<body>this is main resource</body>', time: timestamp }; var foo_js = {content: 'console.log(\'foo.js!\');', time: null}; var bar_css = { - contentType: Common.resourceTypes.Stylesheet, + contentType: Common.ResourceType.resourceTypes.Stylesheet, content: '* { box-sizing: border-box }', time: timestamp };
diff --git a/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sourcemap-nameclash.js b/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sourcemap-nameclash.js index 8e15c8c8..7e02c7b5 100644 --- a/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sourcemap-nameclash.js +++ b/third_party/blink/web_tests/http/tests/devtools/persistence/automapping-sourcemap-nameclash.js
@@ -6,6 +6,8 @@ import {BindingsTestRunner} from 'bindings_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult( `Verify that sourcemap sources are mapped event when sourcemap compiled url matches with one of the source urls.\n`); @@ -19,8 +21,8 @@ Promise .all([ - getResourceContent('out.js', Common.resourceTypes.Script), - getResourceContent('out.js', Common.resourceTypes.SourceMapScript), + getResourceContent('out.js', Common.ResourceType.resourceTypes.Script), + getResourceContent('out.js', Common.ResourceType.resourceTypes.SourceMapScript), ]) .then(onResourceContents);
diff --git a/third_party/blink/web_tests/http/tests/devtools/persistence/persistence-sync-content-nodejs.js b/third_party/blink/web_tests/http/tests/devtools/persistence/persistence-sync-content-nodejs.js index fa0ef02..51c6e00 100644 --- a/third_party/blink/web_tests/http/tests/devtools/persistence/persistence-sync-content-nodejs.js +++ b/third_party/blink/web_tests/http/tests/devtools/persistence/persistence-sync-content-nodejs.js
@@ -6,13 +6,15 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {BindingsTestRunner} from 'bindings_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that syncing Node.js contents works fine.\n`); await TestRunner.loadLegacyModule('sources'); var testMapping = BindingsTestRunner.initializeTestMapping(); // Pretend we are running under V8 front-end. - SDK.targetManager.primaryPageTarget().markAsNodeJSForTest(); + SDK.TargetManager.TargetManager.instance().primaryPageTarget().markAsNodeJSForTest(); var content = ['', '', 'var express = require("express");', '//TODO'].join('\n');
diff --git a/third_party/blink/web_tests/http/tests/devtools/portals/portals-console.js b/third_party/blink/web_tests/http/tests/devtools/portals/portals-console.js index 82b279f6..2e662b9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/portals/portals-console.js +++ b/third_party/blink/web_tests/http/tests/devtools/portals/portals-console.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the console works correctly with portals`); await TestRunner.loadLegacyModule('console'); @@ -13,12 +15,12 @@ await TestRunner.navigatePromise('resources/append-predecessor-host.html'); async function setContextLabel(target, label) { - var runtimeModel = target.model(SDK.RuntimeModel); + var runtimeModel = target.model(SDK.RuntimeModel.RuntimeModel); await TestRunner.waitForExecutionContext(runtimeModel); runtimeModel.executionContexts()[0].setLabel(label); } - var targets = SDK.targetManager.targets(); + var targets = SDK.TargetManager.TargetManager.instance().targets(); TestRunner.assertEquals(2, targets.length); TestRunner.runTestSuite([ @@ -52,11 +54,11 @@ async function activate(next) { TestRunner.evaluateInPage('activate()'); - await TestRunner.waitForTargetRemoved(SDK.targetManager.rootTarget()); + await TestRunner.waitForTargetRemoved(SDK.TargetManager.TargetManager.instance().rootTarget()); await TestRunner.waitForTarget(); - await TestRunner.waitForTarget(target => target != SDK.targetManager.rootTarget()); + await TestRunner.waitForTarget(target => target != SDK.TargetManager.TargetManager.instance().rootTarget()); await TestRunner.waitForExecutionContext(TestRunner.runtimeModel); - targets = SDK.targetManager.targets(); + targets = SDK.TargetManager.TargetManager.instance().targets(); next(); },
diff --git a/third_party/blink/web_tests/http/tests/devtools/portals/portals-elements-activate.js b/third_party/blink/web_tests/http/tests/devtools/portals/portals-elements-activate.js index ec4c405..8b5bcdd 100644 --- a/third_party/blink/web_tests/http/tests/devtools/portals/portals-elements-activate.js +++ b/third_party/blink/web_tests/http/tests/devtools/portals/portals-elements-activate.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ElementsTestRunner} from 'elements_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that element tree is updated after activation.\n`); @@ -18,7 +20,7 @@ TestRunner.runTestSuite([ function testSetUp(next) { - TestRunner.assertEquals(2, SDK.targetManager.targets().length); + TestRunner.assertEquals(2, SDK.TargetManager.TargetManager.instance().targets().length); ElementsTestRunner.expandElementsTree(() => { ElementsTestRunner.dumpElementsTree(); next(); @@ -28,7 +30,7 @@ async function testActivate(next) { TestRunner.evaluateInPage( 'setTimeout(() => {document.querySelector(\'portal\').activate();})'); - const rootTarget = SDK.targetManager.rootTarget(); + const rootTarget = SDK.TargetManager.TargetManager.instance().rootTarget(); await TestRunner.waitForEvent( Host.InspectorFrontendHostAPI.Events.ReattachRootTarget, Host.InspectorFrontendHost.events); @@ -36,7 +38,7 @@ }, function testAfterActivate(next) { - TestRunner.assertEquals(1, SDK.targetManager.targets().length); + TestRunner.assertEquals(1, SDK.TargetManager.TargetManager.instance().targets().length); ElementsTestRunner.expandElementsTree(() => { ElementsTestRunner.dumpElementsTree(); TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-large-tree-search.js b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-large-tree-search.js index 342a04a..c0007ba 100644 --- a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-large-tree-search.js +++ b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-large-tree-search.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {CPUProfilerTestRunner} from 'cpu_profiler_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that search works for large bottom-up view of CPU profile.\n`); await TestRunner.loadLegacyModule('profiler'); @@ -27,9 +29,9 @@ var profileAndExpectations = { 'title': 'profile1', 'target': function() { - return SDK.targetManager.targets()[0]; + return SDK.TargetManager.TargetManager.instance().targets()[0]; }, - 'profileModel': () => new SDK.CPUProfileDataModel({ + 'profileModel': () => new SDK.CPUProfileDataModel.CPUProfileDataModel({ 'nodes': [ { 'id': 0,
diff --git a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-times.js b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-times.js index 53ac3d6..a0e855b7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-times.js +++ b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-bottom-up-times.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {CPUProfilerTestRunner} from 'cpu_profiler_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests bottom-up view self and total time calculation in CPU profiler.\n`); await TestRunner.loadLegacyModule('profiler'); @@ -12,9 +14,9 @@ var profileAndExpectations = { 'title': 'profile1', 'target': function() { - return SDK.targetManager.targets()[0]; + return SDK.TargetManager.TargetManager.instance().targets()[0]; }, - 'profileModel': () => new SDK.CPUProfileDataModel({ + 'profileModel': () => new SDK.CPUProfileDataModel.CPUProfileDataModel({ 'nodes': [ { 'id': 0,
diff --git a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-flame-chart-overview.js b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-flame-chart-overview.js index 0f334da..1c42c4e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-flame-chart-overview.js +++ b/third_party/blink/web_tests/http/tests/devtools/profiler/cpu-profiler-flame-chart-overview.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {CPUProfilerTestRunner} from 'cpu_profiler_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests Overview pane calculation in FlameChart for different width = 2^n with n in range 4 - 0. @@ -854,7 +856,7 @@ profileAndExpectations.debuggerModel = null; profileAndExpectations.debuggerModel = () => null; profileAndExpectations.weakTarget = () => new WeakReference(null); - profileAndExpectations.profileModel = () => new SDK.CPUProfileDataModel(profile); + profileAndExpectations.profileModel = () => new SDK.CPUProfileDataModel.CPUProfileDataModel(profile); var cpuProfileView = new Profiler.CPUProfileView(profileAndExpectations); cpuProfileView.viewSelectComboBox.setSelectedIndex(0); cpuProfileView.changeView();
diff --git a/third_party/blink/web_tests/http/tests/devtools/profiler/heap-snapshot-loader.js b/third_party/blink/web_tests/http/tests/devtools/profiler/heap-snapshot-loader.js index 347161d2..dab0064 100644 --- a/third_party/blink/web_tests/http/tests/devtools/profiler/heap-snapshot-loader.js +++ b/third_party/blink/web_tests/http/tests/devtools/profiler/heap-snapshot-loader.js
@@ -6,6 +6,7 @@ import {HeapProfilerTestRunner} from 'heap_profiler_test_runner'; import * as Common from 'devtools/core/common/common.js'; +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult(`This test checks HeapSnapshots loader.\n`); @@ -16,7 +17,7 @@ var partSize = sourceStringified.length >> 3; async function injectMockProfile(callback) { - var heapProfilerModel = TestRunner.mainTarget.model(SDK.HeapProfilerModel); + var heapProfilerModel = TestRunner.mainTarget.model(SDK.HeapProfilerModel.HeapProfilerModel); var panel = UI.panels.heap_profiler; panel.reset(); @@ -43,8 +44,8 @@ TestRunner.addSniffer( Profiler.HeapProfileHeader.prototype, 'didWriteToTempFile', tempFileReady); - if (!UI.context.flavor(SDK.HeapProfilerModel)) { - await new Promise(resolve => UI.context.addFlavorChangeListener(SDK.HeapProfilerModel, resolve)); + if (!UI.context.flavor(SDK.HeapProfilerModel.HeapProfilerModel)) { + await new Promise(resolve => UI.context.addFlavorChangeListener(SDK.HeapProfilerModel.HeapProfilerModel, resolve)); } profileType.takeHeapSnapshot(); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/profiler/sampling-profiler-basic.js b/third_party/blink/web_tests/http/tests/devtools/profiler/sampling-profiler-basic.js index cd053453..8add400 100644 --- a/third_party/blink/web_tests/http/tests/devtools/profiler/sampling-profiler-basic.js +++ b/third_party/blink/web_tests/http/tests/devtools/profiler/sampling-profiler-basic.js
@@ -4,11 +4,13 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the sampling heap profiler works and supports nesting.\n`); await TestRunner.loadLegacyModule('profiler'); - const profiler = SDK.targetManager.primaryPageTarget().model(SDK.HeapProfilerModel); + const profiler = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.HeapProfilerModel.HeapProfilerModel); await profiler.startSampling(); await profiler.startSampling(); await TestRunner.evaluateInPagePromise(`let dump = new Array(5e4).fill(42.42)`);
diff --git a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js index 7a7dd171..c2510cd 100644 --- a/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js +++ b/third_party/blink/web_tests/http/tests/devtools/report-protocol-errors.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that InspectorBackendDispatcher is catching incorrect messages.\n`); @@ -15,7 +17,7 @@ } - const frameTargetSession = SDK.targetManager.primaryPageTarget().sessionId; + const frameTargetSession = SDK.TargetManager.TargetManager.instance().primaryPageTarget().sessionId; var messages = [ 'some wrong string',
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-har-conversion.js b/third_party/blink/web_tests/http/tests/devtools/resource-har-conversion.js index b2c95e1..da7ff68 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-har-conversion.js +++ b/third_party/blink/web_tests/http/tests/devtools/resource-har-conversion.js
@@ -6,6 +6,8 @@ import {NetworkTestRunner} from 'network_test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests conversion of Inspector's resource representation into HAR format.\n`); await TestRunner.loadLegacyModule('console'); @@ -24,14 +26,14 @@ } function addCookieHeadersToRequest(request) { - const c1 = new SDK.Cookie('a', 'b'); + const c1 = new SDK.Cookie.Cookie('a', 'b'); c1.addAttribute('path', '/path'); c1.addAttribute('domain', 'example.com'); request.addExtraRequestInfo({ includedRequestCookies: [ c1, - new SDK.Cookie('a1', 'b1'), - new SDK.Cookie('c1', 'd1'), + new SDK.Cookie.Cookie('a1', 'b1'), + new SDK.Cookie.Cookie('c1', 'd1'), ], blockedRequestCookies: [], requestHeaders: [{name: 'version', value: 'HTTP/1.1'}],
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-har-headers.js b/third_party/blink/web_tests/http/tests/devtools/resource-har-headers.js index 76a635d..22a044d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-har-headers.js +++ b/third_party/blink/web_tests/http/tests/devtools/resource-har-headers.js
@@ -6,6 +6,9 @@ import {ApplicationTestRunner} from 'application_test_runner'; import {NetworkTestRunner} from 'network_test_runner'; +import * as Common from 'devtools/core/common/common.js'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { 'use strict'; TestRunner.addResult(`Tests the nondeterministic bits of HAR conversion via the magic of hard-coded values.\n`); @@ -29,7 +32,7 @@ request.resourceSize = 1000; request.setTransferSize(539); // 39 = header size at the end of the day request.setPriority('VeryHigh'); - request.setResourceType(Common.resourceTypes.Fetch); + request.setResourceType(Common.ResourceType.resourceTypes.Fetch); // sample timing values used here are copied from a real request request.setIssueTime(357904.060558); @@ -59,7 +62,7 @@ url: 'http://example.com/inspector-test.js', lineNumber: 117 }; - var testRequest = SDK.NetworkRequest.create( + var testRequest = SDK.NetworkRequest.NetworkRequest.create( 'testRequest', 'http://example.com/inspector-test.js', 'http://example.com/fake-document-url', 1, 1, fakeInitiator); setRequestValues(testRequest);
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-tree/iframe-main-resource.js b/third_party/blink/web_tests/http/tests/devtools/resource-tree/iframe-main-resource.js index 66db142cc..74c70a8 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-tree/iframe-main-resource.js +++ b/third_party/blink/web_tests/http/tests/devtools/resource-tree/iframe-main-resource.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that iframe's main resource is reported only once.\n`); await TestRunner.loadLegacyModule('console'); @@ -18,7 +20,7 @@ })(); `); - var resourceTreeModel = new SDK.ResourceTreeModel(TestRunner.mainTarget); + var resourceTreeModel = new SDK.ResourceTreeModel.ResourceTreeModel(TestRunner.mainTarget); var resources = []; resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded, event => resources.push(event.data)); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded, function() {
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-request-content-while-loading.js b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-request-content-while-loading.js index a7dd30468..877ba84 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-request-content-while-loading.js +++ b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-request-content-while-loading.js
@@ -5,13 +5,15 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests resource content is correctly loaded if Resource.requestContent was called before network request was finished. https://bugs.webkit.org/show_bug.cgi?id=90153\n`); await TestRunner.loadLegacyModule('console'); await TestRunner.showPanel('resources'); - TestRunner.addSniffer(SDK.ResourceTreeFrame.prototype, 'addRequest', requestAdded, true); + TestRunner.addSniffer(SDK.ResourceTreeModel.ResourceTreeFrame.prototype, 'addRequest', requestAdded, true); TestRunner.addSniffer(TestRunner.PageAgent, 'getResourceContent', pageAgentGetResourceContentCalled, true); TestRunner.evaluateInPageAsync(` (function loadStylesheet() {
diff --git a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-invalid-mime-type-css-content.js b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-invalid-mime-type-css-content.js index 87b081f..9b764ba 100644 --- a/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-invalid-mime-type-css-content.js +++ b/third_party/blink/web_tests/http/tests/devtools/resource-tree/resource-tree-invalid-mime-type-css-content.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult( `Tests that content is correctly shown for css loaded with invalid mime type in quirks mode. https://bugs.webkit.org/show_bug.cgi?id=80528\n`); @@ -19,7 +21,7 @@ }); TestRunner.addResult(cssResource.url); TestRunner.assertEquals( - cssResource.resourceType(), Common.resourceTypes.Stylesheet, 'Resource type should be Stylesheet.'); + cssResource.resourceType(), Common.ResourceType.resourceTypes.Stylesheet, 'Resource type should be Stylesheet.'); TestRunner.assertTrue(!cssResource.failed, 'Resource loading failed.'); const {isEncoded} = await cssResource.requestContent();
diff --git a/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-timeout.js b/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-timeout.js index e6bc0f36..ab1418b1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-timeout.js +++ b/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-timeout.js
@@ -5,11 +5,13 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.loadLegacyModule('sources'); TestRunner.addResult("Test frontend's timeout support.\n"); - const executionContext = UI.context.flavor(SDK.ExecutionContext); + const executionContext = UI.context.flavor(SDK.RuntimeModel.ExecutionContext); const regularExpression = '1 + 1'; const infiniteExpression = 'while (1){}';
diff --git a/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-without-side-effects.js b/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-without-side-effects.js index 4a6be195..863f594 100644 --- a/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-without-side-effects.js +++ b/third_party/blink/web_tests/http/tests/devtools/runtime/evaluate-without-side-effects.js
@@ -5,11 +5,13 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { await TestRunner.loadLegacyModule('sources'); TestRunner.addResult("Test frontend's side-effect support check for compatibility.\n"); - const executionContext = UI.context.flavor(SDK.ExecutionContext); + const executionContext = UI.context.flavor(SDK.RuntimeModel.ExecutionContext); const expressionWithSideEffect = '(async function(){ await 1; })()'; const expressionWithoutSideEffect = '1 + 1';
diff --git a/third_party/blink/web_tests/http/tests/devtools/runtime/runtime-evaluate-bad-unicode.js b/third_party/blink/web_tests/http/tests/devtools/runtime/runtime-evaluate-bad-unicode.js index 7f5807a4..306156c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/runtime/runtime-evaluate-bad-unicode.js +++ b/third_party/blink/web_tests/http/tests/devtools/runtime/runtime-evaluate-bad-unicode.js
@@ -4,11 +4,13 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests TestRunner.RuntimeAgent.evaluate can handle invalid Unicode code points and non-characters.\n`); async function test(expression) { - const executionContext = UI.context.flavor(SDK.ExecutionContext); + const executionContext = UI.context.flavor(SDK.RuntimeModel.ExecutionContext); const compileResult = await executionContext.runtimeModel.compileScript(expression, '', true, executionContext.id); const runResult = await executionContext.runtimeModel.runScript(compileResult.scriptId, executionContext.id); TestRunner.addResult(`"${expression}" -> ${runResult.object.value}`);
diff --git a/third_party/blink/web_tests/http/tests/devtools/search/search-in-static.js b/third_party/blink/web_tests/http/tests/devtools/search/search-in-static.js index d05bec9a..a485ef86f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/search/search-in-static.js +++ b/third_party/blink/web_tests/http/tests/devtools/search/search-in-static.js
@@ -6,6 +6,8 @@ import {ApplicationTestRunner} from 'application_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests static content provider search.\n`); await TestRunner.loadLegacyModule('console'); @@ -24,7 +26,7 @@ } async function step3() { - staticContentProvider = TextUtils.StaticContentProvider.fromString('', Common.resourceTypes.Script, resource.content); + staticContentProvider = TextUtils.StaticContentProvider.fromString('', Common.ResourceType.resourceTypes.Script, resource.content); TestRunner.addResult(resource.url); var text = 'searchTestUniqueString';
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/blank-origins-not-shown.js b/third_party/blink/web_tests/http/tests/devtools/security/blank-origins-not-shown.js index fd2d09e..5303fce2 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/blank-origins-not-shown.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/blank-origins-not-shown.js
@@ -5,15 +5,17 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that blank origins aren't shown in the security panel origins list.\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/foo.jpg', 'https://foo.test', 0, 0, null); SecurityTestRunner.dispatchRequestFinished(request1); - var request2 = SDK.NetworkRequest.create( + var request2 = SDK.NetworkRequest.NetworkRequest.create( 0, 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAKCAYAAABmBXS+AAAAPElEQVR42mNgQAMZGRn/GfABkIIdO3b8x6kQpgAEsCpEVgADKAqxKcBQCCLwARRFIBodYygiyiSCighhAO4e2jskhrm3AAAAAElFTkSuQmCC', 'https://foo.test', 0, 0, null);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/blocked-mixed-content.js b/third_party/blink/web_tests/http/tests/devtools/security/blocked-mixed-content.js index 29cd666..a82b252 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/blocked-mixed-content.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/blocked-mixed-content.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests active mixed content blocking in the security panel.\n`); await TestRunner.showPanel('security'); @@ -16,7 +18,7 @@ Protocol.Security.SecurityState.Neutral, /* certificateSecurityState= */ null, /* safetyTipInfo= */ null, /* securityStateIssueIds= */ ['scheme-is-not-cryptographic'])); - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); request.setBlockedReason(Protocol.Network.BlockedReason.MixedContent); request.mixedContentType = 'blockable';
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/failed-request.js b/third_party/blink/web_tests/http/tests/devtools/security/failed-request.js index 23e1c47..d16c4b09 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/failed-request.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/failed-request.js
@@ -5,17 +5,19 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that origins with failed requests are shown correctly in the security panel origins list.\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/foo.jpg', 'https://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Secure); SecurityTestRunner.dispatchRequestFinished(request1); - var request2 = SDK.NetworkRequest.create( + var request2 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://does-not-resolve.test', 'https://does-not-resolve.test', 0, 0, null); // Leave the security state unknown.
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/interstitial-sidebar.js b/third_party/blink/web_tests/http/tests/devtools/security/interstitial-sidebar.js index 73cdce9..bf6422d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/interstitial-sidebar.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/interstitial-sidebar.js
@@ -5,17 +5,19 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the sidebar origin list disappears and appers when an interstitial is shown or hidden.\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/', 'https://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Secure); SecurityTestRunner.dispatchRequestFinished(request1); - var request2 = SDK.NetworkRequest.create( + var request2 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://bar.test/foo.jpg', 'https://bar.test', 0, 0, null); request2.setSecurityState(Protocol.Security.SecurityState.Secure); SecurityTestRunner.dispatchRequestFinished(request2); @@ -24,10 +26,10 @@ TestRunner.dumpDeepInnerHTML(Security.SecurityPanel.instance().sidebarTree.element); // Test that the sidebar is hidden when an interstitial is shown. https://crbug.com/559150 - TestRunner.mainTarget.model(SDK.ResourceTreeModel) + TestRunner.mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel) .dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialShown); // Simulate a request finishing after the interstitial is shown, to make sure that doesn't show up in the sidebar. - var request3 = SDK.NetworkRequest.create( + var request3 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://bar.test/foo.jpg', 'https://bar.test', 0, 0, null); request3.setSecurityState(Protocol.Security.SecurityState.Unknown); SecurityTestRunner.dispatchRequestFinished(request3); @@ -35,7 +37,7 @@ TestRunner.dumpDeepInnerHTML(Security.SecurityPanel.instance().sidebarTree.element); // Test that the sidebar is shown again when the interstitial is hidden. https://crbug.com/559150 - TestRunner.mainTarget.model(SDK.ResourceTreeModel) + TestRunner.mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel) .dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialHidden); TestRunner.addResult('After interstitial is hidden:'); TestRunner.dumpDeepInnerHTML(Security.SecurityPanel.instance().sidebarTree.element);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-active-and-passive-reload.js b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-active-and-passive-reload.js index 26ea69e3..9b15b15 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-active-and-passive-reload.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-active-and-passive-reload.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the active and passive mixed content explanations prompt the user to refresh when there are no recorded requests, and link to the network panel when there are recorded requests.\n`); @@ -34,12 +36,12 @@ Security.SecurityModel.Events.VisibleSecurityStateChanged, pageVisibleSecurityState); - var passive = SDK.NetworkRequest.create( + var passive = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); passive.mixedContentType = 'optionally-blockable'; SecurityTestRunner.dispatchRequestFinished(passive); - var active = SDK.NetworkRequest.create( + var active = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); active.mixedContentType = 'blockable'; SecurityTestRunner.dispatchRequestFinished(active);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-reload.js b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-reload.js index e27b24f..de2f9a28 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-reload.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-reload.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the mixed content explanation prompts the user to refresh when there are no recorded requests, and links to the network panel when there are recorded requests.\n`); @@ -34,7 +36,7 @@ Security.SecurityModel.Events.VisibleSecurityStateChanged, pageVisibleSecurityState); - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); request.mixedContentType = 'optionally-blockable'; SecurityTestRunner.dispatchRequestFinished(request);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-sidebar.js b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-sidebar.js index 77a897fc..086d7e9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-sidebar.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/mixed-content-sidebar.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the sidebar uses the correct styling for mixed content subresources.\n`); @@ -18,12 +20,12 @@ Security.SecurityModel.Events.VisibleSecurityStateChanged, pageVisibleSecurityState); - var passive = SDK.NetworkRequest.create( + var passive = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); passive.mixedContentType = 'optionally-blockable'; SecurityTestRunner.dispatchRequestFinished(passive); - var active = SDK.NetworkRequest.create( + var active = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://bar.test', 'https://bar.test', 0, 0, null); active.mixedContentType = 'blockable'; SecurityTestRunner.dispatchRequestFinished(active);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-ct-compliance.js b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-ct-compliance.js index c2af8d9..da74e16 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-ct-compliance.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-ct-compliance.js
@@ -5,12 +5,14 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the panel includes Certificate Transparency compliance status\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/', 'https://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Secure); let securityDetails = {};
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-noncryptographic-secure-origin.js b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-noncryptographic-secure-origin.js index b76300a..adb366c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-noncryptographic-secure-origin.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-noncryptographic-secure-origin.js
@@ -5,12 +5,14 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the panel shows the correct text for non-cryptographic secure origins\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'chrome-test://test', 'chrome-test://test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Secure); SecurityTestRunner.dispatchRequestFinished(request1);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-then-interstitial.js b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-then-interstitial.js index 5f91868..2e508d0d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/origin-view-then-interstitial.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/origin-view-then-interstitial.js
@@ -5,12 +5,14 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that the panel transitions to the overview view when navigating to an interstitial. Regression test for https://crbug.com/638601\n`); await TestRunner.showPanel('security'); - var request1 = SDK.NetworkRequest.create( + var request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test/', 'http://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Insecure); SecurityTestRunner.dispatchRequestFinished(request1); @@ -24,7 +26,7 @@ TestRunner.dumpDeepInnerHTML(Security.SecurityPanel.instance().visibleView.contentElement); // Test that the panel transitions to an origin view when an interstitial is shown. https://crbug.com/559150 - TestRunner.mainTarget.model(SDK.ResourceTreeModel) + TestRunner.mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel) .dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialShown); TestRunner.addResult('After interstitial is shown:'); TestRunner.dumpDeepInnerHTML(Security.SecurityPanel.instance().visibleView.contentElement);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/security-blocked-mixed-content.js b/third_party/blink/web_tests/http/tests/devtools/security/security-blocked-mixed-content.js index a28e4a1..fea4f52 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/security-blocked-mixed-content.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/security-blocked-mixed-content.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests active mixed content blocking in the security panel.\n`); await TestRunner.showPanel('security'); @@ -16,7 +18,7 @@ Protocol.Security.SecurityState.Secure, /* certificateSecurityState= */ null, /* safetyTipInfo */ null, /* securityStateIssueIds= */ ['scheme-is-not-cryptographic'])); - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); request.setBlockedReason(Protocol.Network.BlockedReason.MixedContent); request.mixedContentType = 'blockable'; @@ -28,7 +30,7 @@ TestRunner.dumpDeepInnerHTML(explanations[i]); // Test that the explanations are cleared on navigation. Regression test for https://crbug.com/601944. - TestRunner.mainTarget.model(SDK.ResourceTreeModel) + TestRunner.mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel) .dispatchEventToListeners( SDK.ResourceTreeModel.Events.PrimaryPageChanged, {frame: TestRunner.resourceTreeModel.mainFrame, type: 'Navigation'}); explanations =
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/security-details-updated-with-security-state.js b/third_party/blink/web_tests/http/tests/devtools/security/security-details-updated-with-security-state.js index 869773b..8315836 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/security-details-updated-with-security-state.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/security-details-updated-with-security-state.js
@@ -5,24 +5,26 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that the security details for an origin are updated if its security state changes.\n`); await TestRunner.showPanel('security'); // Add a request without security details. - const request1 = SDK.NetworkRequest.create( + const request1 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/foo.jpg', 'https://foo.test', 0, 0, null); request1.setSecurityState(Protocol.Security.SecurityState.Unknown); SecurityTestRunner.dispatchRequestFinished(request1); // Add an unrelated request. - const request2 = SDK.NetworkRequest.create( + const request2 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://bar.test/bar.jpg', 'https://bar.test', 0, 0, null); request2.setSecurityState(Protocol.Security.SecurityState.Unknown); SecurityTestRunner.dispatchRequestFinished(request2); // Add a request to the first origin, this time including security details. - const request3 = SDK.NetworkRequest.create( + const request3 = SDK.NetworkRequest.NetworkRequest.create( 0, 'https://foo.test/foo2.jpg', 'https://foo.test', 0, 0, null); request3.setSecurityState(Protocol.Security.SecurityState.Secure); let securityDetails = {}; @@ -43,7 +45,7 @@ SecurityTestRunner.dispatchRequestFinished(request3); // Add a request with both keyExchange and keyExchangeGroup (TLS 1.2 ECDHE), and with empty MAC (an AEAD cipher). - const request4 = SDK.NetworkRequest.create(0, 'https://ecdhe.foo.test/foo2.jpg', 'https://ecdhe.foo.test', 0, 0, null); + const request4 = SDK.NetworkRequest.NetworkRequest.create(0, 'https://ecdhe.foo.test/foo2.jpg', 'https://ecdhe.foo.test', 0, 0, null); request4.setSecurityState(Protocol.Security.SecurityState.Secure); securityDetails = {}; securityDetails.protocol = 'TLS 1.2'; @@ -64,7 +66,7 @@ SecurityTestRunner.dispatchRequestFinished(request4); // Add a request with only keyExchangeGroup (TLS 1.3). - const request5 = SDK.NetworkRequest.create(0, 'https://tls13.foo.test/foo2.jpg', 'https://tls13.foo.test', 0, 0, null); + const request5 = SDK.NetworkRequest.NetworkRequest.create(0, 'https://tls13.foo.test/foo2.jpg', 'https://tls13.foo.test', 0, 0, null); request5.setSecurityState(Protocol.Security.SecurityState.Secure); securityDetails = {}; securityDetails.protocol = 'TLS 1.3'; @@ -85,7 +87,7 @@ SecurityTestRunner.dispatchRequestFinished(request5); // Add a request with ECH. - const request6 = SDK.NetworkRequest.create(0, 'https://ech.foo.test/foo2.jpg', 'https://ech.foo.test', 0, 0, null); + const request6 = SDK.NetworkRequest.NetworkRequest.create(0, 'https://ech.foo.test/foo2.jpg', 'https://ech.foo.test', 0, 0, null); request6.setSecurityState(Protocol.Security.SecurityState.Secure); securityDetails = {}; securityDetails.protocol = 'TLS 1.3';
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/security-explanation-ordering.js b/third_party/blink/web_tests/http/tests/devtools/security/security-explanation-ordering.js index 750a392..3ca5772 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/security-explanation-ordering.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/security-explanation-ordering.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that info explanations are placed after regular explanations.\n`); await TestRunner.showPanel('security'); @@ -40,7 +42,7 @@ Security.SecurityModel.Events.VisibleSecurityStateChanged, pageVisibleSecurityState); - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://foo.test', 'https://foo.test', 0, 0, null); SecurityTestRunner.dispatchRequestFinished(request);
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/security-unknown-resource.js b/third_party/blink/web_tests/http/tests/devtools/security/security-unknown-resource.js index 3432c92c..23906c7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/security-unknown-resource.js +++ b/third_party/blink/web_tests/http/tests/devtools/security/security-unknown-resource.js
@@ -5,12 +5,14 @@ import {TestRunner} from 'test_runner'; import {SecurityTestRunner} from 'security_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that requests to unresolved origins result in unknown security state and show up in the sidebar origin list.\n`); await TestRunner.showPanel('security'); - var request = SDK.NetworkRequest.create( + var request = SDK.NetworkRequest.NetworkRequest.create( 0, 'http://unknown', 'https://foo.test', 0, 0, null); SecurityTestRunner.dispatchRequestFinished(request);
diff --git a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-agents.js b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-agents.js index 976c3a1..4dfbe97 100644 --- a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-agents.js +++ b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-agents.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests the way service workers don't enable DOM agent and does enable Debugger agent.\n`); await TestRunner.loadLegacyModule('console'); @@ -16,9 +18,9 @@ var scriptURL = 'http://127.0.0.1:8000/devtools/service-workers/resources/service-worker-empty.js'; var scope = 'http://127.0.0.1:8000/devtools/service-workers/resources/scope1/'; - TestRunner.addSniffer(SDK.MainConnection.prototype, 'sendRawMessage', function(messageString) { + TestRunner.addSniffer(SDK.Connections.MainConnection.prototype, 'sendRawMessage', function(messageString) { var message = JSON.parse(messageString); - if (!message.sessionId || message.sessionId === SDK.targetManager.primaryPageTarget().sessionId) + if (!message.sessionId || message.sessionId === SDK.TargetManager.TargetManager.instance().primaryPageTarget().sessionId) return; if (messageString.includes('DOM.')) TestRunner.addResult('DOM-related command should NOT be issued: ' + messageString); @@ -35,9 +37,9 @@ async function step1(target) { TestRunner.addResult('Suspending targets.'); - await SDK.targetManager.suspendAllTargets(); + await SDK.TargetManager.TargetManager.instance().suspendAllTargets(); TestRunner.addResult('Resuming targets.'); - await SDK.targetManager.resumeAllTargets(); + await SDK.TargetManager.TargetManager.instance().resumeAllTargets(); TestRunner.completeTest(); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-manager.js b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-manager.js index de9888a..6b361cb 100644 --- a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-manager.js +++ b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-worker-manager.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests the way service worker manager manages targets.\n`); await TestRunner.loadLegacyModule('console'); @@ -17,12 +19,12 @@ var scope = 'http://127.0.0.1:8000/devtools/service-workers/resources/scope1/'; ApplicationTestRunner.registerServiceWorker(scriptURL, scope); - SDK.targetManager.observeTargets({ + SDK.TargetManager.TargetManager.instance().observeTargets({ targetAdded: function(target) { TestRunner.addResult('Target added: ' + target.name() + '; type: ' + target.type()); if (target.type() === SDK.Target.Type.ServiceWorker) { - var serviceWorkerManager = SDK.targetManager.primaryPageTarget().model(SDK.ServiceWorkerManager); - // Allow agents to do rountrips. + var serviceWorkerManager = SDK.TargetManager.TargetManager.instance().primaryPageTarget().model(SDK.ServiceWorkerManager.ServiceWorkerManager); + // Allow agents to do roundtrips. TestRunner.deprecatedRunAfterPendingDispatches(function() { for (var registration of serviceWorkerManager.registrations().values()) serviceWorkerManager.deleteRegistration(registration.id)
diff --git a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-workers-navigation-preload.js b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-workers-navigation-preload.js index e8888b96..1c36681 100644 --- a/third_party/blink/web_tests/http/tests/devtools/service-workers/service-workers-navigation-preload.js +++ b/third_party/blink/web_tests/http/tests/devtools/service-workers/service-workers-navigation-preload.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {ApplicationTestRunner} from 'application_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests the navigation request related events are available in the DevTools\n`); await TestRunner.loadLegacyModule('console'); @@ -52,10 +54,10 @@ } } - SDK.targetManager.addModelListener(SDK.NetworkManager, SDK.NetworkManager.Events.RequestStarted, onRequestStarted); - SDK.targetManager.addModelListener( - SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived); - SDK.targetManager.addModelListener(SDK.NetworkManager, SDK.NetworkManager.Events.RequestFinished, onRequestFinished); + SDK.TargetManager.TargetManager.instance().addModelListener(SDK.NetworkManager.NetworkManager, SDK.NetworkManager.Events.RequestStarted, onRequestStarted); + SDK.TargetManager.TargetManager.instance().addModelListener( + SDK.NetworkManager.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived); + SDK.TargetManager.TargetManager.instance().addModelListener(SDK.NetworkManager.NetworkManager, SDK.NetworkManager.Events.RequestFinished, onRequestFinished); ApplicationTestRunner.registerServiceWorker(scriptURL, scope) .then(_ => ApplicationTestRunner.waitForActivated(scope))
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/event-listener-breakpoints-after-suspension.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/event-listener-breakpoints-after-suspension.js index 08ea10b7..1f38097 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/event-listener-breakpoints-after-suspension.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/event-listener-breakpoints-after-suspension.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests event listener breakpoints.\n`); await TestRunner.loadLegacyModule('sources'); await TestRunner.loadLegacyModule('panels/browser_debugger'); @@ -41,13 +43,13 @@ function suspendAll() { TestRunner.addResult('Suspend all targets'); - SDK.targetManager.suspendAllTargets(); + SDK.TargetManager.TargetManager.instance().suspendAllTargets(); TestRunner.deprecatedRunAfterPendingDispatches(resumeAll); } function resumeAll() { TestRunner.addResult('Resume all targets'); - SDK.targetManager.resumeAllTargets(); + SDK.TargetManager.TargetManager.instance().resumeAllTargets(); SourcesTestRunner.waitUntilPaused(finish); TestRunner.evaluateInPageWithTimeout('addListenerAndClick()'); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/nodejs-set-breakpoint.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/nodejs-set-breakpoint.js index e0e005b..db0cd55 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/nodejs-set-breakpoint.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-breakpoints/nodejs-set-breakpoint.js
@@ -6,15 +6,17 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {SDKTestRunner} from 'sdk_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Verify that front-end is able to set breakpoint for node.js scripts.\n`); await TestRunner.loadLegacyModule('sources'); await TestRunner.showPanel('sources'); - SDK.targetManager.rootTarget().markAsNodeJSForTest(); + SDK.TargetManager.TargetManager.instance().rootTarget().markAsNodeJSForTest(); SourcesTestRunner.startDebuggerTest(); - var debuggerModel = SDK.targetManager.rootTarget().model(SDK.DebuggerModel); + var debuggerModel = SDK.TargetManager.TargetManager.instance().rootTarget().model(SDK.DebuggerModel.DebuggerModel); var functionText = 'function foobar() { \nconsole.log(\'foobar execute!\');\n}'; var sourceURL = Host.isWin() ? '\n//# sourceURL=c:\\prog\\foobar.js' : '\n//# sourceURL=/usr/local/home/prog/foobar.js'; await TestRunner.evaluateInPageAnonymously(functionText + sourceURL);
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-console/debugger-command-line-api.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-console/debugger-command-line-api.js index b789d518..333e472 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-console/debugger-command-line-api.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-console/debugger-command-line-api.js
@@ -6,6 +6,8 @@ import {ConsoleTestRunner} from 'console_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that inspect() command line api works while on breakpoint.\n`); await TestRunner.loadLegacyModule('console'); @@ -23,10 +25,10 @@ } `); - TestRunner.addSniffer(SDK.RuntimeModel.prototype, 'inspectRequested', inspect); + TestRunner.addSniffer(SDK.RuntimeModel.RuntimeModel.prototype, 'inspectRequested', inspect); const originalReveal = Common.Revealer.reveal; Common.Revealer.setRevealForTest((node) => { - if (!(node instanceof SDK.RemoteObject)) { + if (!(node instanceof SDK.RemoteObject.RemoteObject)) { return Promise.resolve(); } return originalReveal(node).then(updateFocusedNode);
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-step/debugger-step-into-event-listener.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-step/debugger-step-into-event-listener.js index 3c4f68c4..47daaebea 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-step/debugger-step-into-event-listener.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-step/debugger-step-into-event-listener.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that stepping into dispatchEvent() method will lead to a pause in the first event listener.\n`); @@ -51,7 +53,7 @@ 'FAIL: Unexpected top function: expected ' + expectedName + ', found ' + topFunctionName); TestRunner.assertEquals( - SDK.DebuggerModel.BreakReason.Step, reason, + Protocol.Debugger.PausedEventReason.Step, reason, 'FAIL: wrong pause reason: ' + reason); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/debugger-save-to-temp-var.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/debugger-save-to-temp-var.js index e78b057..0834c70 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/debugger-save-to-temp-var.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/debugger-save-to-temp-var.js
@@ -6,6 +6,8 @@ import {ConsoleTestRunner} from 'console_test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests saving objects to temporary variables while paused.\n`); await TestRunner.loadLegacyModule('console'); @@ -72,11 +74,11 @@ function didEvaluate(result) { TestRunner.assertTrue(!result.exceptionDetails, 'FAIL: was thrown. Expression: ' + expression); - SDK.consoleModel.saveToTempVariable(UI.context.flavor(SDK.ExecutionContext), result.object); + SDK.consoleModel.saveToTempVariable(UI.context.flavor(SDK.RuntimeModel.ExecutionContext), result.object); ConsoleTestRunner.waitUntilNthMessageReceived(2, evaluateNext); } - UI.context.flavor(SDK.ExecutionContext) + UI.context.flavor(SDK.RuntimeModel.ExecutionContext) .evaluate({expression: expression, objectGroup: 'console'}) .then(didEvaluate); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/last-execution-context.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/last-execution-context.js index 19379c8..bfbca16 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/last-execution-context.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/last-execution-context.js
@@ -5,15 +5,17 @@ import {TestRunner} from 'test_runner'; import {SDKTestRunner} from 'sdk_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests how execution context and target are selected.\n`); await TestRunner.loadLegacyModule('main'); await TestRunner.showPanel('sources'); var context = new UI.Context(); - context.addFlavorChangeListener(SDK.ExecutionContext, executionContextChanged, this); - context.addFlavorChangeListener(SDK.Target, targetChanged, this); - new Main.ExecutionContextSelector(SDK.targetManager, context); + context.addFlavorChangeListener(SDK.RuntimeModel.ExecutionContext, executionContextChanged, this); + context.addFlavorChangeListener(SDK.Target.Target, targetChanged, this); + new Main.ExecutionContextSelector(SDK.TargetManager.TargetManager.instance(), context); function executionContextChanged(event) { var executionContext = event.data; @@ -31,64 +33,64 @@ TestRunner.addResult('Adding page target'); var pageMock = new SDKTestRunner.PageMock('mock-url.com/page.html'); var pageTarget = pageMock.connectAsMainTarget('page-target'); - await pageTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); + await pageTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); pageMock.evalScript('contentScript1.js', 'var script', true /* isContentScript */); - await pageTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); + await pageTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); TestRunner.addResult(''); TestRunner.addResult('Adding frame target'); var frameMock = new SDKTestRunner.PageMock('mock-url.com/iframe.html'); var frameTarget = frameMock.connectAsChildTarget('frame-target', pageMock); - await frameTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); + await frameTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); TestRunner.addResult(''); TestRunner.addResult('Adding worker target'); var workerMock = new SDKTestRunner.PageMock('mock-url.com/worker.js'); workerMock.turnIntoWorker(); var workerTarget = workerMock.connectAsChildTarget('worker-target', pageMock); - await workerTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); + await workerTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); TestRunner.addResult(''); TestRunner.addResult('User selected content script'); - context.setFlavor(SDK.ExecutionContext, pageTarget.model(SDK.RuntimeModel).executionContexts().find(context => !context.isDefault)); + context.setFlavor(SDK.RuntimeModel.ExecutionContext, pageTarget.model(SDK.RuntimeModel.RuntimeModel).executionContexts().find(context => !context.isDefault)); TestRunner.addResult(''); TestRunner.addResult('Removing content script'); pageMock.removeContentScripts(); - await pageTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextDestroyed); + await pageTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextDestroyed); TestRunner.addResult(''); TestRunner.addResult('Readding content script'); pageMock.evalScript('contentScript2.js', 'var script', true /* isContentScript */); - await pageTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); + await pageTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextCreated); TestRunner.addResult(''); TestRunner.addResult('Switching to worker target'); - context.setFlavor(SDK.Target, workerTarget); + context.setFlavor(SDK.Target.Target, workerTarget); TestRunner.addResult(''); TestRunner.addResult('Switching to page target'); - context.setFlavor(SDK.Target, pageTarget); + context.setFlavor(SDK.Target.Target, pageTarget); TestRunner.addResult(''); TestRunner.addResult('User selected content script'); - context.setFlavor(SDK.ExecutionContext, pageTarget.model(SDK.RuntimeModel).executionContexts().find(context => !context.isDefault)); + context.setFlavor(SDK.RuntimeModel.ExecutionContext, pageTarget.model(SDK.RuntimeModel.RuntimeModel).executionContexts().find(context => !context.isDefault)); TestRunner.addResult(''); TestRunner.addResult('Switching to worker target'); - context.setFlavor(SDK.Target, workerTarget); + context.setFlavor(SDK.Target.Target, workerTarget); TestRunner.addResult(''); TestRunner.addResult('Switching to page target'); - context.setFlavor(SDK.Target, pageTarget); + context.setFlavor(SDK.Target.Target, pageTarget); TestRunner.addResult(''); TestRunner.addResult('User selected iframe1'); - context.setFlavor(SDK.ExecutionContext, frameTarget.model(SDK.RuntimeModel).executionContexts()[0]); + context.setFlavor(SDK.RuntimeModel.ExecutionContext, frameTarget.model(SDK.RuntimeModel.RuntimeModel).executionContexts()[0]); TestRunner.addResult(''); TestRunner.addResult('Switching to worker target'); - context.setFlavor(SDK.Target, workerTarget); + context.setFlavor(SDK.Target.Target, workerTarget); TestRunner.addResult(''); TestRunner.addResult('Removing worker'); @@ -96,20 +98,20 @@ TestRunner.addResult(''); TestRunner.addResult('User selected content script'); - context.setFlavor(SDK.ExecutionContext, pageTarget.model(SDK.RuntimeModel).executionContexts().find(context => !context.isDefault)); + context.setFlavor(SDK.RuntimeModel.ExecutionContext, pageTarget.model(SDK.RuntimeModel.RuntimeModel).executionContexts().find(context => !context.isDefault)); TestRunner.addResult(''); TestRunner.addResult('Switching to iframe target'); - context.setFlavor(SDK.Target, frameTarget); + context.setFlavor(SDK.Target.Target, frameTarget); TestRunner.addResult(''); TestRunner.addResult('Removing content script'); pageMock.removeContentScripts(); - await pageTarget.model(SDK.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextDestroyed); + await pageTarget.model(SDK.RuntimeModel.RuntimeModel).once(SDK.RuntimeModel.Events.ExecutionContextDestroyed); TestRunner.addResult(''); TestRunner.addResult('Switching to page target'); - context.setFlavor(SDK.Target, pageTarget); + context.setFlavor(SDK.Target.Target, pageTarget); TestRunner.completeTest(); })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/monitor-console-command.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/monitor-console-command.js index 8b16e1b..7fcdc5b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/monitor-console-command.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/monitor-console-command.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests traceCalls(fn) console command.\n`); await TestRunner.loadLegacyModule('sources'); @@ -64,7 +66,7 @@ ConsoleTestRunner.waitUntilMessageReceived(didReceive); function didReceive(message) { - if (message.type === SDK.ConsoleMessage.FrontendMessageType.Result) { + if (message.type === SDK.ConsoleModel.FrontendMessageType.Result) { ConsoleTestRunner.waitUntilMessageReceived(didReceive); return; }
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/scripts-panel.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/scripts-panel.js index 6550f84..f32a76a 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/scripts-panel.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/scripts-panel.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {SDKTestRunner} from 'sdk_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that scripts panel UI elements work as intended.\n`); await TestRunner.loadLegacyModule('sources'); @@ -38,7 +40,7 @@ function reload() { page.reload(); - return new Promise(fulfill => TestRunner.addSniffer(SDK.ResourceTreeModel.prototype, 'frameNavigated', fulfill)); + return new Promise(fulfill => TestRunner.addSniffer(SDK.ResourceTreeModel.ResourceTreeModel.prototype, 'frameNavigated', fulfill)); } TestRunner.runTestSuite([
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/ui-source-code.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/ui-source-code.js index bb8d334..e56bc6b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/ui-source-code.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-ui/ui-source-code.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests UISourceCode class.\n`); await TestRunner.showPanel('sources'); @@ -34,7 +36,7 @@ }; TestRunner.runTestSuite([function testUISourceCode(next) { - var uiSourceCode = new Workspace.UISourceCode(new MockProject(), 'url', Common.resourceTypes.Script); + var uiSourceCode = new Workspace.UISourceCode(new MockProject(), 'url', Common.ResourceType.resourceTypes.Script); function didRequestContent(callNumber, { content, error, isEncoded }) { TestRunner.addResult('Callback ' + callNumber + ' is invoked.'); TestRunner.assertEquals('text/javascript', uiSourceCode.mimeType());
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/debugger-compile-and-run.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/debugger-compile-and-run.js index 9c23944..837c481 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/debugger-compile-and-run.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/debugger-compile-and-run.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests separate compilation and run.\n`); await TestRunner.loadLegacyModule('sources'); @@ -31,7 +33,7 @@ } } - var contextId = UI.context.flavor(SDK.ExecutionContext).id; + var contextId = UI.context.flavor(SDK.RuntimeModel.ExecutionContext).id; SourcesTestRunner.runDebuggerTestSuite([ async function testSuccessfulCompileAndRun(next) { var expression = 'var a = 1; var b = 2; a + b; ';
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/dynamic-script-tag.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/dynamic-script-tag.js index 4b5c6fb3..3dee7d6f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/dynamic-script-tag.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/dynamic-script-tag.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult( `Tests that inline scripts and document.write scripts get different uiSourceCodes with different URLs.`); @@ -18,7 +20,7 @@ function testOpenDevToolsAfterLoad(next) { var consoleMessagesCount = 2; - var messages = SDK.ConsoleModel.allMessagesUnordered(); + var messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered(); for (var i = 0; i < messages.length; ++i) processMessage(messages[i]); checkWhenScriptsLoaded();
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js index 94cdb28..609d5a4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js
@@ -6,6 +6,8 @@ import {SourcesTestRunner} from 'sources_test_runner'; import {SDKTestRunner} from 'sdk_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests scripts panel file selectors.\n`); await TestRunner.loadLegacyModule('sources'); @@ -151,7 +153,7 @@ TestRunner.addResult('\n\n================================================'); TestRunner.addResult('Removing all resources:'); - for (const target of SDK.targetManager.targets()) { + for (const target of SDK.TargetManager.TargetManager.instance().targets()) { if (target !== TestRunner.mainTarget) Bindings.debuggerWorkspaceBinding.resetForTest(target); }
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/network-uisourcecode-provider.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/network-uisourcecode-provider.js index 5e9b7dc..318247e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger/network-uisourcecode-provider.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/debugger/network-uisourcecode-provider.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests NetworkUISourceCodeProvider class.\n`); await TestRunner.loadLegacyModule('sources'); @@ -26,8 +28,8 @@ function dumpUISourceCode(uiSourceCode, callback) { TestRunner.addResult('UISourceCode: ' + uiSourceCodeURL(uiSourceCode)); - if (uiSourceCode.contentType() === Common.resourceTypes.Script || - uiSourceCode.contentType() === Common.resourceTypes.Document) + if (uiSourceCode.contentType() === Common.ResourceType.resourceTypes.Script || + uiSourceCode.contentType() === Common.ResourceType.resourceTypes.Document) TestRunner.addResult( 'UISourceCode is content script: ' + (uiSourceCode.project().type() ===
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/inline-styles-scripts-locations.js b/third_party/blink/web_tests/http/tests/devtools/sources/inline-styles-scripts-locations.js index 080b76f..a58ec386 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sources/inline-styles-scripts-locations.js +++ b/third_party/blink/web_tests/http/tests/devtools/sources/inline-styles-scripts-locations.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Bindings should only generate locations for an inline script (style) if the location is inside of the inline script (style).\n`); await TestRunner.loadLegacyModule('sources'); @@ -37,7 +39,7 @@ return null; } async function checkValidity(location) { - if (location instanceof SDK.CSSLocation) { + if (location instanceof SDK.CSSModel.CSSLocation) { const h = location.header(); if (!h) return "invalid css header"; if (!h.containsLocation(location.lineNumber, location.columnNumber))
diff --git a/third_party/blink/web_tests/http/tests/devtools/stylesheet-source-mapping.js b/third_party/blink/web_tests/http/tests/devtools/stylesheet-source-mapping.js index 88002d53..38e6122 100644 --- a/third_party/blink/web_tests/http/tests/devtools/stylesheet-source-mapping.js +++ b/third_party/blink/web_tests/http/tests/devtools/stylesheet-source-mapping.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests SourceMap and StyleSheetMapping.\n`); await TestRunner.loadLegacyModule('sources'); @@ -33,7 +35,7 @@ function locationsUpdated() { var header = cssModel.styleSheetHeaderForId(styleSheetId); - var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(new SDK.CSSLocation(header, 2, 3)); + var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(new SDK.CSSModel.CSSLocation(header, 2, 3)); if (uiLocation.uiSourceCode.url().indexOf('.scss') === -1) return; finalMappedLocation = uiLocation.uiSourceCode.url() + ':' + uiLocation.lineNumber + ':' + uiLocation.columnNumber; @@ -49,7 +51,7 @@ function testAndDumpLocation(uiSourceCode, expectedLine, expectedColumn, line, column) { var header = cssModel.styleSheetHeaderForId(styleSheetId); - var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(new SDK.CSSLocation(header, line, column)); + var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(new SDK.CSSModel.CSSLocation(header, line, column)); TestRunner.assertEquals( uiSourceCode, uiLocation.uiSourceCode, `Incorrect uiSourceCode, expected ${uiSourceCode.url()}, but got ${
diff --git a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-disable-cache.js b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-disable-cache.js index 8b72531..c029281 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-disable-cache.js +++ b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-disable-cache.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; + +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult('The \'disable cache\' flag must affect on the certificate fetch request.\n'); @@ -39,14 +41,14 @@ async function addPrefetchAndWait(prefetchUrl, waitUrl) { const promise = new Promise(resolve => { - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); function loadingFinished(event) { var request = NetworkTestRunner.networkLog().requestByManagerAndId( TestRunner.networkManager, event.requestId); if (request.url() == waitUrl) { resolve(); } else { - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished); } } });
diff --git a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch-fail.js b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch-fail.js index 9278c62e..4507ce1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch-fail.js +++ b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch-fail.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; + +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult('Tests the signed exchange information are available when the prefetch failed.\n'); await TestRunner.loadLegacyModule('console'); @@ -12,7 +14,7 @@ NetworkTestRunner.networkLog().reset(); const promise = new Promise(resolve => { - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFailed', loadingFailed, true); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFailed', loadingFailed, true); function loadingFailed(requestId, time, localizedDescription, canceled) { var request = NetworkTestRunner.networkLog().requestByManagerAndId( TestRunner.networkManager, requestId);
diff --git a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch.js b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch.js index 52d22b1c9..0a967b4c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch.js +++ b/third_party/blink/web_tests/http/tests/devtools/sxg/sxg-prefetch.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {NetworkTestRunner} from 'network_test_runner'; import {ConsoleTestRunner} from 'console_test_runner'; + +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult('Tests the signed exchange information are available when the prefetch succeeded.\n'); await TestRunner.loadLegacyModule('console'); @@ -12,7 +14,7 @@ NetworkTestRunner.networkLog().reset(); const promise = new Promise(resolve => { - TestRunner.addSniffer(SDK.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished, true); + TestRunner.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'loadingFinished', loadingFinished, true); function loadingFinished(requestId, finishTime, encodedDataLength) { var request = NetworkTestRunner.networkLog().requestByManagerAndId( TestRunner.networkManager, requestId);
diff --git a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-js/timeline-js-line-level-profile.js b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-js/timeline-js-line-level-profile.js index ef440ce3..4adf0ca 100644 --- a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-js/timeline-js-line-level-profile.js +++ b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-js/timeline-js-line-level-profile.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {SourcesTestRunner} from 'sources_test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that a line-level CPU profile is shown in the text editor.\n`); await TestRunner.loadLegacyModule('sources'); @@ -54,7 +56,7 @@ TestRunner.addResult(TestRunner.formatters.formatAsURL(url)); cpuProfile.nodes.forEach(n => n.callFrame.url = url); const lineProfile = PerfUI.LineLevelProfile.Performance.instance(); - lineProfile.appendCPUProfile(new SDK.CPUProfileDataModel(cpuProfile)); + lineProfile.appendCPUProfile(new SDK.CPUProfileDataModel.CPUProfileDataModel(cpuProfile)); setTimeout(() => TestRunner.completeTest(), 0); } })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/unit/binary-resource-view.js b/third_party/blink/web_tests/http/tests/devtools/unit/binary-resource-view.js index 328079d..4fe7083f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/unit/binary-resource-view.js +++ b/third_party/blink/web_tests/http/tests/devtools/unit/binary-resource-view.js
@@ -1,5 +1,7 @@ import {TestRunner} from 'test_runner'; + +import * as Common from 'devtools/core/common/common.js'; (async function() { TestRunner.addResult( 'Verifies that BinaryResourceViewFactory interprets base64 data correctly'); @@ -9,7 +11,7 @@ const base64content = 'c2VuZGluZyB0aGlzIHV0Zi04IHN0cmluZyBhcyBhIGJpbmFyeSBtZXNzYWdlLi4u'; const factory = new SourceFrame.BinaryResourceViewFactory( - base64content, 'http://example.com', Common.resourceTypes.WebSocket); + base64content, 'http://example.com', Common.ResourceType.resourceTypes.WebSocket); TestRunner.addResult('Base64View:'); TestRunner.addResult((await factory.createBase64View().lazyContent()).content);
diff --git a/third_party/blink/web_tests/http/tests/devtools/unit/object-properties-expand-recursively.js b/third_party/blink/web_tests/http/tests/devtools/unit/object-properties-expand-recursively.js index 996b94a..6f2b051 100644 --- a/third_party/blink/web_tests/http/tests/devtools/unit/object-properties-expand-recursively.js +++ b/third_party/blink/web_tests/http/tests/devtools/unit/object-properties-expand-recursively.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Test that ObjectPropertiesSection expands recursively.\n`); await TestRunner.loadLegacyModule('ui/legacy/components/object_ui'); @@ -27,7 +29,7 @@ } } - var localObject = SDK.RemoteObject.fromLocalObject(object); + var localObject = SDK.RemoteObject.RemoteObject.fromLocalObject(object); var propertiesSection = new ObjectUI.ObjectPropertiesSection(localObject, 'JSON'); await propertiesSection.objectTreeElement().expandRecursively();
diff --git a/third_party/blink/web_tests/http/tests/devtools/user-agent-setting-major-version.js b/third_party/blink/web_tests/http/tests/devtools/user-agent-setting-major-version.js index d70c160..b62ff37 100644 --- a/third_party/blink/web_tests/http/tests/devtools/user-agent-setting-major-version.js +++ b/third_party/blink/web_tests/http/tests/devtools/user-agent-setting-major-version.js
@@ -6,6 +6,7 @@ import {NetworkTestRunner} from 'network_test_runner'; import * as Network from 'devtools/panels/network/network.js'; +import * as SDK from 'devtools/core/sdk/sdk.js'; (async function() { TestRunner.addResult(`Test user agent setting\n`); @@ -51,7 +52,7 @@ if (splitUserAgentVersion.length === 3) testPatchedUserAgentVersion += additionalAppVersion + splitUserAgentVersion[2]; - const patchedUserAgentVersion = SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value); + const patchedUserAgentVersion = SDK.NetworkManager.MultitargetNetworkManager.patchUserAgentWithChromeVersion(userAgentVersion.value); if (patchedUserAgentVersion !== testPatchedUserAgentVersion) failTest('Computed user agent strings are not equal.');
diff --git a/third_party/blink/web_tests/http/tests/devtools/workers-on-navigation.js b/third_party/blink/web_tests/http/tests/devtools/workers-on-navigation.js index 41a9a81..f12760e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/workers-on-navigation.js +++ b/third_party/blink/web_tests/http/tests/devtools/workers-on-navigation.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as SDK from 'devtools/core/sdk/sdk.js'; + (async function() { TestRunner.addResult(`Tests that workers are correctly detached upon navigation.\n`); @@ -37,7 +39,7 @@ } } }; - SDK.targetManager.observeTargets(observer); + SDK.TargetManager.TargetManager.instance().observeTargets(observer); await TestRunner.navigatePromise('resources/workers-on-navigation-resource.html'); TestRunner.evaluateInPagePromise('startWorker()'); await workerAddedPromise;
diff --git a/third_party/blink/web_tests/http/tests/devtools/workspace-mapping.js b/third_party/blink/web_tests/http/tests/devtools/workspace-mapping.js index 71799896..f9e80d395 100644 --- a/third_party/blink/web_tests/http/tests/devtools/workspace-mapping.js +++ b/third_party/blink/web_tests/http/tests/devtools/workspace-mapping.js
@@ -4,6 +4,8 @@ import {TestRunner} from 'test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests workspace mappings\n`); @@ -20,7 +22,7 @@ workspace.addProject(project); projects[projectId] = project; } - var uiSourceCode = project.createUISourceCode(projectId + '/' + relativePath, Common.resourceTypes.Script); + var uiSourceCode = project.createUISourceCode(projectId + '/' + relativePath, Common.ResourceType.resourceTypes.Script); project.addUISourceCode(uiSourceCode); }
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index 796b2a5..00252478 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -682,6 +682,11 @@ setter x setter y setter z +interface CSSScopeRule : CSSConditionRule + attribute @@toStringTag + getter end + getter start + method constructor interface CSSSkew : CSSTransformComponent attribute @@toStringTag getter ax
diff --git a/third_party/closure_compiler/externs/accessibility_private.js b/third_party/closure_compiler/externs/accessibility_private.js index f41c9b72..6600830e 100644 --- a/third_party/closure_compiler/externs/accessibility_private.js +++ b/third_party/closure_compiler/externs/accessibility_private.js
@@ -277,6 +277,7 @@ GOOGLE_TTS_LANGUAGE_PACKS: 'googleTtsLanguagePacks', DICTATION_CONTEXT_CHECKING: 'dictationContextChecking', CHROMEVOX_SETTINGS_MIGRATION: 'chromevoxSettingsMigration', + GAME_FACE_INTEGRATION: 'gameFaceIntegration', }; /**
diff --git a/third_party/wpt_tools/README.chromium b/third_party/wpt_tools/README.chromium index 8849ea2..f1a8bcb3 100644 --- a/third_party/wpt_tools/README.chromium +++ b/third_party/wpt_tools/README.chromium
@@ -1,7 +1,7 @@ Name: web-platform-tests - Test Suites for Web Platform specifications Short Name: wpt URL: https://github.com/web-platform-tests/wpt/ -Version: d48fa8b3e81c1fd052237372533ba69113812ecf +Version: bffb3618d329fd2c7b82284c889572421d26633b License: LICENSES FOR W3C TEST SUITES (https://www.w3.org/Consortium/Legal/2008/03-bsd-license.html) Security Critical: no Shipped: no
diff --git a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/executors/executorservo.py b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/executors/executorservo.py index 3250c74f..a8ec386 100644 --- a/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/executors/executorservo.py +++ b/third_party/wpt_tools/wpt/tools/wptrunner/wptrunner/executors/executorservo.py
@@ -83,7 +83,6 @@ ProcessTestExecutor.teardown(self) def do_test(self, test): - self.test = test self.result_data = None self.result_flag = threading.Event() @@ -157,7 +156,7 @@ else: self.logger.process_output(self.proc.pid, line, - " ".join(self.command), self.test.url) + " ".join(self.command)) def on_finish(self): self.result_flag.set() @@ -271,7 +270,6 @@ return True, [base64.b64encode(data).decode()] def do_test(self, test): - self.test = test result = self.implementation.run_test(test) return self.convert_result(test, result) @@ -283,7 +281,7 @@ else: self.logger.process_output(self.proc.pid, line, - " ".join(self.command), self.test.url) + " ".join(self.command)) class ServoTimedRunner(TimedRunner): @@ -344,22 +342,21 @@ env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" - self.command = build_servo_command(self.test, - self.test_url, - self.browser, - self.binary, - False, - self.debug_info, - extra_args=["-x"]) + command = build_servo_command(self.test, + self.test_url, + self.browser, + self.binary, + False, + self.debug_info, + extra_args=["-x"]) if not self.interactive: - self.proc = ProcessHandler(self.command, + self.proc = ProcessHandler(command, env=env, - processOutputLine=[self.on_output], storeOutput=False) self.proc.run() else: - self.proc = subprocess.Popen(self.command, env=env) + self.proc = subprocess.Popen(command, env=env) self.proc.wait() @@ -367,9 +364,3 @@ return {"status": "PASS", "message": None} return {"status": "CRASH", "message": None} - - def on_output(self, line): - line = line.decode("utf8", "replace") - self.logger.process_output(self.proc.pid, - line, - " ".join(self.command), self.test.url)
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9c3c697..f8b82e6 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -9611,6 +9611,7 @@ <int value="2" label="Signed In and Wallet Sync Transport Enabled"/> <int value="3" label="Signed In and Sync Feature Enabled"/> <int value="4" label="Sync Paused"/> + <int value="5" label="Unknown"/> </enum> <enum name="AutofillTypeQuality">
diff --git a/tools/metrics/histograms/metadata/navigation/histograms.xml b/tools/metrics/histograms/metadata/navigation/histograms.xml index 2fc6d33e..4a2f2d9 100644 --- a/tools/metrics/histograms/metadata/navigation/histograms.xml +++ b/tools/metrics/histograms/metadata/navigation/histograms.xml
@@ -1795,7 +1795,7 @@ <histogram name="Prerender.Experimental.DefaultSearchEngine.SearchTermExtractorCorrectness" - enum="Boolean" expires_after="2023-08-13"> + enum="Boolean" expires_after="2023-10-31"> <owner>lingqi@chromium.org</owner> <owner>chrome-prerendering@google.com</owner> <summary> @@ -1908,7 +1908,7 @@ <histogram name="Prerender.Experimental.PrerenderLoadingFailureError{PrerenderTriggerType}" - enum="NetErrorCodes" expires_after="2023-08-27"> + enum="NetErrorCodes" expires_after="2023-10-31"> <owner>lingqi@chromium.org</owner> <owner>chrome-prerendering@google.com</owner> <summary> @@ -1978,7 +1978,7 @@ <histogram name="Prerender.Experimental.Search.FirstCorrectPrerenderHintReceivedToRealSearchNavigationStartedDuration" - units="ms" expires_after="2023-08-20"> + units="ms" expires_after="2023-10-31"> <owner>lingqi@chromium.org</owner> <owner>chrome-prerendering@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index 2917282..dc72c47 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -6308,16 +6308,6 @@ <summary>Track whether Firebase is enabled or not at app startup.</summary> </histogram> -<histogram name="FirstRun.iOSFreFinchEnabled" enum="BooleanEnabled" - expires_after="2023-09-01"> - <owner>triploblastic@chromium.org</owner> - <owner>chrome-signin-team@google.com</owner> - <summary> - Tests whether the FRE screen on iOS is finchable. Recorded once the FRE - screen is shown to the user. - </summary> -</histogram> - <histogram name="FirstRun.LaunchSource" enum="FirstRunLaunchSource" expires_after="2024-04-01"> <owner>jlebel@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/page/histograms.xml b/tools/metrics/histograms/metadata/page/histograms.xml index a95b8ee9..7acebbe 100644 --- a/tools/metrics/histograms/metadata/page/histograms.xml +++ b/tools/metrics/histograms/metadata/page/histograms.xml
@@ -2401,7 +2401,7 @@ <histogram name="PageLoad.Internal.Prerender2.ActivatedPageLoaderStatus{PrerenderTriggerType}" - enum="NetErrorCodes" expires_after="2023-08-27"> + enum="NetErrorCodes" expires_after="2023-10-31"> <owner>lingqi@chromium.org</owner> <owner>chrome-prerendering@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/signin/histograms.xml b/tools/metrics/histograms/metadata/signin/histograms.xml index 8205cda..cc0b3dff6 100644 --- a/tools/metrics/histograms/metadata/signin/histograms.xml +++ b/tools/metrics/histograms/metadata/signin/histograms.xml
@@ -177,7 +177,7 @@ </histogram> <histogram name="Signin.AccountFetcher.AccountAvatarFetchTime" units="ms" - expires_after="2023-09-03"> + expires_after="2024-03-22"> <owner>triploblastic@chromium.org</owner> <owner>chrome-signin-team@google.com</owner> <summary> @@ -318,7 +318,7 @@ </histogram> <histogram name="Signin.AndroidDeviceAccountsNumberWhenEnteringFRE" - units="count" expires_after="2023-09-10"> + units="count" expires_after="2024-03-22"> <owner>bsazonov@chromium.org</owner> <owner>chrome-signin-team@google.com</owner> <summary> @@ -1401,7 +1401,7 @@ </histogram> <histogram name="Signin.SyncErrorMessage{SyncErrorReason}" - enum="SyncErrorPromptUIAction" expires_after="2023-09-12"> + enum="SyncErrorPromptUIAction" expires_after="2024-03-22"> <owner>triploblastic@chromium.org</owner> <owner>bsazonov@chromium.org</owner> <summary> @@ -1425,7 +1425,7 @@ </histogram> <histogram name="Signin.SyncFirstSetupCompleteSource" - enum="SyncFirstSetupCompleteSource" expires_after="2023-08-20"> + enum="SyncFirstSetupCompleteSource" expires_after="2024-03-22"> <owner>triploblastic@chromium.org</owner> <owner>bsazonov@chromium.org</owner> <summary>Tracks where FirstSetupComplete bit is set from.</summary> @@ -1471,7 +1471,7 @@ </histogram> <histogram name="Signin.SyncPromo.{Action}.Count.{AccessPoint}" units="counts" - expires_after="2023-09-22"> + expires_after="2024-03-22"> <owner>triploblastic@chromium.org</owner> <owner>chrome-signin-team@google.com</owner> <summary>
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn index cda1666e0..576a5c15 100644 --- a/ui/base/BUILD.gn +++ b/ui/base/BUILD.gn
@@ -194,6 +194,8 @@ "models/tree_model.h", "models/tree_node_iterator.h", "models/tree_node_model.h", + "moving_max.cc", + "moving_max.h", "nine_image_painter_factory.cc", "nine_image_painter_factory.h", "page_transition_types.cc", @@ -1005,6 +1007,7 @@ "models/simple_combobox_model_unittest.cc", "models/simple_menu_model_unittest.cc", "models/tree_node_iterator_unittest.cc", + "moving_max_unittest.cc", "pointer/touch_ui_controller_unittest.cc", "prediction/empty_filter_unittests.cc", "prediction/input_filter_unittest_helpers.cc",
diff --git a/ui/base/interaction/state_observer.h b/ui/base/interaction/state_observer.h index 4132275..476c891 100644 --- a/ui/base/interaction/state_observer.h +++ b/ui/base/interaction/state_observer.h
@@ -9,8 +9,8 @@ #include <ostream> #include <type_traits> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/callback.h" +#include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" #include "ui/base/interaction/element_identifier.h"
diff --git a/ui/base/moving_max.cc b/ui/base/moving_max.cc new file mode 100644 index 0000000..f1d260cd --- /dev/null +++ b/ui/base/moving_max.cc
@@ -0,0 +1,40 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/base/moving_max.h" + +#include <base/check_op.h> + +namespace ui { + +MovingMax::MovingMax(size_t window_size) + : window_size_(window_size), values_(window_size), added_at_(window_size) {} + +MovingMax::~MovingMax() = default; + +void MovingMax::Put(int value) { + ++total_added_; + // Remove old elements from the back of the window; + while (size_ > 0 && added_at_[begin_idx_] + window_size_ <= total_added_) { + begin_idx_ = (begin_idx_ + 1) % window_size_; + --size_; + } + // Remove small elements from the front of the window because they can never + // become the maximum in the window since the currently added element is + // bigger than them and will leave the window later. + while (size_ > 0 && + values_[(begin_idx_ + size_ - 1) % window_size_] < value) { + --size_; + } + DCHECK_LT(size_, window_size_); + values_[(begin_idx_ + size_) % window_size_] = value; + added_at_[(begin_idx_ + size_) % window_size_] = total_added_; + ++size_; +} + +int MovingMax::Max() const { + DCHECK_GT(size_, 0u); + return values_[begin_idx_]; +} +} // namespace ui
diff --git a/ui/base/moving_max.h b/ui/base/moving_max.h new file mode 100644 index 0000000..639c201 --- /dev/null +++ b/ui/base/moving_max.h
@@ -0,0 +1,42 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#ifndef UI_BASE_MOVING_MAX_H_ +#define UI_BASE_MOVING_MAX_H_ + +#include <stdint.h> +#include <vector> + +#include "base/component_export.h" + +namespace ui { + +// Simple class to efficiently calculate maximum in a moving window. +// This class isn't thread safe. +class COMPONENT_EXPORT(UI_BASE) MovingMax { + public: + explicit MovingMax(size_t window_size); + ~MovingMax(); + // Add new sample to the stream. + void Put(int value); + // Get the maximum of the last `window_size` elements. + int Max() const; + + private: + const size_t window_size_; + // Circular buffer with some values in the window. + // Only possible candidates for maximum are stored: + // values form a non-increasing sequence. + std::vector<int> values_; + // Circular buffer storing when numbers in `values_` were added. + std::vector<size_t> added_at_; + // Begin of the circular buffers above. + size_t begin_idx_ = 0; + // How many elements are stored in the circular buffers above. + size_t size_ = 0; + // Counter of all `Put` operations. + size_t total_added_ = 0; +}; + +} // namespace ui +#endif // UI_BASE_MOVING_MAX_H_
diff --git a/ui/base/moving_max_unittest.cc b/ui/base/moving_max_unittest.cc new file mode 100644 index 0000000..be2a8fa --- /dev/null +++ b/ui/base/moving_max_unittest.cc
@@ -0,0 +1,64 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/base/moving_max.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace ui { + +const std::vector<int> kTestValues{ + 33, 1, 2, 7, 5, 2, 4, 45, 1000, 1, 100, 2, 200, 2, 2, 2, 300, 4, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, + 2, 1, 4, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1}; + +class MovingMaxTest : public testing::TestWithParam<unsigned int> {}; + +INSTANTIATE_TEST_SUITE_P(All, + MovingMaxTest, + testing::ValuesIn({1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u, + 10u, 17u, 20u, 100u})); + +TEST_P(MovingMaxTest, BlanketTest) { + const size_t window_size = GetParam(); + MovingMax window(window_size); + for (size_t i = 0; i < kTestValues.size(); ++i) { + window.Put(kTestValues[i]); + int slow_max = kTestValues[i]; + for (size_t j = 1; j < window_size && j <= i; ++j) { + slow_max = std::max(slow_max, kTestValues[i - j]); + } + EXPECT_EQ(window.Max(), slow_max); + } +} + +TEST(MovingMax, SingleElementWindow) { + MovingMax window(1u); + window.Put(100); + EXPECT_EQ(window.Max(), 100); + window.Put(1000); + EXPECT_EQ(window.Max(), 1000); + window.Put(1); + EXPECT_EQ(window.Max(), 1); + window.Put(3); + EXPECT_EQ(window.Max(), 3); + window.Put(4); + EXPECT_EQ(window.Max(), 4); +} + +TEST(MovingMax, VeryLargeWindow) { + MovingMax window(100u); + window.Put(100); + EXPECT_EQ(window.Max(), 100); + window.Put(1000); + EXPECT_EQ(window.Max(), 1000); + window.Put(1); + EXPECT_EQ(window.Max(), 1000); + window.Put(3); + EXPECT_EQ(window.Max(), 1000); + window.Put(4); + EXPECT_EQ(window.Max(), 1000); +} + +} // namespace ui
diff --git a/ui/events/ozone/evdev/event_thread_evdev.cc b/ui/events/ozone/evdev/event_thread_evdev.cc index 1e65793..b587843c 100644 --- a/ui/events/ozone/evdev/event_thread_evdev.cc +++ b/ui/events/ozone/evdev/event_thread_evdev.cc
@@ -7,7 +7,6 @@ #include <memory> #include <utility> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/logging.h"
diff --git a/ui/file_manager/file_manager/background/js/file_operation_handler.js b/ui/file_manager/file_manager/background/js/file_operation_handler.js index e4207a7..0e7086a 100644 --- a/ui/file_manager/file_manager/background/js/file_operation_handler.js +++ b/ui/file_manager/file_manager/background/js/file_operation_handler.js
@@ -358,6 +358,7 @@ case chrome.fileManagerPrivate.IOTaskType.COPY: return str('DLP_FILES_COPY_WARN_CONTINUE_BUTTON'); case chrome.fileManagerPrivate.IOTaskType.MOVE: + case chrome.fileManagerPrivate.IOTaskType.RESTORE_TO_DESTINATION: return str('DLP_FILES_MOVE_WARN_CONTINUE_BUTTON'); default: console.error('Unexpected operation type: ' + event.type);
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 94be6af..28ed6d2 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
@@ -452,6 +452,22 @@ } /** + * @param {!DataTransfer} clipboardData DataTransfer object from the event. + * @return {boolean} Returns true when some file under action is encrypted. + * @private + */ + isEncrypted_(clipboardData) { + let data = clipboardData.getData(`fs/${ENCRYPTED}`); + if (!data) { + // |clipboardData| in protected mode. + const globalData = this.getDragAndDropGlobalData_(); + if (globalData) { + data = globalData.encrypted; + } + } + return data === 'true'; + } + /** * Calls executePaste with |pastePlan| if paste is allowed by Data Leak * Prevention policy. If paste is not allowed, it shows a toast to the * user. @@ -1192,6 +1208,14 @@ return false; } } + // Don't allow copy of encrypted files. + if (this.metadataModel_.getCache(entries, ['contentMimeType']) + .some( + (metadata, i) => FileType.isEncrypted( + entries[i], metadata.contentMimeType))) { + return false; + } + // Check if canCopy is true or undefined, but not false (see // https://crbug.com/849999). return this.metadataModel_.getCache(entries, ['canCopy']) @@ -1326,6 +1350,11 @@ return false; } + // Moving an encrypted files outside of Google Drive is not supported. + if (this.isEncrypted_(clipboardData)) { + return false; + } + // Block transferring hosted files between different sources in order to // prevent hosted files from being transferred outside of Drive. This is // done because hosted files aren't 'real' files, so it doesn't make sense
diff --git a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js index aac9be5..737a9dd 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js +++ b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js
@@ -247,6 +247,7 @@ case ProgressItemType.COPY: return str('DLP_FILES_COPY_REVIEW_TITLE'); case ProgressItemType.MOVE: + case ProgressItemType.RESTORE_TO_DESTINATION: return str('DLP_FILES_MOVE_REVIEW_TITLE'); default: console.error('Unexpected operation type: ' + item.type);
diff --git a/ui/file_manager/integration_tests/file_manager/context_menu.js b/ui/file_manager/integration_tests/file_manager/context_menu.js index aa227e8..bb40d13 100644 --- a/ui/file_manager/integration_tests/file_manager/context_menu.js +++ b/ui/file_manager/integration_tests/file_manager/context_menu.js
@@ -988,3 +988,85 @@ chrome.test.assertFalse(nonDefaultTaskItem.attributes['class'].includes('change-default')); } }; + +/* + * Test that the "copy" context menu item is disabled for Google Drive CSE + * files. + */ +testcase.checkEncryptedCopyDisabled = async () => { + const appId = + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.testCSEFile]); + + await remoteCall.showContextMenuFor(appId, ENTRIES.testCSEFile.nameText); + + await remoteCall.waitForElement( + appId, + '#file-context-menu:not([hidden]) [command="#copy"][disabled]:not([hidden])'); +}; + +/* + * Test that a Google Drive CSE files can be moved (using cut+paste) within + * Google Drive. + */ +testcase.checkEncryptedMoveEnabled = async () => { + const appId = await setupAndWaitUntilReady( + RootPath.DRIVE, [], [ENTRIES.testCSEFile, ENTRIES.photos]); + + await remoteCall.showContextMenuFor(appId, ENTRIES.testCSEFile.nameText); + + // Check that the cut command is available for the user. + await remoteCall.waitForElement( + appId, + '#file-context-menu:not([hidden]) [command="#cut"]:not([disabled]):not([hidden])'); + + await remoteCall.waitUntilSelected(appId, ENTRIES.testCSEFile.nameText); + chrome.test.assertTrue( + !!await remoteCall.callRemoteTestUtil('execCommand', appId, ['cut']), + 'execCommand failed'); + + // Navigate to a folder, ENTRIES.photos appears to be just a writeable test + // folder. + await navigateWithDirectoryTree(appId, '/My Drive/photos'); + + // Right-click inside the file list. + chrome.test.assertTrue(!!await remoteCall.callRemoteTestUtil( + 'fakeMouseRightClick', appId, ['#file-list'])); + + // Wait for the command option to appear. + await remoteCall.waitForElement( + appId, + '#file-context-menu:not([hidden]) [command="#paste"]:not([disabled]):not([hidden])'); +}; + +/* + * Test that a Google Drive CSE files can not be moved (using cut+paste) outside + * of Google Drive. + */ +testcase.checkEncryptedCrossVolumeMoveDisabled = async () => { + const appId = + await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.testCSEFile]); + + await remoteCall.showContextMenuFor(appId, ENTRIES.testCSEFile.nameText); + + // Check that the cut command is available for the user. + await remoteCall.waitForElement( + appId, + '#file-context-menu:not([hidden]) [command="#cut"]:not([disabled]):not([hidden])'); + + await remoteCall.waitUntilSelected(appId, ENTRIES.testCSEFile.nameText); + chrome.test.assertTrue( + !!await remoteCall.callRemoteTestUtil('execCommand', appId, ['cut']), + 'execCommand failed'); + + // Navigate to a folder, “My files“ is just an example of a writeable one. + await navigateWithDirectoryTree(appId, '/My files'); + + // Right-click inside the file list. + chrome.test.assertTrue(!!await remoteCall.callRemoteTestUtil( + 'fakeMouseRightClick', appId, ['#file-list'])); + + // Wait for the command option to appear. + await remoteCall.waitForElement( + appId, + '#file-context-menu:not([hidden]) [command="#paste"][disabled]:not([hidden])'); +};
diff --git a/ui/file_manager/integration_tests/file_manager/dlp.js b/ui/file_manager/integration_tests/file_manager/dlp.js index 838483d..0e0c929 100644 --- a/ui/file_manager/integration_tests/file_manager/dlp.js +++ b/ui/file_manager/integration_tests/file_manager/dlp.js
@@ -11,7 +11,7 @@ import {BASIC_ANDROID_ENTRY_SET, BASIC_LOCAL_ENTRY_SET} from './test_data.js'; /** - * Copies or moves a file to provided location. + * Copies or moves a file from Downloads to the provided location. * @param {string} appId ID of the Files app window. * @param {TestEntryInfo} file Test entry info to be copied/cut. * @param {string} destination Name of the destination folder. @@ -23,8 +23,8 @@ chrome.test.assertTrue(false, 'copyOrMove invalid parameters'); } + await navigateWithDirectoryTree(appId, '/My files/Downloads'); await remoteCall.waitForFiles(appId, [file.getExpectedRow()]); - await remoteCall.waitUntilSelected(appId, file.nameText); const command = isCopy ? 'copy' : 'cut'; @@ -36,16 +36,59 @@ } /** + * List of panel types. + * + * Keep this in sync with PanelItem panel types. + * + * @enum {number} + * @const + */ +const PanelType = { + DEFAULT: -1, + PROGRESS: 0, + SUMMARY: 1, + DONE: 2, + ERROR: 3, + INFO: 4, + FORMAT_PROGRESS: 5, + SYNC_PROGRESS: 6, +}; + +/** + * List of checked panel status indicator types. + * + * @enum {string} + * @const + */ +const StatusIndicator = { + WARNING: 'warning', + FAILURE: 'failure', +}; + +/** + * Returns the first panel item with the provided panel type. + * @param {string} appId ID of the Files app window. + * @param {PanelType} panelType + */ +async function getPanelItem(appId, panelType) { + const panel = await remoteCall.waitForElement( + appId, ['#progress-panel', `xf-panel-item[panel-type="${panelType}"]`]); + return panel; +} + +/** * Checks that the panel item with provided parameters exists. * @param {string} appId ID of the Files app window. + * @param {PanelType} panelType Expected panel type. * @param {string} primaryText Expected primary text. - * @param {string} secondaryText Expected secondary text. - * @param {string} status Expected status indicator (failure or warning). + * @param {?string} secondaryText Expected secondary text. Can be null. + * @param {StatusIndicator} status Expected status indicator (failure or + * warning). * @return {Promise} Promise fulfilled on success. */ -async function verifyPanelItem(appId, primaryText, secondaryText, status) { - const panel = await remoteCall.waitForElement( - appId, ['#progress-panel', 'xf-panel-item']); +async function verifyPanelItem( + appId, panelType, primaryText, secondaryText, status) { + const panel = await getPanelItem(appId, panelType); chrome.test.assertEq(primaryText, panel.attributes['primary-text']); chrome.test.assertEq(secondaryText, panel.attributes['secondary-text']); @@ -83,6 +126,29 @@ } /** + * Expands the summary panel if it's collapsed, no-op if already expanded. + * @param {string} appId ID of the Files app window. + * */ +async function maybeExpandSummary(appId) { + const summaryPanel = await getPanelItem(appId, PanelType.SUMMARY); + if (summaryPanel.attributes['data-category'] === 'expanded') { + return; + } + + await remoteCall.waitAndClickElement(appId, [ + '#progress-panel', + `xf-panel-item[panel-type="${PanelType.SUMMARY}"]`, + 'xf-button#primary-action', + ]); + + await remoteCall.waitForElement(appId, [ + '#progress-panel', + `xf-panel-item[panel-type="${ + PanelType.SUMMARY}"][data-category="expanded"]`, + ]); +} + +/** * Tests that DLP block toast is shown when a restricted file is cut. */ testcase.transferShowDlpToast = async () => { @@ -843,21 +909,20 @@ // Check that the error panel is open with correct primary and secondary text, // and has the expected button types. await verifyPanelItem( - appId, 'File blocked from copying', - `${entry.nameText} was blocked because of policy`, 'failure'); + appId, PanelType.ERROR, 'File blocked from copying', + `${entry.nameText} was blocked because of policy`, + StatusIndicator.FAILURE); await verifyPanelButtonsAndClick(appId, 'dismiss', 'secondary'); - // Navigate back to Downloads. - await navigateWithDirectoryTree(appId, '/My files/Downloads'); - // Cut and paste the file to USB. await copyOrMove(appId, entry, '/fake-usb', /*isCopy=*/ false); // Check that the error panel is open with correct primary and secondary text, // and has the expected button types. await verifyPanelItem( - appId, 'File blocked from moving', - `${entry.nameText} was blocked because of policy`, 'failure'); + appId, PanelType.ERROR, 'File blocked from moving', + `${entry.nameText} was blocked because of policy`, + StatusIndicator.FAILURE); await verifyPanelButtonsAndClick(appId, 'dismiss', 'primary'); }; @@ -894,13 +959,11 @@ // Check that the warning panel is open with correct primary and secondary // text, and has the expected button types. await verifyPanelItem( - appId, 'Review is required before copying', - `${entry.nameText} may contain sensitive content`, 'warning'); + appId, PanelType.INFO, 'Review is required before copying', + `${entry.nameText} may contain sensitive content`, + StatusIndicator.WARNING); await verifyPanelButtonsAndClick(appId, 'cancel', 'secondary'); - // Navigate back to Downloads. - await navigateWithDirectoryTree(appId, '/My files/Downloads'); - // Set the first mock to pause the task. await sendTestMessage({ name: 'setCheckFilesTransferMockToPause', @@ -915,7 +978,103 @@ // Check that the warning panel is open with correct primary and secondary // text, and has the expected button types. await verifyPanelItem( - appId, 'Review is required before moving', - `${entry.nameText} may contain sensitive content`, 'warning'); + appId, PanelType.INFO, 'Review is required before moving', + `${entry.nameText} may contain sensitive content`, + StatusIndicator.WARNING); await verifyPanelButtonsAndClick(appId, 'cancel', 'primary'); }; + +/** + * Tests that the summary panel shows the correct title when it contains a mix + * of warning (paused copy or move IO task) and error (blocked copy or move IO + * task) panels, or multiple warnings, but is not shown if only one panel is + * visible. + */ +testcase.mixedSummaryDisplayPanel = async () => { + // Add entry to Downloads. + const entry = ENTRIES.hello; + await addEntries(['local'], [entry]); + + // Open Files app. + const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []); + + // Block the second task. + await sendTestMessage({ + name: 'setBlockedFilesTransfer', + fileNames: [entry.nameText], + }); + + // Mount a USB volume. + await sendTestMessage({name: 'mountFakeUsbEmpty'}); + + // Wait for the USB volume to mount. + const usbVolumeQuery = '#directory-tree [volume-type-icon="removable"]'; + await remoteCall.waitForElement(appId, usbVolumeQuery); + + // Copy and paste the file to USB. + await copyOrMove(appId, entry, '/fake-usb', /*isCopy=*/ true); + + // Check that only 1 error panel is opened. + await remoteCall.waitForElementsCount( + appId, ['#progress-panel', `xf-panel-item`], 1); + await remoteCall.waitForElementsCount( + appId, + ['#progress-panel', `xf-panel-item[panel-type="${PanelType.ERROR}"]`], 1); + + // Set the mock to pause the second task. + await sendTestMessage({ + name: 'setCheckFilesTransferMockToPause', + taskId: 2, + fileNames: [entry.nameText], + action: 'copy', + }); + + // Copy the file to USB. + await copyOrMove(appId, entry, '/fake-usb', /*isCopy=*/ true); + + // Check that the summary panel is open with correct title and the two sub + // panels (3 in total). + await remoteCall.waitForElementsCount( + appId, ['#progress-panel', 'xf-panel-item'], 3); + await verifyPanelItem( + appId, PanelType.SUMMARY, '1 errors. 1 warning.', null, + StatusIndicator.FAILURE); + // Expand the summary panel if needed, in order to click on the individual + // ones. + await maybeExpandSummary(appId); + + // Dismiss the error panel. + await remoteCall.waitAndClickElement(appId, [ + '#progress-panel', + `xf-panel-item[panel-type="${PanelType.ERROR}"]`, + 'xf-button#secondary-action', + ]); + + // Check that only 1 warning panel remains. + await remoteCall.waitForElementsCount( + appId, ['#progress-panel', `xf-panel-item`], 1); + await remoteCall.waitForElementsCount( + appId, + ['#progress-panel', `xf-panel-item[panel-type="${PanelType.INFO}"]`], 1); + + // Set the mock to pause the third task. + await sendTestMessage({ + name: 'setCheckFilesTransferMockToPause', + taskId: 3, + fileNames: [entry.nameText], + action: 'copy', + }); + + // Copy the file to USB. + await copyOrMove(appId, entry, '/fake-usb', /*isCopy=*/ true); + + // Check that the summary panel is open with correct title and the two sub + // panels (3 in total). + await remoteCall.waitForElementsCount( + appId, ['#progress-panel', 'xf-panel-item'], 3); + await remoteCall.waitForElementsCount( + appId, + ['#progress-panel', `xf-panel-item[panel-type="${PanelType.INFO}"]`], 2); + await verifyPanelItem( + appId, PanelType.SUMMARY, '2 warnings.', null, StatusIndicator.WARNING); +};
diff --git a/ui/file_manager/integration_tests/file_manager/file_transfer_connector.js b/ui/file_manager/integration_tests/file_manager/file_transfer_connector.js index 9fb9046..1037222aa 100644 --- a/ui/file_manager/integration_tests/file_manager/file_transfer_connector.js +++ b/ui/file_manager/integration_tests/file_manager/file_transfer_connector.js
@@ -249,8 +249,17 @@ // TODO(crbug.com/1361898): Remove these ones proper error details are // displayed. -const COPY_FAIL_MESSAGE = 'File blocked from copying'; -const MOVE_FAIL_MESSAGE = `File blocked from moving`; +const OLD_COPY_FAIL_MESSAGE = + 'Copy operation failed. The file could not be accessed ' + + 'for security reasons.'; +const OLD_MOVE_FAIL_DIRECTORY_MESSAGE = + `Can't move file. The file could not be modified.`; +const OLD_MOVE_FAIL_FILE_MESSAGE = + `Can't move file. The file could not be accessed ` + + 'for security reasons.'; + +const NEW_COPY_FAIL_MESSAGE = 'File blocked from copying'; +const NEW_MOVE_FAIL_MESSAGE = `File blocked from moving`; /** * Opens a Files app's main window and creates the source and destination @@ -594,7 +603,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromAndroidFilesToDownloadsFlat = () => { @@ -604,7 +613,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; @@ -618,7 +627,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromCrostiniToDownloadsFlat = () => { @@ -628,7 +637,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; @@ -642,7 +651,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromDriveToDownloadsFlat = () => { @@ -652,7 +661,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; @@ -667,7 +676,7 @@ isMove: true, }), CONNECTOR_ENTRIES_DEEP, - MOVE_FAIL_MESSAGE, + OLD_MOVE_FAIL_DIRECTORY_MESSAGE, ); }; testcase.transferConnectorFromDriveToDownloadsMoveFlat = () => { @@ -678,7 +687,7 @@ isMove: true, }), CONNECTOR_ENTRIES_FLAT, - MOVE_FAIL_MESSAGE, + OLD_MOVE_FAIL_FILE_MESSAGE, ); }; @@ -692,7 +701,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromMtpToDownloadsFlat = () => { @@ -702,7 +711,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; @@ -716,7 +725,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromSmbfsToDownloadsFlat = () => { @@ -726,7 +735,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; @@ -740,7 +749,7 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_DEEP, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); }; testcase.transferConnectorFromUsbToDownloadsFlat = () => { @@ -750,6 +759,6 @@ destination: TRANSFER_LOCATIONS.downloads, }), CONNECTOR_ENTRIES_FLAT, - COPY_FAIL_MESSAGE, + OLD_COPY_FAIL_MESSAGE, ); };
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 7998d2d..69e0f0d0 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -323,7 +323,10 @@ "/DELAYLOAD:dwmapi.dll", "/DELAYLOAD:dxgi.dll", ] - deps += [ "//ui/gfx/mojom:dxgi_info" ] + deps += [ + "//ui/base", + "//ui/gfx/mojom:dxgi_info", + ] assert(use_egl) data_deps += [
diff --git a/ui/gl/DEPS b/ui/gl/DEPS index e5c17f6c..8f52725 100644 --- a/ui/gl/DEPS +++ b/ui/gl/DEPS
@@ -6,6 +6,7 @@ "+third_party/skia", "+ui/events", "+ui/base/x", + "+ui/base/moving_max.h", "+ui/gfx", "+ui/ozone/buildflags.h", "+third_party/angle/src/gpu_info_util/SystemInfo.h",
diff --git a/ui/gl/dc_layer_tree.cc b/ui/gl/dc_layer_tree.cc index 7f0acee..aefac48 100644 --- a/ui/gl/dc_layer_tree.cc +++ b/ui/gl/dc_layer_tree.cc
@@ -25,9 +25,8 @@ namespace gl { namespace { -bool SizeContains(const gfx::Size& a, const gfx::Size& b) { - return gfx::Rect(a).Contains(gfx::Rect(b)); -} + +constexpr size_t kVideoProcessorDimensionsWindowSize = 100; bool NeedSwapChainPresenter(const DCLayerOverlayParams* overlay) { if (overlay->background_color.has_value()) { @@ -87,6 +86,10 @@ force_dcomp_triple_buffer_video_swap_chain_( force_dcomp_triple_buffer_video_swap_chain), no_downscaled_overlay_promotion_(no_downscaled_overlay_promotion), + max_video_processor_input_height_(kVideoProcessorDimensionsWindowSize), + max_video_processor_input_width_(kVideoProcessorDimensionsWindowSize), + max_video_processor_output_height_(kVideoProcessorDimensionsWindowSize), + max_video_processor_output_width_(kVideoProcessorDimensionsWindowSize), ink_renderer_(std::make_unique<DelegatedInkRenderer>()) {} DCLayerTree::~DCLayerTree() = default; @@ -153,40 +156,52 @@ VideoProcessorWrapper* DCLayerTree::InitializeVideoProcessor( const gfx::Size& input_size, - const gfx::Size& output_size, - bool is_hdr_output) { - VideoProcessorWrapper& video_processor_wrapper = - GetOrCreateVideoProcessor(is_hdr_output); - - if (!video_processor_wrapper.video_device) { + const gfx::Size& output_size) { + if (!video_processor_wrapper_.video_device) { // This can fail if the D3D device is "Microsoft Basic Display Adapter". - if (FAILED(d3d11_device_.As(&video_processor_wrapper.video_device))) { + if (FAILED(d3d11_device_.As(&video_processor_wrapper_.video_device))) { DLOG(ERROR) << "Failed to retrieve video device from D3D11 device"; DCHECK(false); DisableDirectCompositionOverlays(); return nullptr; } - DCHECK(video_processor_wrapper.video_device); + DCHECK(video_processor_wrapper_.video_device); Microsoft::WRL::ComPtr<ID3D11DeviceContext> context; d3d11_device_->GetImmediateContext(&context); DCHECK(context); - context.As(&video_processor_wrapper.video_context); - DCHECK(video_processor_wrapper.video_context); + context.As(&video_processor_wrapper_.video_context); + DCHECK(video_processor_wrapper_.video_context); } - if (video_processor_wrapper.video_processor && - SizeContains(video_processor_wrapper.video_input_size, input_size) && - SizeContains(video_processor_wrapper.video_output_size, output_size)) - return &video_processor_wrapper; + // Calculate input and output size to be maximum in a sliding window. + max_video_processor_input_width_.Put(input_size.width()); + max_video_processor_input_height_.Put(input_size.height()); + max_video_processor_output_width_.Put(output_size.width()); + max_video_processor_output_height_.Put(output_size.height()); + gfx::Size effective_input_size(max_video_processor_input_width_.Max(), + max_video_processor_input_height_.Max()); + gfx::Size effective_output_size(max_video_processor_output_width_.Max(), + max_video_processor_output_height_.Max()); + + // Reuse existing video processor only if it has exactly the computed size. + // Even if it may have bigger dimensions and may be reusable for requested + // sizes we will recreate it to reduce resource usage. Sliding window max + // above guarantees that this reduction will only happen after prolonged usage + // with smaller texture sizes. + if (video_processor_wrapper_.video_processor && + video_processor_wrapper_.video_input_size == effective_input_size && + video_processor_wrapper_.video_output_size == effective_output_size) { + return &video_processor_wrapper_; + } TRACE_EVENT2("gpu", "DCLayerTree::InitializeVideoProcessor", "input_size", input_size.ToString(), "output_size", output_size.ToString()); - video_processor_wrapper.video_input_size = input_size; - video_processor_wrapper.video_output_size = output_size; - video_processor_wrapper.video_processor.Reset(); - video_processor_wrapper.video_processor_enumerator.Reset(); + video_processor_wrapper_.video_input_size = effective_input_size; + video_processor_wrapper_.video_output_size = effective_output_size; + video_processor_wrapper_.video_processor.Reset(); + video_processor_wrapper_.video_processor_enumerator.Reset(); D3D11_VIDEO_PROCESSOR_CONTENT_DESC desc = {}; desc.InputFrameFormat = D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE; desc.InputFrameRate.Numerator = 60; @@ -199,8 +214,8 @@ desc.OutputHeight = output_size.height(); desc.Usage = D3D11_VIDEO_USAGE_PLAYBACK_NORMAL; HRESULT hr = - video_processor_wrapper.video_device->CreateVideoProcessorEnumerator( - &desc, &video_processor_wrapper.video_processor_enumerator); + video_processor_wrapper_.video_device->CreateVideoProcessorEnumerator( + &desc, &video_processor_wrapper_.video_processor_enumerator); if (FAILED(hr)) { DLOG(ERROR) << "CreateVideoProcessorEnumerator failed with error 0x" << std::hex << hr; @@ -209,9 +224,9 @@ DisableDirectCompositionOverlays(); return nullptr; } - hr = video_processor_wrapper.video_device->CreateVideoProcessor( - video_processor_wrapper.video_processor_enumerator.Get(), 0, - &video_processor_wrapper.video_processor); + hr = video_processor_wrapper_.video_device->CreateVideoProcessor( + video_processor_wrapper_.video_processor_enumerator.Get(), 0, + &video_processor_wrapper_.video_processor); if (FAILED(hr)) { DLOG(ERROR) << "CreateVideoProcessor failed with error 0x" << std::hex << hr; @@ -221,18 +236,10 @@ return nullptr; } // Auto stream processing (the default) can hurt power consumption. - video_processor_wrapper.video_context + video_processor_wrapper_.video_context ->VideoProcessorSetStreamAutoProcessingMode( - video_processor_wrapper.video_processor.Get(), 0, FALSE); - return &video_processor_wrapper; -} - -VideoProcessorWrapper& DCLayerTree::GetOrCreateVideoProcessor(bool is_hdr) { - VideoProcessorType video_processor_type = - is_hdr ? VideoProcessorType::kHDR : VideoProcessorType::kSDR; - return video_processor_map_ - .try_emplace(video_processor_type, VideoProcessorWrapper()) - .first->second; + video_processor_wrapper_.video_processor.Get(), 0, FALSE); + return &video_processor_wrapper_; } Microsoft::WRL::ComPtr<IDXGISwapChain1>
diff --git a/ui/gl/dc_layer_tree.h b/ui/gl/dc_layer_tree.h index befd290..0a0773b 100644 --- a/ui/gl/dc_layer_tree.h +++ b/ui/gl/dc_layer_tree.h
@@ -14,6 +14,7 @@ #include "base/containers/flat_map.h" #include "mojo/public/cpp/bindings/pending_receiver.h" +#include "ui/base/moving_max.h" #include "ui/gfx/color_space_win.h" #include "ui/gfx/geometry/size.h" #include "ui/gl/dc_layer_overlay_params.h" @@ -33,8 +34,6 @@ class DirectCompositionChildSurfaceWin; class SwapChainPresenter; -enum class VideoProcessorType { kSDR, kHDR }; - // Cache video processor and its size. struct VideoProcessorWrapper { VideoProcessorWrapper(); @@ -63,8 +62,6 @@ // CommitAndClearPendingOverlays(). class GL_EXPORT DCLayerTree { public: - using VideoProcessorMap = - base::flat_map<VideoProcessorType, VideoProcessorWrapper>; using DelegatedInkRenderer = DelegatedInkPointRendererGpu<IDCompositionInkTrailDevice, IDCompositionDelegatedInkTrail, @@ -99,8 +96,7 @@ // layers so the same one can be reused if it's large enough. Returns true on // success. VideoProcessorWrapper* InitializeVideoProcessor(const gfx::Size& input_size, - const gfx::Size& output_size, - bool is_hdr_output); + const gfx::Size& output_size); bool disable_nv12_dynamic_textures() const { return disable_nv12_dynamic_textures_; @@ -122,8 +118,6 @@ return no_downscaled_overlay_promotion_; } - VideoProcessorWrapper& GetOrCreateVideoProcessor(bool is_hdr); - Microsoft::WRL::ComPtr<IDXGISwapChain1> GetLayerSwapChainForTesting( size_t index) const; @@ -454,9 +448,16 @@ // A IDCompositionSurface cleared to white, used for solid color overlays. Microsoft::WRL::ComPtr<IDCompositionSurface> solid_color_texture_; - // Store video processor for SDR/HDR mode separately, which could avoid - // problem in (http://crbug.com/1121061). - VideoProcessorMap video_processor_map_; + // Store the largest video processor to avoid problems in + // (http://crbug.com/1121061) and (http://crbug.com/1472975). + VideoProcessorWrapper video_processor_wrapper_; + // To reduce resource usage, we keep track of the largest input/output + // dimensions for several last VideoProcessor usages. All 4 dimensions must be + // tracked separately. + ui::MovingMax max_video_processor_input_height_; + ui::MovingMax max_video_processor_input_width_; + ui::MovingMax max_video_processor_output_height_; + ui::MovingMax max_video_processor_output_width_; // Current video processor input and output colorspace. gfx::ColorSpace video_input_color_space_;
diff --git a/ui/gl/swap_chain_presenter.cc b/ui/gl/swap_chain_presenter.cc index 5bf409a..7eaa0c1 100644 --- a/ui/gl/swap_chain_presenter.cc +++ b/ui/gl/swap_chain_presenter.cc
@@ -1738,8 +1738,8 @@ gfx::ColorSpace output_color_space = GetOutputColorSpace(src_color_space, is_yuv_swapchain); VideoProcessorWrapper* video_processor_wrapper = - layer_tree_->InitializeVideoProcessor( - content_rect.size(), swap_chain_size_, output_color_space.IsHDR()); + layer_tree_->InitializeVideoProcessor(content_rect.size(), + swap_chain_size_); if (!video_processor_wrapper) return false;
diff --git a/ui/views/test/view_skia_gold_pixel_diff.h b/ui/views/test/view_skia_gold_pixel_diff.h index 782eefa..0f4bff1 100644 --- a/ui/views/test/view_skia_gold_pixel_diff.h +++ b/ui/views/test/view_skia_gold_pixel_diff.h
@@ -8,7 +8,7 @@ #include <string> #include <vector> -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" +#include "base/memory/raw_ptr.h" #include "ui/base/test/skia_gold_pixel_diff.h" #include "ui/gfx/native_widget_types.h"