diff --git a/DEPS b/DEPS index 90b0e7cb..09d9314 100644 --- a/DEPS +++ b/DEPS
@@ -275,11 +275,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '0317614443f8a4d77619b69cae52e92613244dcf', + 'skia_revision': 'd45ffc66de49de91e0be652cf3933940efd410a0', # 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': 'b1413ed7c71ababe05d590de4b5c4ed97b68693e', + 'v8_revision': '55702f825524980a73083f00ad75c9fc9b8fd816', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. @@ -302,7 +302,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Fuchsia sdk # and whatever else without interference from each other. - 'fuchsia_version': 'version:8.20220607.0.1', + 'fuchsia_version': 'version:8.20220607.2.1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling google-toolbox-for-mac # and whatever else without interference from each other. @@ -354,7 +354,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '23e92fb203f44be724ff4f22d3623dcd4c1a088a', + 'devtools_frontend_revision': 'ed6446880ed002cc4d1c79b9b35ec4c9d72625ea', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -920,7 +920,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'X3OVCru2OMw4Pxf6UaS3e0NxseUYtB_jm1VAfM3xtVIC', + 'version': 'Hv4Itz1fIjMhW5YyoWnY4NPZ7dPYr76pHLVwW717k98C', }, ], 'condition': 'checkout_android', @@ -1113,7 +1113,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '071eeb6c55dd3034dcdd546152471a6eb58a4ecc', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'e2b62ac2cfc6aaecac290dc511540534bd9da966', 'condition': 'checkout_chromeos', }, @@ -1136,7 +1136,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '138bff2823590b3f3db440425bf712392defb7de', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'f5d3b1b68b6dc0eb8531fb274754ae5c3cfcbd2b', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1425,7 +1425,7 @@ Var('chromium_git') + '/webm/libwebm.git' + '@' + 'e4fbea0c9751ae8aa86629b197a28d8276a2b0da', 'src/third_party/libyuv': - Var('chromium_git') + '/libyuv/libyuv.git' + '@' + 'd011314f14738e0751dcb269c1d989c4dcbaad7b', + Var('chromium_git') + '/libyuv/libyuv.git' + '@' + 'd62ee21e6627888e84466b5a5ed15775582ac67b', 'src/third_party/lighttpd': { 'url': Var('chromium_git') + '/chromium/deps/lighttpd.git' + '@' + Var('lighttpd_revision'), @@ -1705,10 +1705,10 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'bb289ce3cb15bbabd42fdcb01439367846d9069d', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '3ebdea84d63cd0a0bb5b185b97206494cc0df960', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '9474c0e203c79ec191b18c3d305513282bbda1de', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'fbc6a2db5d187be518ecb653ced1722a912169bd', + Var('webrtc_git') + '/src.git' + '@' + '6383a47b67d9bf3e9d0534f0cc7a8e9975125ebe', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1811,7 +1811,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/help_app/app', - 'version': 'Do0A-bPpxUoGJYAokKHpVI_JkyPVBOCFRTtIp4zjymwC', + 'version': '-r5clhZKMsKXeyTvDOdrDvtevLMbxBxCv4TpRaK5SK4C', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/WATCHLISTS b/WATCHLISTS index 2c124f28..8764483e 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1514,6 +1514,10 @@ 'os_crypt': { 'filepath': 'components/os_crypt/', }, + 'os_feedback_ui': { + 'filepath': 'ash/webui/os_feedback_ui/|' \ + 'chrome/browser/ash/os_feedback/' + }, 'ozone': { 'filepath': 'ui/ozone/|'\ 'ui/events/ozone/|'\ @@ -2712,6 +2716,13 @@ 'origin_trials': ['chasej+watch@chromium.org', 'iclelland+watch@chromium.org'], 'os_crypt': ['wfh+watch@chromium.org'], + 'os_feedback_ui': ['ashleydp+feedback-watch@google.com', + 'cambickel+feedback-watch@google.com', + 'longbowei+feedback-watch@google.com', + 'wangdanny+feedback-watch@google.com', + 'xiangdongkong+feedback-watch@google.com', + 'yyhyyh+feedback-watch@google.com', + 'zhangwenyu+feedback-watch@google.com'], 'ozone': ['ozone-reviews@chromium.org'], 'ozone_fuchsia': ['dworsham@google.com', 'emircan@google.com',
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index a9cdd3f..104b882 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -317,7 +317,7 @@ if (delegate_) { delegate_->DidAcceptSuggestion(suggestions_[position].main_text.value, suggestions_[position].frontend_id, - suggestions_[position].backend_id, position); + suggestions_[position].payload, position); } }
diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc index 52de48c..b1c75cba6 100644 --- a/android_webview/browser/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -417,7 +417,7 @@ const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::RenderProcessHost* host = - web_contents_->GetMainFrame()->GetProcess(); + web_contents_->GetPrimaryMainFrame()->GetProcess(); if (host->run_renderer_in_process()) { return ScopedJavaLocalRef<jobject>(); } @@ -794,7 +794,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); AwRenderProcess* aw_render_process = AwRenderProcess::GetInstanceForRenderProcessHost( - web_contents_->GetMainFrame()->GetProcess()); + web_contents_->GetPrimaryMainFrame()->GetProcess()); aw_render_process->ClearCache(); @@ -1358,7 +1358,7 @@ jlong request_id, const JavaParamRef<jobject>& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - web_contents_->GetMainFrame()->InsertVisualStateCallback( + web_contents_->GetPrimaryMainFrame()->InsertVisualStateCallback( base::BindOnce(&InvokeVisualStateCallback, java_ref_, request_id, ScopedJavaGlobalRef<jobject>(env, callback))); } @@ -1366,8 +1366,9 @@ jint AwContents::GetEffectivePriority( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { - switch ( - web_contents_->GetMainFrame()->GetProcess()->GetEffectiveImportance()) { + switch (web_contents_->GetPrimaryMainFrame() + ->GetProcess() + ->GetEffectiveImportance()) { case content::ChildProcessImportance::NORMAL: return static_cast<jint>(RendererPriority::WAIVED); case content::ChildProcessImportance::MODERATE: @@ -1480,7 +1481,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); AwRenderProcess* aw_render_process = AwRenderProcess::GetInstanceForRenderProcessHost( - web_contents_->GetMainFrame()->GetProcess()); + web_contents_->GetPrimaryMainFrame()->GetProcess()); aw_render_process->SetJsOnlineProperty(network_up); } @@ -1515,7 +1516,8 @@ JNIEnv* env, const JavaParamRef<jobject>& obj) { content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestScheme( - web_contents_->GetMainFrame()->GetProcess()->GetID(), url::kFileScheme); + web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(), + url::kFileScheme); } void AwContents::ResumeLoadingCreatedPopupWebContents(
diff --git a/android_webview/browser/aw_contents_io_thread_client.cc b/android_webview/browser/aw_contents_io_thread_client.cc index 5963e4c..1b2fe92 100644 --- a/android_webview/browser/aw_contents_io_thread_client.cc +++ b/android_webview/browser/aw_contents_io_thread_client.cc
@@ -199,8 +199,8 @@ DCHECK(web_contents); DCHECK(jdelegate); - if (web_contents->GetMainFrame()) - RenderFrameCreated(web_contents->GetMainFrame()); + if (web_contents->GetPrimaryMainFrame()) + RenderFrameCreated(web_contents->GetPrimaryMainFrame()); } void ClientMapEntryUpdater::RenderFrameCreated(RenderFrameHost* rfh) {
diff --git a/android_webview/browser/aw_print_manager.cc b/android_webview/browser/aw_print_manager.cc index 3452426..39b255d 100644 --- a/android_webview/browser/aw_print_manager.cc +++ b/android_webview/browser/aw_print_manager.cc
@@ -63,7 +63,7 @@ bool AwPrintManager::PrintNow() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto* rfh = web_contents()->GetMainFrame(); + auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh->IsRenderFrameLive()) return false; GetPrintRenderFrame(rfh)->PrintRequestedPages();
diff --git a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc index 318eb25..31c07ca 100644 --- a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc +++ b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc
@@ -152,7 +152,7 @@ // Make sense from any frame of the current frame tree, because a focused // node could be in either the mainframe or a subframe. - if (main_frame_host != web_contents()->GetMainFrame()) + if (main_frame_host != web_contents()->GetPrimaryMainFrame()) return; DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -165,7 +165,7 @@ frame_host_receivers_.GetCurrentTargetFrame(); // Only makes sense coming from the main frame of the current frame tree. - if (render_frame_host != web_contents()->GetMainFrame()) + if (render_frame_host != web_contents()->GetPrimaryMainFrame()) return; client_->OnWebLayoutContentsSizeChanged(contents_size); @@ -203,7 +203,7 @@ // RenderFrameCreated/RenderFrameHostChanged events but the timings of when // this class gets called vs others using this class might cause a TOU // problem, so we validate it each time before use. - content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); + content::RenderFrameHost* main_frame = web_contents()->GetPrimaryMainFrame(); content::GlobalRenderFrameHostId main_frame_id = main_frame->GetGlobalId(); if (main_frame_global_id_ == main_frame_id) { return local_main_frame_remote_.get();
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index d88c623..1e7fea0 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -354,6 +354,10 @@ "clipboard/views/clipboard_history_text_item_view.cc", "clipboard/views/clipboard_history_text_item_view.h", "clipboard/views/clipboard_history_view_constants.h", + "controls/contextual_nudge.cc", + "controls/contextual_nudge.h", + "controls/contextual_tooltip.cc", + "controls/contextual_tooltip.h", "controls/gradient_layer_delegate.cc", "controls/gradient_layer_delegate.h", "controls/rounded_scroll_bar.cc", @@ -830,10 +834,6 @@ "shelf/assistant_overlay.h", "shelf/back_button.cc", "shelf/back_button.h", - "shelf/contextual_nudge.cc", - "shelf/contextual_nudge.h", - "shelf/contextual_tooltip.cc", - "shelf/contextual_tooltip.h", "shelf/drag_handle.cc", "shelf/drag_handle.h", "shelf/drag_window_from_shelf_controller.cc", @@ -2515,6 +2515,7 @@ "clipboard/clipboard_history_unittest.cc", "clipboard/clipboard_history_util_unittest.cc", "clipboard/clipboard_nudge_controller_unittest.cc", + "controls/contextual_tooltip_unittest.cc", "controls/rounded_scroll_bar_unittest.cc", "controls/scroll_view_gradient_helper_unittest.cc", "dbus/gesture_properties_service_provider_unittest.cc", @@ -2648,7 +2649,6 @@ "session/session_controller_impl_unittest.cc", "shelf/assistant_overlay_unittest.cc", "shelf/back_button_unittest.cc", - "shelf/contextual_tooltip_unittest.cc", "shelf/drag_handle_unittest.cc", "shelf/drag_window_from_shelf_controller_test_api.cc", "shelf/drag_window_from_shelf_controller_test_api.h", @@ -2983,7 +2983,10 @@ "//ash/assistant/util", "//ash/components/arc:notification_test_support", "//ash/components/audio", + "//ash/components/cryptohome", "//ash/components/geolocation", + "//ash/components/login/auth", + "//ash/components/login/auth:test_support", "//ash/components/phonehub:test_support", "//ash/components/settings", "//ash/constants", @@ -3027,6 +3030,7 @@ "//chromeos/components/sensors:test_support", "//chromeos/components/sensors/mojom", "//chromeos/constants", + "//chromeos/crosapi/cpp", "//chromeos/dbus:test_support", "//chromeos/dbus/audio", "//chromeos/dbus/hermes", @@ -3034,6 +3038,7 @@ "//chromeos/dbus/human_presence:hps_proto", "//chromeos/dbus/power", "//chromeos/dbus/power:power_manager_proto", + "//chromeos/dbus/userdataauth", "//chromeos/network:test_support", "//chromeos/services/assistant/public/cpp", "//chromeos/services/assistant/public/mojom",
diff --git a/ash/ambient/ambient_controller.cc b/ash/ambient/ambient_controller.cc index 423e815..747186a 100644 --- a/ash/ambient/ambient_controller.cc +++ b/ash/ambient/ambient_controller.cc
@@ -615,7 +615,10 @@ DCHECK(AmbientClient::Get()); ambient_photo_controller_ = std::make_unique<AmbientPhotoController>( *AmbientClient::Get(), access_token_controller_, delegate_, - CreatePhotoConfigForCurrentTheme()); + // The type of photo config specified here is actually irrelevant as it + // always gets reset with the correct configuration anyways in + // StartRefreshingImages() before ambient mode starts. + CreateAmbientSlideshowPhotoConfig()); ambient_ui_model_observer_.Observe(&ambient_ui_model_); @@ -785,8 +788,10 @@ std::unique_ptr<views::Widget> AmbientController::CreateWidget( aura::Window* container) { + AmbientAnimationTheme current_theme = GetCurrentTheme(); auto container_view = std::make_unique<AmbientContainerView>( - &delegate_, std::move(pending_animation_static_resources_)); + &delegate_, AmbientAnimationStaticResources::Create( + current_theme, /*serializable=*/true)); auto* widget_delegate = new AmbientWidgetDelegate(); widget_delegate->SetInitiallyFocusedView(container_view.get()); @@ -816,7 +821,7 @@ DCHECK(start_time_); ambient::RecordAmbientModeStartupTime(base::Time::Now() - *start_time_, - GetCurrentTheme()); + current_theme); // Only announce for the primary window. if (Shell::GetPrimaryRootWindow() == container->GetRootWindow()) { @@ -843,17 +848,27 @@ // model/controller with the appropriate config each time before calling // StartScreenUpdate(). DCHECK(!ambient_photo_controller_->IsScreenUpdateActive()); - ambient_photo_controller_->ambient_backend_model()->SetPhotoConfig( - CreatePhotoConfigForCurrentTheme()); + AmbientAnimationTheme current_theme = GetCurrentTheme(); + DVLOG(4) << "Loaded ambient theme " << ToString(current_theme); + + AmbientPhotoConfig photo_config; std::unique_ptr<AmbientTopicQueue::Delegate> topic_queue_delegate; - if (pending_animation_static_resources_) { - topic_queue_delegate = std::make_unique<AmbientTopicQueueAnimationDelegate>( - pending_animation_static_resources_->GetSkottieWrapper() - ->GetImageAssetMetadata()); - } else { + if (current_theme == AmbientAnimationTheme::kSlideshow) { + photo_config = CreateAmbientSlideshowPhotoConfig(); topic_queue_delegate = std::make_unique<AmbientTopicQueueSlideshowDelegate>(); + } else { + scoped_refptr<cc::SkottieWrapper> animation = + AmbientAnimationStaticResources::Create(current_theme, + /*serializable=*/false) + ->GetSkottieWrapper(); + photo_config = + CreateAmbientAnimationPhotoConfig(animation->GetImageAssetMetadata()); + topic_queue_delegate = std::make_unique<AmbientTopicQueueAnimationDelegate>( + animation->GetImageAssetMetadata()); } + ambient_photo_controller_->ambient_backend_model()->SetPhotoConfig( + std::move(photo_config)); ambient_photo_controller_->StartScreenUpdate(std::move(topic_queue_delegate)); } @@ -862,22 +877,6 @@ ambient_photo_controller_->StopScreenUpdate(); } -AmbientPhotoConfig AmbientController::CreatePhotoConfigForCurrentTheme() { - AmbientAnimationTheme current_theme = GetCurrentTheme(); - DVLOG(4) << "Loaded ambient theme " << ToString(current_theme); - - pending_animation_static_resources_.reset(); - if (current_theme == AmbientAnimationTheme::kSlideshow) { - return CreateAmbientSlideshowPhotoConfig(); - } else { - pending_animation_static_resources_ = - AmbientAnimationStaticResources::Create(current_theme); - return CreateAmbientAnimationPhotoConfig( - pending_animation_static_resources_->GetSkottieWrapper() - ->GetImageAssetMetadata()); - } -} - AmbientAnimationTheme AmbientController::GetCurrentTheme() const { AmbientAnimationTheme current_theme = kDefaultAmbientAnimationTheme; absl::optional<bool> animation_experiment_enabled =
diff --git a/ash/ambient/ambient_controller.h b/ash/ambient/ambient_controller.h index 455f99f..86c9441a 100644 --- a/ash/ambient/ambient_controller.h +++ b/ash/ambient/ambient_controller.h
@@ -44,7 +44,6 @@ namespace ash { -class AmbientAnimationStaticResources; class AmbientBackendController; class AmbientContainerView; class AmbientPhotoController; @@ -166,7 +165,6 @@ void StartRefreshingImages(); void StopRefreshingImages(); - AmbientPhotoConfig CreatePhotoConfigForCurrentTheme(); AmbientAnimationTheme GetCurrentTheme() const; // Invoked when the auto-show timer in |InactivityMonitor| gets fired after @@ -246,14 +244,6 @@ // called. Used to prevent Ambient mode starting after screen is off. bool is_screen_off_ = false; - // Transient location to hold an animation's static resources while the - // model is being buffered with an initial set of topics. Once the animation - // is ready to be rendered, this gets transferred to an AmbientAnimationView. - // - // Null if the slideshow theme is active. - std::unique_ptr<AmbientAnimationStaticResources> - pending_animation_static_resources_; - // Not set until the AmbientAnimationTheme is initially read from pref // storage when ambient mode is enabled. absl::optional<AmbientAnimationTheme> current_theme_from_pref_;
diff --git a/ash/ambient/ambient_controller_unittest.cc b/ash/ambient/ambient_controller_unittest.cc index f330a3a..a4e90de9 100644 --- a/ash/ambient/ambient_controller_unittest.cc +++ b/ash/ambient/ambient_controller_unittest.cc
@@ -907,6 +907,12 @@ auto* screen = display::Screen::GetScreen(); EXPECT_EQ(screen->GetNumDisplays(), 2); EXPECT_EQ(GetContainerViews().size(), 2u); + AmbientViewID expected_child_view_id = + GetParam() == AmbientAnimationTheme::kSlideshow + ? AmbientViewID::kAmbientPhotoView + : AmbientViewID::kAmbientAnimationView; + EXPECT_TRUE(GetContainerViews().front()->GetViewByID(expected_child_view_id)); + EXPECT_TRUE(GetContainerViews().back()->GetViewByID(expected_child_view_id)); // Check that each root controller has an ambient widget. for (auto* ctrl : RootWindowController::root_window_controllers()) EXPECT_TRUE(ctrl->ambient_widget_for_testing() &&
diff --git a/ash/ambient/resources/ambient_animation_static_resources.h b/ash/ambient/resources/ambient_animation_static_resources.h index 84a78ea..26740841 100644 --- a/ash/ambient/resources/ambient_animation_static_resources.h +++ b/ash/ambient/resources/ambient_animation_static_resources.h
@@ -36,8 +36,14 @@ public: // Creates an AmbientAnimationStaticResources instance that loads resources // for the given |theme|. Returns nullptr if |theme| is not supported. + // + // If |serializable| is true, GetSkottieWrapper() will return an animation + // that can be used for out-of-process rasterization in the graphics pipeline. + // If false, resource creation is cheaper and uses less memory but cannot be + // used for OOP rasterization. static std::unique_ptr<AmbientAnimationStaticResources> Create( - AmbientAnimationTheme theme); + AmbientAnimationTheme theme, + bool serializable); virtual ~AmbientAnimationStaticResources() = default;
diff --git a/ash/ambient/resources/ambient_animation_static_resources_impl.cc b/ash/ambient/resources/ambient_animation_static_resources_impl.cc index 16b70b0..57ffd02 100644 --- a/ash/ambient/resources/ambient_animation_static_resources_impl.cc +++ b/ash/ambient/resources/ambient_animation_static_resources_impl.cc
@@ -94,17 +94,23 @@ } scoped_refptr<cc::SkottieWrapper> CreateSkottieWrapper( - int lottie_json_resource_id) { + int lottie_json_resource_id, + bool serializable) { base::StringPiece animation_json = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( lottie_json_resource_id); DCHECK(!animation_json.empty()); base::span<const uint8_t> lottie_data_bytes = base::as_bytes(base::make_span(animation_json)); - // Create a serializable SkottieWrapper since the SkottieWrapper may have to - // be serialized and transmitted over IPC for out-of-process rasterization. - auto animation = cc::SkottieWrapper::CreateSerializable( - std::vector<uint8_t>(lottie_data_bytes.begin(), lottie_data_bytes.end())); + scoped_refptr<cc::SkottieWrapper> animation; + if (serializable) { + // Create a serializable SkottieWrapper since the SkottieWrapper may have to + // be serialized and transmitted over IPC for out-of-process rasterization. + animation = cc::SkottieWrapper::CreateSerializable(std::vector<uint8_t>( + lottie_data_bytes.begin(), lottie_data_bytes.end())); + } else { + animation = cc::SkottieWrapper::CreateNonSerializable(lottie_data_bytes); + } DCHECK(animation); DCHECK(animation->is_valid()); return animation; @@ -116,9 +122,11 @@ AmbientAnimationStaticResourcesImpl( AmbientAnimationTheme theme, int lottie_json_resource_id, - base::flat_map<base::StringPiece, int> asset_id_to_resource_id) + base::flat_map<base::StringPiece, int> asset_id_to_resource_id, + bool create_serializable_skottie) : theme_(theme), - animation_(CreateSkottieWrapper(lottie_json_resource_id)), + animation_(CreateSkottieWrapper(lottie_json_resource_id, + create_serializable_skottie)), asset_id_to_resource_id_(std::move(asset_id_to_resource_id)) { DCHECK(animation_); } @@ -164,13 +172,14 @@ // static std::unique_ptr<AmbientAnimationStaticResources> -AmbientAnimationStaticResources::Create(AmbientAnimationTheme theme) { +AmbientAnimationStaticResources::Create(AmbientAnimationTheme theme, + bool serializable) { if (!GetAnimationThemeToLottieResourceIdMap().contains(theme)) return nullptr; return std::make_unique<AmbientAnimationStaticResourcesImpl>( theme, GetAnimationThemeToLottieResourceIdMap().at(theme), - GetAssetIdToResourceIdMapForTheme(theme)); + GetAssetIdToResourceIdMapForTheme(theme), serializable); } } // namespace ash
diff --git a/ash/ambient/resources/ambient_animation_static_resources_impl_unittest.cc b/ash/ambient/resources/ambient_animation_static_resources_impl_unittest.cc index 2f0b9f9..ad762b2 100644 --- a/ash/ambient/resources/ambient_animation_static_resources_impl_unittest.cc +++ b/ash/ambient/resources/ambient_animation_static_resources_impl_unittest.cc
@@ -26,14 +26,14 @@ TEST(AmbientAnimationStaticResourcesTest, LoadsLottieData) { auto resources = AmbientAnimationStaticResources::Create( - AmbientAnimationTheme::kFeelTheBreeze); + AmbientAnimationTheme::kFeelTheBreeze, /*serializable=*/false); ASSERT_THAT(resources->GetSkottieWrapper(), NotNull()); EXPECT_TRUE(resources->GetSkottieWrapper()->is_valid()); } TEST(AmbientAnimationStaticResourcesTest, LoadsStaticAssets) { auto resources = AmbientAnimationStaticResources::Create( - AmbientAnimationTheme::kFeelTheBreeze); + AmbientAnimationTheme::kFeelTheBreeze, /*serializable=*/false); ASSERT_THAT(resources, NotNull()); for (base::StringPiece asset_id : ambient::resources::kAllFeelTheBreezeStaticAssets) { @@ -47,13 +47,13 @@ TEST(AmbientAnimationStaticResourcesTest, FailsForSlideshowTheme) { EXPECT_THAT(AmbientAnimationStaticResources::Create( - AmbientAnimationTheme::kSlideshow), + AmbientAnimationTheme::kSlideshow, /*serializable=*/false), IsNull()); } TEST(AmbientAnimationStaticResourcesTest, FailsForUnknownAssetId) { auto resources = AmbientAnimationStaticResources::Create( - AmbientAnimationTheme::kFeelTheBreeze); + AmbientAnimationTheme::kFeelTheBreeze, /*serializable=*/false); ASSERT_THAT(resources, NotNull()); gfx::ImageSkia image = resources->GetStaticImageAsset("unknown_asset_id"); EXPECT_TRUE(image.isNull());
diff --git a/ash/ambient/resources/ambient_animation_static_resources_stub.cc b/ash/ambient/resources/ambient_animation_static_resources_stub.cc index 6b6694d..a994a1a 100644 --- a/ash/ambient/resources/ambient_animation_static_resources_stub.cc +++ b/ash/ambient/resources/ambient_animation_static_resources_stub.cc
@@ -18,7 +18,11 @@ // static std::unique_ptr<AmbientAnimationStaticResources> -AmbientAnimationStaticResources::Create(AmbientAnimationTheme theme) { +AmbientAnimationStaticResources::Create(AmbientAnimationTheme theme, + bool serializable) { + if (theme == AmbientAnimationTheme::kSlideshow) + return nullptr; + LOG(FATAL) << "Ambient animation resources are not available on this build. " "To enable, an internal chrome-branded checkout is required, " "and the include_ash_ambient_animation_resources GN flag must "
diff --git a/ash/ambient/ui/ambient_container_view.cc b/ash/ambient/ui/ambient_container_view.cc index 20f5c325..7dd61d26 100644 --- a/ash/ambient/ui/ambient_container_view.cc +++ b/ash/ambient/ui/ambient_container_view.cc
@@ -13,6 +13,7 @@ #include "ash/ambient/ui/ambient_view_ids.h" #include "ash/ambient/ui/photo_view.h" #include "ash/ambient/util/ambient_util.h" +#include "ash/public/cpp/ambient/ambient_metrics.h" #include "ash/public/cpp/shell_window_ids.h" #include "base/check.h" #include "ui/aura/window.h" @@ -40,12 +41,20 @@ // Updates focus behavior to receive key press events. SetFocusBehavior(views::View::FocusBehavior::ALWAYS); SetLayoutManager(std::make_unique<views::FillLayout>()); + View* main_rendering_view = nullptr; + AmbientAnimationTheme theme = + animation_static_resources + ? animation_static_resources->GetAmbientAnimationTheme() + : AmbientAnimationTheme::kSlideshow; if (animation_static_resources) { - AddChildView(std::make_unique<AmbientAnimationView>( + main_rendering_view = AddChildView(std::make_unique<AmbientAnimationView>( delegate, std::move(animation_static_resources))); } else { - AddChildView(std::make_unique<PhotoView>(delegate)); + main_rendering_view = AddChildView(std::make_unique<PhotoView>(delegate)); } + orientation_metrics_recorder_ = + std::make_unique<ambient::AmbientOrientationMetricsRecorder>( + main_rendering_view, theme); } AmbientContainerView::~AmbientContainerView() = default;
diff --git a/ash/ambient/ui/ambient_container_view.h b/ash/ambient/ui/ambient_container_view.h index b9b3fab..aeaa1df7 100644 --- a/ash/ambient/ui/ambient_container_view.h +++ b/ash/ambient/ui/ambient_container_view.h
@@ -5,6 +5,8 @@ #ifndef ASH_AMBIENT_UI_AMBIENT_CONTAINER_VIEW_H_ #define ASH_AMBIENT_UI_AMBIENT_CONTAINER_VIEW_H_ +#include <memory> + #include "ash/ash_export.h" #include "ui/views/view.h" @@ -13,6 +15,10 @@ class AmbientAnimationStaticResources; class AmbientViewDelegateImpl; +namespace ambient { +class AmbientOrientationMetricsRecorder; +} // namespace ambient + // Container view to display all Ambient Mode related views, i.e. photo frame, // weather info. class ASH_EXPORT AmbientContainerView : public views::View { @@ -29,6 +35,9 @@ private: friend class AmbientAshTestBase; + + std::unique_ptr<ambient::AmbientOrientationMetricsRecorder> + orientation_metrics_recorder_; }; } // namespace ash
diff --git a/ash/ash_prefs.cc b/ash/ash_prefs.cc index d2401f6..5cd54d6c 100644 --- a/ash/ash_prefs.cc +++ b/ash/ash_prefs.cc
@@ -14,6 +14,7 @@ #include "ash/clipboard/clipboard_nudge_controller.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/detachable_base/detachable_base_handler.h" #include "ash/display/display_prefs.h" #include "ash/display/privacy_screen_controller.h" @@ -26,7 +27,6 @@ #include "ash/public/cpp/holding_space/holding_space_prefs.h" #include "ash/quick_pair/keyed_service/quick_pair_mediator.h" #include "ash/session/fullscreen_controller.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/shelf_controller.h" #include "ash/style/ash_color_provider.h" #include "ash/style/dark_mode_controller.h"
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 57a7fb6f..a5fd46a9 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -1756,7 +1756,7 @@ Toggle marker. <ph name="STATE_TEXT">$1<ex>Marker is on.</ex></ph> </message> - <message name="IDS_ASH_STATUS_AREA_PROJECTOR_ANNOTATION_TRAY_ACCESSIBLE_TITLE" desc="The accessible title for the projector marker button in the system tray, telling the user how to use the marker."> + <message name="IDS_ASH_STATUS_AREA_PROJECTOR_ANNOTATION_TRAY_ACCESSIBLE_TITLE" desc="The accessible title for the projector marker button in the system tray, telling the user how to use the marker."> Toggle marker. <ph name="STATE_TEXT">$1<ex>Marker is on.</ex></ph> Use the trackpad, touchscreen, or stylus to draw onscreen. </message> @@ -3563,6 +3563,10 @@ <ph name="date">$1<ex>August 31, 2021</ex></ph>, <ph name="number">$2<ex>8</ex></ph> events </message> + <message name="IDS_ASH_CALENDAR_DATE_CELL_LOADING_TOOLTIP" desc="The tooltip of a calendar date cell when the events are loading."> + <ph name="date">$1<ex>August 31, 2021</ex></ph>, Loading events. + </message> + <message name="IDS_ASH_CALENDAR_DATE_CELL_ON_FOCUS_ACCESSIBLE_DESCRIPTION" desc="The accessible label of a calendar date cell, which is on focused for the first time."> <ph name="date_cell_tool_tip">$1<ex>August 31, 2021, 2 events</ex></ph>. Use arrow keys to navigate between dates. </message> @@ -3576,9 +3580,9 @@ </message> <message name="IDS_ASH_CALENDAR_EVENT_ENTRY_ACCESSIBLE_DESCRIPTION" desc="The accessible label of a calendar event entry."> - <ph name="start_time">$1<ex>12 PM</ex></ph> to - <ph name="end_time">$2<ex>1 PM</ex></ph>, - <ph name="time_zone">$3<ex>Pacific time</ex></ph>, + <ph name="start_time">$1<ex>12 PM</ex></ph> to + <ph name="end_time">$2<ex>1 PM</ex></ph>, + <ph name="time_zone">$3<ex>Pacific time</ex></ph>, <ph name="event_summary">$4<ex>Lunch break</ex></ph>. Select for more details in Google Calendar. </message> @@ -3602,6 +3606,10 @@ Open in Google calendar </message> + <message name="IDS_ASH_STATUS_TRAY_PROGRESS_BAR_ACCESSIBLE_NAME" desc="The accessible name for the progress bar shown in the status tray."> + Loading + </message> + <!-- Power off menu --> <message name="IDS_ASH_POWER_BUTTON_MENU_POWER_OFF_BUTTON" desc="Text shown on power off button in power button menu."> Shut down
diff --git a/ash/ash_strings_grd/IDS_ASH_CALENDAR_DATE_CELL_LOADING_TOOLTIP.png.sha1 b/ash/ash_strings_grd/IDS_ASH_CALENDAR_DATE_CELL_LOADING_TOOLTIP.png.sha1 new file mode 100644 index 0000000..8edb6eab --- /dev/null +++ b/ash/ash_strings_grd/IDS_ASH_CALENDAR_DATE_CELL_LOADING_TOOLTIP.png.sha1
@@ -0,0 +1 @@ +5616682bef60f37819a297578b625bf0b86dc582 \ No newline at end of file
diff --git a/ash/capture_mode/capture_mode_camera_preview_view.cc b/ash/capture_mode/capture_mode_camera_preview_view.cc index 492d3a4..273e8ea 100644 --- a/ash/capture_mode/capture_mode_camera_preview_view.cc +++ b/ash/capture_mode/capture_mode_camera_preview_view.cc
@@ -327,8 +327,9 @@ // a render surface. This also avoids the rendering artifacts seen in // https://crbug.com/1312059. DCHECK_EQ(width(), height()); - camera_video_renderer_.host_window()->layer()->SetRoundedCornerRadius( - gfx::RoundedCornersF(height() / 2.f)); + auto* layer = camera_video_renderer_.host_window()->layer(); + layer->SetRoundedCornerRadius(gfx::RoundedCornersF(height() / 2.f)); + layer->SetIsFastRoundedCorner(true); // Refocus the camera preview to relayout the focus ring on it. if (has_focus())
diff --git a/ash/components/login/auth/BUILD.gn b/ash/components/login/auth/BUILD.gn index 806f75f51..15225ec 100644 --- a/ash/components/login/auth/BUILD.gn +++ b/ash/components/login/auth/BUILD.gn
@@ -106,6 +106,7 @@ deps = [ ":auth", "//base", + "//chromeos/dbus/userdataauth", "//chromeos/login/login_state", "//components/account_id", "//google_apis", @@ -117,6 +118,8 @@ sources = [ "fake_extended_authenticator.cc", "fake_extended_authenticator.h", + "mock_auth_performer.cc", + "mock_auth_performer.h", "mock_auth_status_consumer.cc", "mock_auth_status_consumer.h", ]
diff --git a/ash/components/login/auth/auth_performer.h b/ash/components/login/auth/auth_performer.h index 8f8ddc9..201a455 100644 --- a/ash/components/login/auth/auth_performer.h +++ b/ash/components/login/auth/auth_performer.h
@@ -32,7 +32,7 @@ AuthPerformer(const AuthPerformer&) = delete; AuthPerformer& operator=(const AuthPerformer&) = delete; - ~AuthPerformer(); + virtual ~AuthPerformer(); using StartSessionCallback = base::OnceCallback<void(bool /* user_exists */, @@ -50,9 +50,9 @@ // fills information about supported (and configured if user exists) keys. // `Context` should not have associated auth session. // Does not authenticate new session. - void StartAuthSession(std::unique_ptr<UserContext> context, - bool ephemeral, - StartSessionCallback callback); + virtual void StartAuthSession(std::unique_ptr<UserContext> context, + bool ephemeral, + StartSessionCallback callback); // Attempts to authenticate session using Key in `context`. // If key is a plain text, it is assumed that it is a knowledge-based key, @@ -75,10 +75,10 @@ // Attempts to authenticate session using plain text password. // Does not fill any password-related fields in `context`. // Session will become authenticated upon success. - void AuthenticateWithPassword(const std::string& key_label, - const std::string& password, - std::unique_ptr<UserContext> context, - AuthOperationCallback callback); + virtual void AuthenticateWithPassword(const std::string& key_label, + const std::string& password, + std::unique_ptr<UserContext> context, + AuthOperationCallback callback); // Attempts to authenticate session using PIN as a factor. // PINs use custom salt stored in LocalState, this salt should be provided
diff --git a/ash/components/login/auth/mock_auth_performer.cc b/ash/components/login/auth/mock_auth_performer.cc new file mode 100644 index 0000000..7eedd77 --- /dev/null +++ b/ash/components/login/auth/mock_auth_performer.cc
@@ -0,0 +1,15 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/components/login/auth/mock_auth_performer.h" +#include "base/memory/raw_ptr.h" + +namespace ash { + +MockAuthPerformer::MockAuthPerformer(base::raw_ptr<UserDataAuthClient> client) + : AuthPerformer(client) {} + +MockAuthPerformer::~MockAuthPerformer() = default; + +} // namespace ash
diff --git a/ash/components/login/auth/mock_auth_performer.h b/ash/components/login/auth/mock_auth_performer.h new file mode 100644 index 0000000..76ca0e8 --- /dev/null +++ b/ash/components/login/auth/mock_auth_performer.h
@@ -0,0 +1,41 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_COMPONENTS_LOGIN_AUTH_MOCK_AUTH_PERFORMER_H_ +#define ASH_COMPONENTS_LOGIN_AUTH_MOCK_AUTH_PERFORMER_H_ + +#include "ash/components/login/auth/auth_performer.h" +#include "ash/components/login/auth/user_context.h" +#include "chromeos/dbus/userdataauth/userdataauth_client.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace ash { + +class MockAuthPerformer : public AuthPerformer { + public: + explicit MockAuthPerformer(base::raw_ptr<UserDataAuthClient> client); + MockAuthPerformer(const MockAuthPerformer&) = delete; + MockAuthPerformer& operator=(const MockAuthPerformer&) = delete; + ~MockAuthPerformer() override; + + // AuthPerformer + MOCK_METHOD(void, + StartAuthSession, + (std::unique_ptr<UserContext> context, + bool ephemeral, + StartSessionCallback callback), + (override)); + + MOCK_METHOD(void, + AuthenticateWithPassword, + (const std::string& key_label, + const std::string& password, + std::unique_ptr<UserContext> context, + AuthOperationCallback callback), + (override)); +}; + +} // namespace ash + +#endif // ASH_COMPONENTS_LOGIN_AUTH_AUTH_PERFORMER_H_
diff --git a/ash/components/phonehub/camera_roll_manager_impl.cc b/ash/components/phonehub/camera_roll_manager_impl.cc index 125e432..2675ad2 100644 --- a/ash/components/phonehub/camera_roll_manager_impl.cc +++ b/ash/components/phonehub/camera_roll_manager_impl.cc
@@ -174,7 +174,7 @@ thumbnail_decoder_->BatchDecode( response, current_items(), base::BindOnce(&CameraRollManagerImpl::OnItemThumbnailsDecoded, - weak_ptr_factory_.GetWeakPtr())); + thumbnail_decoder_weak_ptr_factory_.GetWeakPtr())); } void CameraRollManagerImpl::SendFetchCameraRollItemsRequest() { @@ -214,7 +214,7 @@ } void CameraRollManagerImpl::CancelPendingThumbnailRequests() { - weak_ptr_factory_.InvalidateWeakPtrs(); + thumbnail_decoder_weak_ptr_factory_.InvalidateWeakPtrs(); } bool CameraRollManagerImpl::IsCameraRollSettingEnabled() {
diff --git a/ash/components/phonehub/camera_roll_manager_impl.h b/ash/components/phonehub/camera_roll_manager_impl.h index dafa69b..36e65bc 100644 --- a/ash/components/phonehub/camera_roll_manager_impl.h +++ b/ash/components/phonehub/camera_roll_manager_impl.h
@@ -104,6 +104,10 @@ std::unique_ptr<CameraRollThumbnailDecoder> thumbnail_decoder_; base::WeakPtrFactory<CameraRollManagerImpl> weak_ptr_factory_{this}; + // WeakPtrFactory dedicated to thumbanil decoder callbacks that need to be + // invalidated when the current item set updates. + base::WeakPtrFactory<CameraRollManagerImpl> + thumbnail_decoder_weak_ptr_factory_{this}; }; } // namespace phonehub
diff --git a/ash/components/phonehub/camera_roll_manager_impl_unittest.cc b/ash/components/phonehub/camera_roll_manager_impl_unittest.cc index 5886b4b3..d4951df 100644 --- a/ash/components/phonehub/camera_roll_manager_impl_unittest.cc +++ b/ash/components/phonehub/camera_roll_manager_impl_unittest.cc
@@ -621,6 +621,46 @@ /*bytes_transferred=*/1000); } +TEST_F(CameraRollManagerImplTest, DownloadItemAndCurrentItemsChanged) { + // Make an item available to CameraRollManager. + proto::FetchCameraRollItemsResponse items_response; + PopulateItemProto(items_response.add_items(), "key1"); + fake_message_receiver_.NotifyFetchCameraRollItemsResponseReceived( + items_response); + CompleteThumbnailDecoding(BatchDecodeResult::kCompleted); + const CameraRollItem& item_to_download = + camera_roll_manager()->current_items().back(); + + // Request to download the item that was added. + camera_roll_manager()->DownloadItem(item_to_download.metadata()); + SendFetchCameraRollItemDataResponse( + item_to_download.metadata(), + proto::FetchCameraRollItemDataResponse::AVAILABLE, + /*payload_id=*/1234); + SendFileTransferUpdate(/*payload_id=*/1234, FileTransferStatus::kInProgress, + /*total_bytes=*/1000, /*bytes_transferred=*/200); + + VerifyFileTransferProgress(/*payload_id=*/1234, + FileTransferStatus::kInProgress, + /*total_bytes=*/1000, + /*bytes_transferred=*/200); + + // The item being downloaded is no longer in the current item set, but the + // download should still finish normally. + SendPhoneStatusUpdate(/*has_camera_roll_updates=*/true); + proto::FetchCameraRollItemsResponse new_items_response; + PopulateItemProto(new_items_response.add_items(), "key2"); + fake_message_receiver_.NotifyFetchCameraRollItemsResponseReceived( + new_items_response); + CompleteThumbnailDecoding(BatchDecodeResult::kCompleted); + SendFileTransferUpdate(/*payload_id=*/1234, FileTransferStatus::kSuccess, + /*total_bytes=*/1000, /*bytes_transferred=*/1000); + + VerifyFileTransferProgress(/*payload_id=*/1234, FileTransferStatus::kSuccess, + /*total_bytes=*/1000, + /*bytes_transferred=*/1000); +} + TEST_F(CameraRollManagerImplTest, DownloadItemWhenFileNoLongerAvailableOnPhone) { // Make an item available to CameraRollManager.
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 8510a40..aad7249 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -950,7 +950,7 @@ // and recent apps context menu that allow the user to hide the continue // section. const base::Feature kLauncherHideContinueSection{ - "LauncherHideContinueSection", base::FEATURE_ENABLED_BY_DEFAULT}; + "LauncherHideContinueSection", base::FEATURE_DISABLED_BY_DEFAULT}; // Uses short intervals for launcher nudge for testing if enabled. const base::Feature kLauncherNudgeShortInterval{ @@ -1127,6 +1127,10 @@ const base::Feature kOverviewButton{"OverviewButton", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables the option to snap windows by thirds for split view. +const base::Feature kPartialSplit{"PartialSplit", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables a notification warning users that their Thunderbolt device is not // supported on their CrOS device. const base::Feature kPcieBillboardNotification{ @@ -2079,6 +2083,10 @@ return base::FeatureList::IsEnabled(kEnableOobeThemeSelection); } +bool IsPartialSplitEnabled() { + return base::FeatureList::IsEnabled(kPartialSplit); +} + bool IsPcieBillboardNotificationEnabled() { return base::FeatureList::IsEnabled(kPcieBillboardNotification); }
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index 674f3c0..ad2cbf5 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -451,6 +451,7 @@ COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOsSettingsAppNotificationsPage; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOverviewButton; +COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPartialSplit; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPcieBillboardNotification; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPerDeskShelf; @@ -746,6 +747,7 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeNewRecommendAppsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeRemoveShutdownButtonEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeThemeSelectionEnabled(); +COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPartialSplitEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPcieBillboardNotificationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPciguardUiEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPerDeskShelfEnabled();
diff --git a/ash/shelf/contextual_nudge.cc b/ash/controls/contextual_nudge.cc similarity index 98% rename from ash/shelf/contextual_nudge.cc rename to ash/controls/contextual_nudge.cc index e5af3ee4..1635d80 100644 --- a/ash/shelf/contextual_nudge.cc +++ b/ash/controls/contextual_nudge.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 "ash/shelf/contextual_nudge.h" +#include "ash/controls/contextual_nudge.h" #include "ash/public/cpp/shelf_types.h" #include "ash/public/cpp/shell_window_ids.h"
diff --git a/ash/shelf/contextual_nudge.h b/ash/controls/contextual_nudge.h similarity index 94% rename from ash/shelf/contextual_nudge.h rename to ash/controls/contextual_nudge.h index 69155bb..c0e5e31 100644 --- a/ash/shelf/contextual_nudge.h +++ b/ash/controls/contextual_nudge.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 ASH_SHELF_CONTEXTUAL_NUDGE_H_ -#define ASH_SHELF_CONTEXTUAL_NUDGE_H_ +#ifndef ASH_CONTROLS_CONTEXTUAL_NUDGE_H_ +#define ASH_CONTROLS_CONTEXTUAL_NUDGE_H_ #include "ash/ash_export.h" #include "base/callback.h" @@ -63,4 +63,4 @@ } // namespace ash -#endif // ASH_SHELF_CONTEXTUAL_NUDGE_H_ +#endif // ASH_CONTROLS_CONTEXTUAL_NUDGE_H_
diff --git a/ash/shelf/contextual_tooltip.cc b/ash/controls/contextual_tooltip.cc similarity index 99% rename from ash/shelf/contextual_tooltip.cc rename to ash/controls/contextual_tooltip.cc index 9f16024d..79149fb 100644 --- a/ash/shelf/contextual_tooltip.cc +++ b/ash/controls/contextual_tooltip.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 "ash/shelf/contextual_tooltip.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h"
diff --git a/ash/shelf/contextual_tooltip.h b/ash/controls/contextual_tooltip.h similarity index 96% rename from ash/shelf/contextual_tooltip.h rename to ash/controls/contextual_tooltip.h index aafcc4a..a185461 100644 --- a/ash/shelf/contextual_tooltip.h +++ b/ash/controls/contextual_tooltip.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 ASH_SHELF_CONTEXTUAL_TOOLTIP_H_ -#define ASH_SHELF_CONTEXTUAL_TOOLTIP_H_ +#ifndef ASH_CONTROLS_CONTEXTUAL_TOOLTIP_H_ +#define ASH_CONTROLS_CONTEXTUAL_TOOLTIP_H_ #include "ash/ash_export.h" #include "base/time/clock.h" @@ -112,4 +112,4 @@ } // namespace ash -#endif // ASH_SHELF_CONTEXTUAL_TOOLTIP_H_ +#endif // ASH_CONTROLS_CONTEXTUAL_TOOLTIP_H_
diff --git a/ash/shelf/contextual_tooltip_unittest.cc b/ash/controls/contextual_tooltip_unittest.cc similarity index 98% rename from ash/shelf/contextual_tooltip_unittest.cc rename to ash/controls/contextual_tooltip_unittest.cc index 07f64ebf..555a963f 100644 --- a/ash/shelf/contextual_tooltip_unittest.cc +++ b/ash/controls/contextual_tooltip_unittest.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/shelf/contextual_tooltip.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/json/values_util.h"
diff --git a/ash/in_session_auth/BUILD.gn b/ash/in_session_auth/BUILD.gn index 8154045..47532d6 100644 --- a/ash/in_session_auth/BUILD.gn +++ b/ash/in_session_auth/BUILD.gn
@@ -30,6 +30,7 @@ "//ash/strings", "//base", "//chromeos/components/webauthn", + "//chromeos/dbus/userdataauth", "//ui/views", ] }
diff --git a/ash/in_session_auth/authentication_dialog.cc b/ash/in_session_auth/authentication_dialog.cc index 0e27c633..c2d25e35 100644 --- a/ash/in_session_auth/authentication_dialog.cc +++ b/ash/in_session_auth/authentication_dialog.cc
@@ -6,12 +6,16 @@ #include <memory> +#include "ash/components/login/auth/auth_performer.h" #include "ash/components/login/auth/cryptohome_error.h" +#include "ash/components/login/auth/cryptohome_key_constants.h" #include "ash/components/login/auth/user_context.h" #include "ash/public/cpp/in_session_auth_dialog_controller.h" +#include "ash/public/cpp/in_session_auth_token_provider.h" #include "ash/public/cpp/shelf_config.h" #include "ash/strings/grit/ash_strings.h" #include "base/bind.h" +#include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/unguessable_token.h" #include "ui/base/l10n/l10n_util.h" @@ -69,10 +73,15 @@ } // namespace AuthenticationDialog::AuthenticationDialog( - InSessionAuthDialogController::OnAuthComplete on_auth_complete) + InSessionAuthDialogController::OnAuthComplete on_auth_complete, + InSessionAuthTokenProvider* auth_token_provider, + std::unique_ptr<AuthPerformer> auth_performer, + const AccountId& account_id) : password_field_(AddChildView(std::make_unique<views::Textfield>())), invalid_password_label_(AddChildView(std::make_unique<views::Label>())), - on_auth_complete_(std::move(on_auth_complete)) { + on_auth_complete_(std::move(on_auth_complete)), + auth_performer_(std::move(auth_performer)), + auth_token_provider_(auth_token_provider) { // Dialog setup set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric( views::DistanceMetric::DISTANCE_BUBBLE_PREFERRED_WIDTH)); @@ -90,6 +99,18 @@ .SetCollapseMargins(true); ConfigureChildViews(); + + // We don't want the user to submit an auth factor to cryptohome before the + // auth session has started. We re-enable the UI in `OnAuthSessionStarted` + SetUIDisabled(true); + + auto user_context = std::make_unique<UserContext>(); + user_context->SetAccountId(account_id); + + auth_performer_->StartAuthSession( + std::move(user_context), /*ephemeral=*/false, + base::BindOnce(&AuthenticationDialog::OnAuthSessionStarted, + weak_factory_.GetWeakPtr())); } AuthenticationDialog::~AuthenticationDialog() = default; @@ -121,12 +142,12 @@ ok_button->SetText( l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SUBMIT_BUTTON_ACCESSIBLE_NAME)); ok_button->SetCallback(base::BindRepeating( - &AuthenticationDialog::ValidateAuthFactor, base::Unretained(this))); + &AuthenticationDialog::ValidateAuthFactor, weak_factory_.GetWeakPtr())); } void AuthenticationDialog::SetUIDisabled(bool is_disabled) { - SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_OK, is_disabled); - SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_CANCEL, is_disabled); + SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_OK, !is_disabled); + SetButtonEnabled(ui::DialogButton::DIALOG_BUTTON_CANCEL, !is_disabled); password_field_->SetReadOnly(is_disabled); } @@ -136,16 +157,33 @@ SetUIDisabled(true); - auto user_context = std::make_unique<UserContext>(); - // TODO(b/231568585): call AuthPerformer::AuthenticateWithPassword - // Right now, we just assume that the password is correct no matter what - OnAuthFactorValidityChecked(std::move(user_context), absl::nullopt); + // Create a copy of `user_context_` so that we don't lose it to std::move + // for future auth attempts + auth_performer_->AuthenticateWithPassword( + user_context_->GetAuthFactorsData().FindOnlinePasswordKey()->label, + base::UTF16ToUTF8(password_field_->GetText()), + std::make_unique<UserContext>(*user_context_), + base::BindOnce(&AuthenticationDialog::OnAuthFactorValidityChecked, + weak_factory_.GetWeakPtr())); } void AuthenticationDialog::OnAuthFactorValidityChecked( std::unique_ptr<UserContext> user_context, absl::optional<CryptohomeError> cryptohome_error) { if (cryptohome_error.has_value()) { + if (cryptohome_error.value().error_code == + user_data_auth::CRYPTOHOME_INVALID_AUTH_SESSION_TOKEN) { + // Auth session expired for some reason, start it again and reattempt + // authentication. + auth_performer_->StartAuthSession( + std::move(user_context), /*ephemeral=*/false, + base::BindOnce(&AuthenticationDialog::OnAuthSessionInvalid, + weak_factory_.GetWeakPtr())); + return; + } + LOG(ERROR) << "An error happened during the attempt to validate" + "the password: " + << cryptohome_error.value().error_code; password_field_->SetInvalid(true); password_field_->SelectAll(false); invalid_password_label_->SetText( @@ -155,6 +193,13 @@ } is_closing_ = true; + + auth_token_provider_->ExchangeForToken( + std::move(user_context), + base::BindOnce(&AuthenticationDialog::NotifyResult, + weak_factory_.GetWeakPtr(), /*success=*/true)); + + SetUIDisabled(false); CancelDialog(); return; } @@ -173,4 +218,30 @@ ConfigureInvalidPasswordLabel(invalid_password_label_); } +void AuthenticationDialog::OnAuthSessionInvalid( + bool user_exists, + std::unique_ptr<UserContext> user_context, + absl::optional<CryptohomeError> cryptohome_error) { + OnAuthSessionStarted(user_exists, std::move(user_context), cryptohome_error); + ValidateAuthFactor(); +} + +void AuthenticationDialog::OnAuthSessionStarted( + bool user_exists, + std::unique_ptr<UserContext> user_context, + absl::optional<CryptohomeError> cryptohome_error) { + if (cryptohome_error.has_value()) { + LOG(ERROR) << "Error starting authsession for in session authentication: " + << cryptohome_error.value().error_code; + CancelAuthAttempt(); + } else if (!user_exists) { + LOG(ERROR) << "Attempting to authenticate a user which does not exist. " + "Aborting authentication attempt"; + CancelAuthAttempt(); + } else { + user_context_ = std::move(user_context); + SetUIDisabled(false); + } +} + } // namespace ash
diff --git a/ash/in_session_auth/authentication_dialog.h b/ash/in_session_auth/authentication_dialog.h index 10a83852..41189750 100644 --- a/ash/in_session_auth/authentication_dialog.h +++ b/ash/in_session_auth/authentication_dialog.h
@@ -7,11 +7,14 @@ #include <memory> +#include "ash/components/login/auth/auth_performer.h" #include "ash/components/login/auth/user_context.h" #include "ash/public/cpp/in_session_auth_dialog_controller.h" +#include "ash/public/cpp/in_session_auth_token_provider.h" #include "base/memory/raw_ptr.h" #include "base/time/time.h" #include "base/unguessable_token.h" +#include "components/account_id/account_id.h" #include "ui/views/controls/label.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_delegate.h" @@ -29,10 +32,25 @@ // support all configured forms of authentication on the system. class AuthenticationDialog : public views::DialogDelegateView { public: + class TestApi { + public: + explicit TestApi(AuthenticationDialog* dialog) : dialog_(dialog) {} + + views::Textfield* GetPasswordTextfield() { + return dialog_->password_field_; + } + + private: + base::raw_ptr<AuthenticationDialog> const dialog_; + }; + // |on_auth_complete| is called when the user has been authenticated // or when the dialog has been aborted explicit AuthenticationDialog( - InSessionAuthDialogController::OnAuthComplete on_auth_complete); + InSessionAuthDialogController::OnAuthComplete on_auth_complete, + InSessionAuthTokenProvider* auth_token_provider, + std::unique_ptr<AuthPerformer> auth_performer, + const AccountId& account_id); ~AuthenticationDialog() override; @@ -80,6 +98,20 @@ // error message label. void ConfigureChildViews(); + // Passed as a callback to `AuthPerformer::StartAuthSession` in + // `OnAuthFactorValidityChecked` when trying to validate the password + // and discovering that the auth session is no longer active + void OnAuthSessionInvalid(bool user_exists, + std::unique_ptr<UserContext> user_context, + absl::optional<CryptohomeError> cryptohome_error); + + // Passed as a callback to `AuthPerformer::StartAuthSession`. Saves the + // password key label to pass it later to authentication attempts and handles + // errors from cryptohome + void OnAuthSessionStarted(bool user_exists, + std::unique_ptr<UserContext> user_context, + absl::optional<CryptohomeError> cryptohome_error); + base::raw_ptr<views::Textfield> password_field_; base::raw_ptr<views::Label> invalid_password_label_; @@ -87,6 +119,20 @@ bool is_closing_ = false; InSessionAuthDialogController::OnAuthComplete on_auth_complete_; + + // Called when user submits an auth factor to check its validity + std::unique_ptr<AuthPerformer> auth_performer_; + + // Non owning pointer, initialized and owned by + // `ChromeBrowserMainExtraPartsAsh`. + // `auth_token_provider_` will outlive this dialog since it will + // be destroyed after `AshShellInit`, which owns the aura + // window hierarchy. + base::raw_ptr<InSessionAuthTokenProvider> auth_token_provider_; + + std::unique_ptr<UserContext> user_context_; + + base::WeakPtrFactory<AuthenticationDialog> weak_factory_{this}; }; } // namespace ash
diff --git a/ash/in_session_auth/authentication_dialog_unittest.cc b/ash/in_session_auth/authentication_dialog_unittest.cc index 9f94cab10..2ca5d250 100644 --- a/ash/in_session_auth/authentication_dialog_unittest.cc +++ b/ash/in_session_auth/authentication_dialog_unittest.cc
@@ -4,41 +4,211 @@ #include "ash/in_session_auth/authentication_dialog.h" +#include <cctype> + +#include "ash/components/cryptohome/cryptohome_parameters.h" +#include "ash/components/login/auth/auth_factors_data.h" +#include "ash/components/login/auth/auth_performer.h" +#include "ash/components/login/auth/cryptohome_key_constants.h" +#include "ash/components/login/auth/mock_auth_performer.h" +#include "ash/public/cpp/in_session_auth_token_provider.h" +#include "ash/public/cpp/test/mock_in_session_auth_token_provider.h" #include "ash/test/ash_test_base.h" #include "base/logging.h" #include "base/test/bind.h" #include "base/unguessable_token.h" +#include "chromeos/dbus/userdataauth/userdataauth_client.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/events/keycodes/keyboard_codes_posix.h" +#include "ui/views/controls/button/label_button.h" #include "ui/views/controls/textfield/textfield.h" namespace ash { namespace { +const char kTestAccount[] = "user@test.com"; +const char kExpectedPassword[] = "qwerty"; +base::UnguessableToken kToken = base::UnguessableToken::Create(); +using testing::_; +} // namespace class AuthenticationDialogTest : public AshTestBase { public: void SetUp() override { AshTestBase::SetUp(); - dialog_ = new AuthenticationDialog(base::BindLambdaForTesting( - [&](bool success, const base::UnguessableToken& token, - base::TimeDelta timeout) { success_ = success; })); - dialog_->Show(); + chromeos::UserDataAuthClient::InitializeFake(); + auth_token_provider_ = std::make_unique<MockInSessionAuthTokenProvider>(); + } + + void StartAuthSession(std::unique_ptr<UserContext> user_context, + bool ephemeral, + AuthPerformer::StartSessionCallback callback) { + user_context->SetAuthFactorsData( + AuthFactorsData{{cryptohome::KeyDefinition::CreateForPassword( + "secret", kCryptohomeGaiaKeyLabel, 0)}}); + + std::move(callback).Run(true, std::move(user_context), absl::nullopt); + } + + void GetAuthToken(std::unique_ptr<UserContext> user_context, + InSessionAuthTokenProvider::OnAuthTokenGenerated callback) { + std::move(callback).Run(kToken, base::Minutes(5)); } protected: + void CreateAndShowDialog() { + auto auth_performer = + std::make_unique<MockAuthPerformer>(UserDataAuthClient::Get()); + auth_performer_ = auth_performer.get(); + + EXPECT_CALL(*auth_performer_, StartAuthSession) + .WillRepeatedly( + testing::Invoke(this, &AuthenticationDialogTest::StartAuthSession)); + + // `dialog_` is a `DialogDelegateView` and will be owned by the + // underlying widget. + dialog_ = new AuthenticationDialog( + base::BindLambdaForTesting([&](bool success, + const base::UnguessableToken& token, + base::TimeDelta timeout) { + success_ = success; + token_ = token; + }), + auth_token_provider_.get(), std::move(auth_performer), + AccountId::FromUserEmail(kTestAccount)); + + test_api_ = std::make_unique<AuthenticationDialog::TestApi>(dialog_); + + dialog_->Show(); + } + + void TypePassword(const std::string& password) { + auto* generator = GetEventGenerator(); + generator->MoveMouseTo( + test_api_->GetPasswordTextfield()->GetBoundsInScreen().CenterPoint()); + generator->ClickLeftButton(); + + for (char c : password) { + EXPECT_TRUE(std::isalpha(c)); + generator->PressAndReleaseKey( + static_cast<ui::KeyboardCode>(ui::KeyboardCode::VKEY_A + (c - 'a')), + ui::EF_NONE); + } + } + + void PressOkButton() { + auto* generator = GetEventGenerator(); + generator->MoveMouseTo( + dialog_->GetOkButton()->GetBoundsInScreen().CenterPoint()); + generator->ClickLeftButton(); + } + absl::optional<bool> success_; + base::UnguessableToken token_; base::raw_ptr<AuthenticationDialog> dialog_; + std::unique_ptr<MockInSessionAuthTokenProvider> auth_token_provider_; + base::raw_ptr<MockAuthPerformer> auth_performer_; + std::unique_ptr<AuthenticationDialog::TestApi> test_api_; }; TEST_F(AuthenticationDialogTest, CallbackCalledOnCancel) { + CreateAndShowDialog(); dialog_->Cancel(); EXPECT_TRUE(success_.has_value()); EXPECT_EQ(success_.value(), false); } TEST_F(AuthenticationDialogTest, CallbackCalledOnClose) { + CreateAndShowDialog(); dialog_->Close(); EXPECT_TRUE(success_.has_value()); EXPECT_EQ(success_.value(), false); } -} // namespace +TEST_F(AuthenticationDialogTest, CorrectPasswordProvided) { + CreateAndShowDialog(); + TypePassword(kExpectedPassword); + + EXPECT_CALL(*auth_performer_, + AuthenticateWithPassword(kCryptohomeGaiaKeyLabel, + kExpectedPassword, _, _)) + .WillOnce([](const std::string& key_label, const std::string& password, + std::unique_ptr<UserContext> user_context, + AuthOperationCallback callback) { + std::move(callback).Run(std::move(user_context), absl::nullopt); + }); + + EXPECT_CALL(*auth_token_provider_, ExchangeForToken) + .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken)); + + PressOkButton(); + + EXPECT_TRUE(success_.has_value()); + EXPECT_TRUE(success_.value()); + EXPECT_EQ(token_, kToken); +} + +TEST_F(AuthenticationDialogTest, IncorrectPasswordProvidedThenCorrect) { + CreateAndShowDialog(); + TypePassword("ytrewq"); + + EXPECT_CALL(*auth_performer_, + AuthenticateWithPassword(kCryptohomeGaiaKeyLabel, _, _, _)) + .WillRepeatedly([](const std::string& key_label, + const std::string& password, + std::unique_ptr<UserContext> user_context, + AuthOperationCallback callback) { + std::move(callback).Run( + std::move(user_context), + password == kExpectedPassword + ? absl::nullopt + : absl::optional<CryptohomeError>{CryptohomeError{ + user_data_auth:: + CRYPTOHOME_ERROR_AUTHORIZATION_KEY_NOT_FOUND}}); + }); + + PressOkButton(); + TypePassword(kExpectedPassword); + + EXPECT_CALL(*auth_token_provider_, ExchangeForToken) + .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken)); + + PressOkButton(); + + EXPECT_TRUE(success_.has_value()); + EXPECT_TRUE(success_.value()); + EXPECT_EQ(token_, kToken); +} + +TEST_F(AuthenticationDialogTest, AuthSessionRestartedWhenExpired) { + CreateAndShowDialog(); + TypePassword(kExpectedPassword); + + int number_of_calls = 0; + EXPECT_CALL(*auth_performer_, + AuthenticateWithPassword(kCryptohomeGaiaKeyLabel, + kExpectedPassword, _, _)) + .WillRepeatedly([&number_of_calls]( + const std::string& key_label, + const std::string& password, + std::unique_ptr<UserContext> user_context, + AuthOperationCallback callback) { + std::move(callback).Run( + std::move(user_context), + number_of_calls++ + ? absl::nullopt + : absl::optional<CryptohomeError>{CryptohomeError{ + user_data_auth::CRYPTOHOME_INVALID_AUTH_SESSION_TOKEN}}); + }); + + EXPECT_CALL(*auth_token_provider_, ExchangeForToken) + .WillOnce(testing::Invoke(this, &AuthenticationDialogTest::GetAuthToken)); + + PressOkButton(); + + EXPECT_TRUE(success_.has_value()); + EXPECT_TRUE(success_.value()); + EXPECT_EQ(token_, kToken); +} + } // namespace ash
diff --git a/ash/in_session_auth/in_session_auth_dialog_controller_impl.cc b/ash/in_session_auth/in_session_auth_dialog_controller_impl.cc index 0edf92ce..1f6c496 100644 --- a/ash/in_session_auth/in_session_auth_dialog_controller_impl.cc +++ b/ash/in_session_auth/in_session_auth_dialog_controller_impl.cc
@@ -4,17 +4,32 @@ #include "ash/in_session_auth/in_session_auth_dialog_controller_impl.h" +#include "ash/components/login/auth/auth_performer.h" #include "ash/in_session_auth/authentication_dialog.h" +#include "ash/session/session_controller_impl.h" +#include "ash/shell.h" +#include "chromeos/dbus/userdataauth/userdataauth_client.h" namespace ash { void InSessionAuthDialogControllerImpl::ShowAuthDialog( Reason reason, OnAuthComplete on_auth_complete) { + auto account_id = Shell::Get()->session_controller()->GetActiveAccountId(); + DCHECK(account_id.is_valid()); + // We don't manage the lifetime of `AuthenticationDialog` here. // `AuthenticatonDialog` is-a View and it is instead owned by it's widget, // which would properly delete it when the widget is closed. - (new AuthenticationDialog(std::move(on_auth_complete)))->Show(); + (new AuthenticationDialog( + std::move(on_auth_complete), auth_token_provider_, + std::make_unique<AuthPerformer>(UserDataAuthClient::Get()), account_id)) + ->Show(); +} + +void InSessionAuthDialogControllerImpl::SetTokenProvider( + InSessionAuthTokenProvider* auth_token_provider) { + auth_token_provider_ = auth_token_provider; } } // namespace ash
diff --git a/ash/in_session_auth/in_session_auth_dialog_controller_impl.h b/ash/in_session_auth/in_session_auth_dialog_controller_impl.h index 37d9ede4..b9504e9 100644 --- a/ash/in_session_auth/in_session_auth_dialog_controller_impl.h +++ b/ash/in_session_auth/in_session_auth_dialog_controller_impl.h
@@ -6,6 +6,7 @@ #define ASH_IN_SESSION_AUTH_IN_SESSION_AUTH_DIALOG_CONTROLLER_IMPL_H_ #include "ash/public/cpp/in_session_auth_dialog_controller.h" +#include "ash/public/cpp/in_session_auth_token_provider.h" #include "ui/views/widget/widget.h" namespace ash { @@ -21,6 +22,16 @@ // InSessionAuthDialogController overrides void ShowAuthDialog(Reason reason, OnAuthComplete on_auth_complete) override; + + void SetTokenProvider(InSessionAuthTokenProvider* auth_token_provider); + + private: + // Non owning pointer, initialized and owned by + // `ChromeBrowserMainExtraPartsAsh`. + // `auth_token_provider_` will outlive this controller since the controller + // is part of `ash::Shell` and will be destroyed as part of `AshShellInit` + // before `auth_token_provider`. + base::raw_ptr<InSessionAuthTokenProvider> auth_token_provider_; }; } // namespace ash
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index 43c6bed8..33bc943 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -158,6 +158,7 @@ "ime_info.h", "in_session_auth_dialog_client.h", "in_session_auth_dialog_controller.h", + "in_session_auth_token_provider.h", "keyboard/arc/arc_input_method_bounds_tracker.cc", "keyboard/arc/arc_input_method_bounds_tracker.h", "keyboard/keyboard_config.h", @@ -400,6 +401,7 @@ public_deps = [ "//ash/components/arc/mojom:notifications", + "//ash/components/login/auth", "//ash/public/mojom", "//ash/services/cellular_setup/public/mojom", "//ash/webui/personalization_app/proto", @@ -460,6 +462,8 @@ source_set("test_support") { testonly = true sources = [ + "test/mock_in_session_auth_token_provider.cc", + "test/mock_in_session_auth_token_provider.h", "test/mock_projector_controller.cc", "test/mock_projector_controller.h", "test/test_app_list_color_provider.cc",
diff --git a/ash/public/cpp/ambient/ambient_metrics.cc b/ash/public/cpp/ambient/ambient_metrics.cc index d62c6f97..90076372 100644 --- a/ash/public/cpp/ambient/ambient_metrics.cc +++ b/ash/public/cpp/ambient/ambient_metrics.cc
@@ -8,10 +8,15 @@ #include "ash/public/cpp/ambient/ambient_ui_model.h" #include "ash/public/cpp/ambient/common/ambient_settings.h" +#include "base/check.h" +#include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/strings/strcat.h" +#include "base/strings/stringprintf.h" #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" namespace ash { namespace ambient { @@ -36,6 +41,20 @@ return histogram; } +void RecordEngagementTime(base::StringPiece histogram_name, + base::TimeDelta engagement_time) { + base::UmaHistogramCustomTimes( + histogram_name.data(), + /*sample=*/engagement_time, + // There is no value in bucketing engagement times that are on the order + // of milliseconds. A 1 second minimum is imposed here but not in the + // metric above for legacy reasons (the metric above was already pushed + // to the field and established before this change was made). + /*min=*/base::Seconds(1), + /*max=*/base::Hours(24), + /*buckets=*/kAmbientModeElapsedTimeHistogramBuckets); +} + } // namespace AmbientModePhotoSource AmbientSettingsToPhotoSource( @@ -76,17 +95,9 @@ /*max=*/base::Hours(24), /*buckets=*/kAmbientModeElapsedTimeHistogramBuckets); - base::UmaHistogramCustomTimes( - /*name=*/base::StrCat( - {"Ash.AmbientMode.EngagementTime.", ToString(theme)}), - /*sample=*/time_delta, - // There is no value in bucketing engagement times that are on the order - // of milliseconds. A 1 second minimum is imposed here but not in the - // metric above for legacy reasons (the metric above was already pushed - // to the field and established before this change was made). - /*min=*/base::Seconds(1), - /*max=*/base::Hours(24), - /*buckets=*/kAmbientModeElapsedTimeHistogramBuckets); + RecordEngagementTime( + base::StrCat({"Ash.AmbientMode.EngagementTime.", ToString(theme)}), + time_delta); } void RecordAmbientModeTotalNumberOfAlbums(int num_albums) { @@ -124,5 +135,66 @@ /*buckets=*/50); } +AmbientOrientationMetricsRecorder::AmbientOrientationMetricsRecorder( + views::View* root_rendering_view, + AmbientAnimationTheme theme) + : theme_(ToString(theme)) { + root_rendering_view_observer_.Observe(root_rendering_view); + // Capture initial orientation with manual call. + OnViewBoundsChanged(root_rendering_view); +} + +AmbientOrientationMetricsRecorder::~AmbientOrientationMetricsRecorder() { + SaveCurrentOrientationDuration(); + if (!total_portrait_duration_.is_zero()) { + RecordEngagementTime( + base::StringPrintf("Ash.AmbientMode.EngagementTime.%s.Portrait", + theme_.data()), + total_portrait_duration_); + } + if (!total_landscape_duration_.is_zero()) { + RecordEngagementTime( + base::StringPrintf("Ash.AmbientMode.EngagementTime.%s.Landscape", + theme_.data()), + total_landscape_duration_); + } +} + +void AmbientOrientationMetricsRecorder::OnViewBoundsChanged( + views::View* observed_view) { + DCHECK(observed_view); + gfx::Rect content_bounds = observed_view->GetContentsBounds(); + if (content_bounds.IsEmpty()) { + DVLOG(4) << "Initial view layout has not occurred yet. Ignoring empty view " + "bounds"; + return; + } + + bool new_orientation_is_portrait = + content_bounds.width() < content_bounds.height(); + if (current_orientation_is_portrait_.has_value() && + *current_orientation_is_portrait_ == new_orientation_is_portrait) { + return; + } + + SaveCurrentOrientationDuration(); + current_orientation_is_portrait_.emplace(new_orientation_is_portrait); + // Effectively stops the existing timer and starts new one. + current_orientation_timer_.emplace(); +} + +void AmbientOrientationMetricsRecorder::SaveCurrentOrientationDuration() { + if (!current_orientation_is_portrait_.has_value() || + !current_orientation_timer_.has_value()) { + return; + } + + if (*current_orientation_is_portrait_) { + total_portrait_duration_ += current_orientation_timer_->Elapsed(); + } else { + total_landscape_duration_ += current_orientation_timer_->Elapsed(); + } +} + } // namespace ambient } // namespace ash
diff --git a/ash/public/cpp/ambient/ambient_metrics.h b/ash/public/cpp/ambient/ambient_metrics.h index 797073a..abae7cf 100644 --- a/ash/public/cpp/ambient/ambient_metrics.h +++ b/ash/public/cpp/ambient/ambient_metrics.h
@@ -7,7 +7,13 @@ #include "ash/constants/ambient_animation_theme.h" #include "ash/public/cpp/ash_public_export.h" +#include "base/scoped_observation.h" +#include "base/strings/string_piece.h" #include "base/time/time.h" +#include "base/timer/elapsed_timer.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "ui/views/view.h" +#include "ui/views/view_observer.h" namespace ash { @@ -59,6 +65,34 @@ base::TimeDelta startup_time, AmbientAnimationTheme theme); +// Records metrics that track the total usage of each orientation in ambient +// mode. +class ASH_PUBLIC_EXPORT AmbientOrientationMetricsRecorder + : public views::ViewObserver { + public: + AmbientOrientationMetricsRecorder(views::View* root_rendering_view, + AmbientAnimationTheme theme); + AmbientOrientationMetricsRecorder(const AmbientOrientationMetricsRecorder&) = + delete; + AmbientOrientationMetricsRecorder& operator=( + const AmbientOrientationMetricsRecorder&) = delete; + ~AmbientOrientationMetricsRecorder() override; + + private: + void OnViewBoundsChanged(views::View* observed_view) override; + void SaveCurrentOrientationDuration(); + + const base::StringPiece theme_; + base::ScopedObservation<views::View, ViewObserver> + root_rendering_view_observer_{this}; + // Null until a non-empty view boundary is provided (i.e. the initial view + // layout occurs). + absl::optional<bool> current_orientation_is_portrait_; + absl::optional<base::ElapsedTimer> current_orientation_timer_; + base::TimeDelta total_portrait_duration_; + base::TimeDelta total_landscape_duration_; +}; + } // namespace ambient } // namespace ash
diff --git a/ash/public/cpp/ambient/ambient_metrics_unittest.cc b/ash/public/cpp/ambient/ambient_metrics_unittest.cc index f8865200..d4d403b 100644 --- a/ash/public/cpp/ambient/ambient_metrics_unittest.cc +++ b/ash/public/cpp/ambient/ambient_metrics_unittest.cc
@@ -8,7 +8,11 @@ #include <vector> #include "ash/public/cpp/ambient/common/ambient_settings.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/timer/elapsed_timer.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/geometry/size.h" +#include "ui/views/view.h" namespace ash { namespace ambient { @@ -65,6 +69,27 @@ AmbientSettingsToPhotoSource(settings)); } +TEST(AmbientOrientationMetricsRecorderTest, RecordsEngagementTime) { + base::ScopedMockElapsedTimersForTest mock_timer; + base::HistogramTester histogram_tester; + { + views::View test_view; + AmbientOrientationMetricsRecorder recorder( + &test_view, AmbientAnimationTheme::kFeelTheBreeze); + test_view.SetSize(gfx::Size(200, 100)); + // No change in size shouldn't count. + test_view.SetSize(gfx::Size(200, 100)); + test_view.SetSize(gfx::Size(100, 200)); + test_view.SetSize(gfx::Size(200, 100)); + } + histogram_tester.ExpectTimeBucketCount( + "Ash.AmbientMode.EngagementTime.FeelTheBreeze.Landscape", + base::ScopedMockElapsedTimersForTest::kMockElapsedTime * 2, 1); + histogram_tester.ExpectTimeBucketCount( + "Ash.AmbientMode.EngagementTime.FeelTheBreeze.Portrait", + base::ScopedMockElapsedTimersForTest::kMockElapsedTime, 1); +} + } // namespace metrics } // namespace ambient -} // namespace ash \ No newline at end of file +} // namespace ash
diff --git a/ash/public/cpp/desk_template.cc b/ash/public/cpp/desk_template.cc index 4e7fe051..b83210f 100644 --- a/ash/public/cpp/desk_template.cc +++ b/ash/public/cpp/desk_template.cc
@@ -86,32 +86,8 @@ desk_restore_data_->SetDeskIndex(desk_index); } -// TODO(crbug.com/1328850): Factor out common elements between ToString and -// ToDebugString. std::string DeskTemplate::ToString() const { - std::string result = - "Template name: " + base::UTF16ToUTF8(template_name_) + "\n"; - result += "Source: "; - switch (source_) { - case DeskTemplateSource::kUnknownSource: - result += "unknown\n"; - break; - case DeskTemplateSource::kUser: - result += "user\n"; - break; - case DeskTemplateSource::kPolicy: - result += "policy\n"; - break; - } - result += "Type: "; - switch (type_) { - case DeskTemplateType::kTemplate: - result += "template\n"; - break; - case DeskTemplateType::kSaveAndRecall: - result += "save and recall\n"; - break; - } + std::string result = GetDeskTemplateInfo(/*for_debugging=*/false); if (desk_restore_data_) result += desk_restore_data_->ToString(); @@ -119,30 +95,8 @@ } std::string DeskTemplate::ToDebugString() const { - std::string result = - "Template name: " + base::UTF16ToUTF8(template_name_) + "\n"; - result += "GUID: " + uuid_.AsLowercaseString() + "\n"; - result += "Source: "; - switch (source_) { - case DeskTemplateSource::kUnknownSource: - result += "unknown\n"; - break; - case DeskTemplateSource::kUser: - result += "user\n"; - break; - case DeskTemplateSource::kPolicy: - result += "policy\n"; - break; - } - result += "Type: "; - switch (type_) { - case DeskTemplateType::kTemplate: - result += "template\n"; - break; - case DeskTemplateType::kSaveAndRecall: - result += "save and recall\n"; - break; - } + std::string result = GetDeskTemplateInfo(/*for_debugging=*/true); + result += "Time created: " + base::TimeFormatHTTP(created_time_) + "\n"; result += "Time updated: " + base::TimeFormatHTTP(updated_time_) + "\n"; result += "launch id: " + base::NumberToString(launch_id_) + "\n"; @@ -157,4 +111,33 @@ return result; } +std::string DeskTemplate::GetDeskTemplateInfo(bool for_debugging) const { + std::string result = + "Template name: " + base::UTF16ToUTF8(template_name_) + "\n"; + if (for_debugging) + result += "GUID: " + uuid_.AsLowercaseString() + "\n"; + result += "Source: "; + switch (source_) { + case DeskTemplateSource::kUnknownSource: + result += "unknown\n"; + break; + case DeskTemplateSource::kUser: + result += "user\n"; + break; + case DeskTemplateSource::kPolicy: + result += "policy\n"; + break; + } + result += "Type: "; + switch (type_) { + case DeskTemplateType::kTemplate: + result += "template\n"; + break; + case DeskTemplateType::kSaveAndRecall: + result += "save and recall\n"; + break; + } + return result; +} + } // namespace ash
diff --git a/ash/public/cpp/desk_template.h b/ash/public/cpp/desk_template.h index b118d88..1f45000 100644 --- a/ash/public/cpp/desk_template.h +++ b/ash/public/cpp/desk_template.h
@@ -120,6 +120,10 @@ std::string ToDebugString() const; private: + // Returns a string containing basic information for `this`. It could be used + // for `ToString` and `ToDebugString` according to the given `for_debugging`. + std::string GetDeskTemplateInfo(bool for_debugging) const; + const base::GUID uuid_; // We utilize the string based base::GUID to uniquely // identify the template.
diff --git a/ash/public/cpp/in_session_auth_token_provider.h b/ash/public/cpp/in_session_auth_token_provider.h new file mode 100644 index 0000000..e1372002 --- /dev/null +++ b/ash/public/cpp/in_session_auth_token_provider.h
@@ -0,0 +1,30 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_PUBLIC_CPP_IN_SESSION_AUTH_TOKEN_PROVIDER_H_ +#define ASH_PUBLIC_CPP_IN_SESSION_AUTH_TOKEN_PROVIDER_H_ + +#include "ash/components/login/auth/user_context.h" +#include "ash/public/cpp/ash_public_export.h" +#include "base/callback_forward.h" +#include "base/time/time.h" +#include "base/unguessable_token.h" + +namespace ash { + +class ASH_PUBLIC_EXPORT InSessionAuthTokenProvider { + public: + using OnAuthTokenGenerated = + base::OnceCallback<void(const base::UnguessableToken&, base::TimeDelta)>; + + virtual ~InSessionAuthTokenProvider() = default; + + // Constructs an unguessable token for a given `UserContext` + virtual void ExchangeForToken(std::unique_ptr<UserContext> user_context, + OnAuthTokenGenerated callback) = 0; +}; + +} // namespace ash + +#endif // ASH_PUBLIC_CPP_IN_SESSION_AUTH_TOKEN_PROVIDER_H_
diff --git a/ash/public/cpp/test/mock_in_session_auth_token_provider.cc b/ash/public/cpp/test/mock_in_session_auth_token_provider.cc new file mode 100644 index 0000000..c9daf096 --- /dev/null +++ b/ash/public/cpp/test/mock_in_session_auth_token_provider.cc
@@ -0,0 +1,13 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/public/cpp/test/mock_in_session_auth_token_provider.h" + +namespace ash { + +MockInSessionAuthTokenProvider::MockInSessionAuthTokenProvider() = default; + +MockInSessionAuthTokenProvider::~MockInSessionAuthTokenProvider() = default; + +}; // namespace ash
diff --git a/ash/public/cpp/test/mock_in_session_auth_token_provider.h b/ash/public/cpp/test/mock_in_session_auth_token_provider.h new file mode 100644 index 0000000..f7274f79 --- /dev/null +++ b/ash/public/cpp/test/mock_in_session_auth_token_provider.h
@@ -0,0 +1,36 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_PUBLIC_CPP_TEST_MOCK_IN_SESSION_AUTH_TOKEN_PROVIDER_H_ +#define ASH_PUBLIC_CPP_TEST_MOCK_IN_SESSION_AUTH_TOKEN_PROVIDER_H_ + +#include "ash/public/cpp/ash_public_export.h" +#include "ash/public/cpp/in_session_auth_token_provider.h" +#include "base/callback.h" +#include "base/unguessable_token.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace ash { + +class ASH_PUBLIC_EXPORT MockInSessionAuthTokenProvider + : public InSessionAuthTokenProvider { + public: + MockInSessionAuthTokenProvider(); + MockInSessionAuthTokenProvider(const MockInSessionAuthTokenProvider&) = + delete; + MockInSessionAuthTokenProvider& operator=( + const MockInSessionAuthTokenProvider&) = delete; + ~MockInSessionAuthTokenProvider() override; + + // InSessionAuthTokenProvider: + MOCK_METHOD(void, + ExchangeForToken, + (std::unique_ptr<UserContext> user_context, + OnAuthTokenGenerated callback), + (override)); +}; + +} // namespace ash + +#endif // ASH_PUBLIC_CPP_TEST_MOCK_IN_SESSION_AUTH_TOKEN_PROVIDER_H_
diff --git a/ash/shelf/drag_handle.cc b/ash/shelf/drag_handle.cc index 133780fd..6264f65 100644 --- a/ash/shelf/drag_handle.cc +++ b/ash/shelf/drag_handle.cc
@@ -6,9 +6,9 @@ #include "ash/accessibility/accessibility_controller_impl.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/shelf_config.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_observer.h" #include "ash/shelf/shelf_widget.h"
diff --git a/ash/shelf/drag_handle.h b/ash/shelf/drag_handle.h index b07b9b7..ce5ffc3 100644 --- a/ash/shelf/drag_handle.h +++ b/ash/shelf/drag_handle.h
@@ -6,8 +6,8 @@ #define ASH_SHELF_DRAG_HANDLE_H_ #include "ash/ash_export.h" -#include "ash/shelf/contextual_nudge.h" -#include "ash/shelf/contextual_tooltip.h" +#include "ash/controls/contextual_nudge.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/shell_observer.h"
diff --git a/ash/shelf/home_to_overview_nudge_controller.cc b/ash/shelf/home_to_overview_nudge_controller.cc index 6dea522..8c809b41 100644 --- a/ash/shelf/home_to_overview_nudge_controller.cc +++ b/ash/shelf/home_to_overview_nudge_controller.cc
@@ -4,10 +4,10 @@ #include "ash/shelf/home_to_overview_nudge_controller.h" +#include "ash/controls/contextual_nudge.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_nudge.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/hotseat_widget.h" #include "ash/shelf/scrollable_shelf_view.h" #include "ash/shelf/shelf.h"
diff --git a/ash/shelf/home_to_overview_nudge_controller_unittest.cc b/ash/shelf/home_to_overview_nudge_controller_unittest.cc index 6d25190..481bc1ea 100644 --- a/ash/shelf/home_to_overview_nudge_controller_unittest.cc +++ b/ash/shelf/home_to_overview_nudge_controller_unittest.cc
@@ -6,9 +6,9 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "ash/controls/contextual_nudge.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_nudge.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/hotseat_widget.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_layout_manager.h"
diff --git a/ash/shelf/login_shelf_gesture_controller.cc b/ash/shelf/login_shelf_gesture_controller.cc index 6f6c5e4e..2cb211b6 100644 --- a/ash/shelf/login_shelf_gesture_controller.cc +++ b/ash/shelf/login_shelf_gesture_controller.cc
@@ -4,8 +4,8 @@ #include "ash/shelf/login_shelf_gesture_controller.h" +#include "ash/controls/contextual_nudge.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_nudge.h" #include "ash/shelf/drag_handle.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_widget.h"
diff --git a/ash/shelf/login_shelf_gesture_controller_unittest.cc b/ash/shelf/login_shelf_gesture_controller_unittest.cc index a55f0336..8c132b0 100644 --- a/ash/shelf/login_shelf_gesture_controller_unittest.cc +++ b/ash/shelf/login_shelf_gesture_controller_unittest.cc
@@ -4,9 +4,9 @@ #include "ash/shelf/login_shelf_gesture_controller.h" +#include "ash/controls/contextual_nudge.h" #include "ash/login/login_screen_controller.h" #include "ash/login/ui/login_test_base.h" -#include "ash/shelf/contextual_nudge.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h"
diff --git a/ash/shelf/shelf.cc b/ash/shelf/shelf.cc index ba67b01..70efc52 100644 --- a/ash/shelf/shelf.cc +++ b/ash/shelf/shelf.cc
@@ -8,6 +8,7 @@ #include "ash/animation/animation_change_type.h" #include "ash/app_list/app_list_controller_impl.h" +#include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/public/cpp/shelf_item_delegate.h" @@ -590,6 +591,11 @@ if (!shelf_layout_manager_->is_active_session_state()) return; + // Productivity launcher does not show or hide on scroll events. The legacy + // peeking launcher had this behavior, but it doesn't make sense for a bubble. + if (features::IsProductivityLauncherEnabled()) + return; + auto* app_list_controller = Shell::Get()->app_list_controller(); DCHECK(app_list_controller); // If the App List is not visible, send Scroll events to the @@ -608,6 +614,11 @@ !IsHorizontalAlignment()) return; + // Productivity launcher does not show or hide on wheel events. The legacy + // peeking launcher had this behavior, but it doesn't make sense for a bubble. + if (features::IsProductivityLauncherEnabled()) + return; + auto* app_list_controller = Shell::Get()->app_list_controller(); DCHECK(app_list_controller); // If the App List is not visible, send MouseWheel events to the
diff --git a/ash/shelf/shelf_context_menu_model.cc b/ash/shelf/shelf_context_menu_model.cc index 9e79ae0..3eb27c0 100644 --- a/ash/shelf/shelf_context_menu_model.cc +++ b/ash/shelf/shelf_context_menu_model.cc
@@ -196,16 +196,18 @@ ui::kColorAshSystemUIMenuIcon)); } - if (ash::features::IsPersonalizationHubEnabled()) { - AddItemWithStringIdAndIcon( - MENU_PERSONALIZATION_HUB, IDS_AURA_OPEN_PERSONALIZATION_HUB, - ui::ImageModel::FromVectorIcon(kPaintBrushIcon, - ui::kColorAshSystemUIMenuIcon)); - } else if (Shell::Get()->wallpaper_controller()->CanOpenWallpaperPicker()) { - AddItemWithStringIdAndIcon( - MENU_CHANGE_WALLPAPER, IDS_AURA_SET_DESKTOP_WALLPAPER, - ui::ImageModel::FromVectorIcon(kWallpaperIcon, - ui::kColorAshSystemUIMenuIcon)); + if (Shell::Get()->wallpaper_controller()->CanOpenWallpaperPicker()) { + if (ash::features::IsPersonalizationHubEnabled()) { + AddItemWithStringIdAndIcon( + MENU_PERSONALIZATION_HUB, IDS_AURA_OPEN_PERSONALIZATION_HUB, + ui::ImageModel::FromVectorIcon(kPaintBrushIcon, + ui::kColorAshSystemUIMenuIcon)); + } else { + AddItemWithStringIdAndIcon( + MENU_CHANGE_WALLPAPER, IDS_AURA_SET_DESKTOP_WALLPAPER, + ui::ImageModel::FromVectorIcon(kWallpaperIcon, + ui::kColorAshSystemUIMenuIcon)); + } } }
diff --git a/ash/shelf/shelf_drag_handle_unittest.cc b/ash/shelf/shelf_drag_handle_unittest.cc index 4fc9968..d727cb10 100644 --- a/ash/shelf/shelf_drag_handle_unittest.cc +++ b/ash/shelf/shelf_drag_handle_unittest.cc
@@ -5,9 +5,9 @@ #include "ash/app_list/test/app_list_test_helper.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/shelf_types.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/drag_handle.h" #include "ash/shelf/drag_window_from_shelf_controller.h" #include "ash/shelf/drag_window_from_shelf_controller_test_api.h"
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 5a8838e..37b0bb9 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -15,6 +15,7 @@ #include "ash/app_list/views/app_list_view.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/display/screen_orientation_controller.h" #include "ash/drag_drop/scoped_drag_drop_observer.h" #include "ash/public/cpp/app_list/app_list_types.h" @@ -24,7 +25,6 @@ #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/drag_handle.h" #include "ash/shelf/home_to_overview_nudge_controller.h" #include "ash/shelf/hotseat_widget.h" @@ -837,6 +837,8 @@ void ShelfLayoutManager::ProcessScrollOffset(int offset, base::TimeTicks time_stamp) { + DCHECK(!features::IsProductivityLauncherEnabled()); + if (offset <= ShelfConfig::Get()->mousewheel_scroll_offset_threshold()) return; @@ -848,6 +850,7 @@ } void ShelfLayoutManager::ProcessScrollEventFromShelf(ui::ScrollEvent* event) { + DCHECK(!features::IsProductivityLauncherEnabled()); if (shelf_->IsHorizontalAlignment()) { ProcessScrollOffset(GetOffset(event->y_offset(), prefs::kNaturalScroll), event->time_stamp()); @@ -862,6 +865,7 @@ void ShelfLayoutManager::ProcessMouseWheelEventFromShelf( ui::MouseWheelEvent* event) { + DCHECK(!features::IsProductivityLauncherEnabled()); const int y_offset = GetOffset(event->offset().y(), prefs::kMouseReverseScroll); ProcessScrollOffset(y_offset, event->time_stamp());
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index 63f704e..d787721 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -10,6 +10,7 @@ #include "ash/animation/animation_change_type.h" #include "ash/app_list/app_list_controller_impl.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/focus_cycler.h" #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/public/cpp/shelf_config.h" @@ -18,7 +19,6 @@ #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/drag_handle.h" #include "ash/shelf/home_button.h" #include "ash/shelf/hotseat_transition_animator.h"
diff --git a/ash/shelf/shelf_widget.h b/ash/shelf/shelf_widget.h index eda484c..229f7251f 100644 --- a/ash/shelf/shelf_widget.h +++ b/ash/shelf/shelf_widget.h
@@ -9,9 +9,9 @@ #include "ash/accessibility/accessibility_observer.h" #include "ash/ash_export.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/session/session_observer.h" #include "ash/public/cpp/shelf_types.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/hotseat_transition_animator.h" #include "ash/shelf/hotseat_widget.h" #include "ash/shelf/shelf.h"
diff --git a/ash/shelf/swipe_home_to_overview_controller.cc b/ash/shelf/swipe_home_to_overview_controller.cc index ff69ef8..cfd33d8 100644 --- a/ash/shelf/swipe_home_to_overview_controller.cc +++ b/ash/shelf/swipe_home_to_overview_controller.cc
@@ -6,10 +6,10 @@ #include "ash/app_list/app_list_controller_impl.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/app_list/app_list_config.h" #include "ash/public/cpp/shelf_config.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/drag_window_from_shelf_controller.h" #include "ash/shelf/shelf_metrics.h" #include "ash/shell.h"
diff --git a/ash/shell.cc b/ash/shell.cc index c4d6d0e..c898edf 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -34,6 +34,7 @@ #include "ash/clipboard/clipboard_history_controller_impl.h" #include "ash/clipboard/control_v_histogram_recorder.h" #include "ash/constants/ash_switches.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/dbus/ash_dbus_services.h" #include "ash/detachable_base/detachable_base_handler.h" #include "ash/detachable_base/detachable_base_notification_controller.h" @@ -95,7 +96,6 @@ #include "ash/rgb_keyboard/rgb_keyboard_manager.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/shelf_controller.h" #include "ash/shelf/shelf_window_watcher.h" #include "ash/shell_delegate.h"
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.cc b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.cc index 7fb9a5ab..36081e8 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.cc +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.cc
@@ -5,11 +5,11 @@ #include "ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h" #include "ash/bubble/bubble_constants.h" +#include "ash/controls/contextual_nudge.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/shelf_config.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_nudge.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h"
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h index cd2462d..547faf7 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h
@@ -6,7 +6,7 @@ #define ASH_SYSTEM_KEYBOARD_BRIGHTNESS_KEYBOARD_BACKLIGHT_COLOR_NUDGE_CONTROLLER_H_ #include "ash/ash_export.h" -#include "ash/shelf/contextual_nudge.h" +#include "ash/controls/contextual_nudge.h" #include "base/timer/timer.h" namespace views {
diff --git a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller_unittest.cc b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller_unittest.cc index dd7a5b3..e034b0de 100644 --- a/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller_unittest.cc +++ b/ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller_unittest.cc
@@ -4,8 +4,8 @@ #include "ash/system/keyboard_brightness/keyboard_backlight_color_nudge_controller.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/system/keyboard_brightness/keyboard_backlight_color_controller.h" #include "ash/test/ash_test_base.h"
diff --git a/ash/system/network/network_state_list_detailed_view.cc b/ash/system/network/network_state_list_detailed_view.cc index 503ad254..dbce20d7 100644 --- a/ash/system/network/network_state_list_detailed_view.cc +++ b/ash/system/network/network_state_list_detailed_view.cc
@@ -200,7 +200,10 @@ model_(Shell::Get()->system_tray_model()->network_state_model()), info_button_(nullptr), settings_button_(nullptr), - info_bubble_(nullptr) {} + info_bubble_(nullptr) { + OverrideProgressBarAccessibleName(l10n_util::GetStringUTF16( + IDS_ASH_STATUS_TRAY_NETWORK_PROGRESS_ACCESSIBLE_NAME)); +} NetworkStateListDetailedView::~NetworkStateListDetailedView() { model_->RemoveObserver(this);
diff --git a/ash/system/time/calendar_model.cc b/ash/system/time/calendar_model.cc index c58df0a7..d6ac01f 100644 --- a/ash/system/time/calendar_model.cc +++ b/ash/system/time/calendar_model.cc
@@ -518,6 +518,9 @@ CalendarModel::FetchingStatus CalendarModel::FindFetchingStatus( base::Time start_time) const { + if (!calendar_utils::IsActiveUser()) + return kNa; + if (pending_fetches_.count(start_time)) return kFetching; @@ -659,4 +662,12 @@ } } +void CalendarModel::InsertPendingFetchesForTesting(base::Time start_of_month) { + pending_fetches_.emplace(start_of_month, nullptr); +} + +void CalendarModel::DeletePendingFetchesForTesting(base::Time start_of_month) { + pending_fetches_.erase(start_of_month); +} + } // namespace ash
diff --git a/ash/system/time/calendar_model.h b/ash/system/time/calendar_model.h index 39b9d79..b4bf7275 100644 --- a/ash/system/time/calendar_model.h +++ b/ash/system/time/calendar_model.h
@@ -33,7 +33,10 @@ // Controller of the `CalendarView`. class ASH_EXPORT CalendarModel : public SessionObserver { public: - enum FetchingStatus { kNever, kFetching, kSuccess, kError }; + // kNa is used to represent the fetching status when on the non-logged-in + // screens. If kNa is returned, the loading bar won't be shown since events + // are not being fetched. + enum FetchingStatus { kNever, kFetching, kSuccess, kError, kNa }; CalendarModel(); CalendarModel(const CalendarModel& other) = delete; @@ -125,6 +128,8 @@ friend class CalendarViewEventListViewTest; friend class CalendarMonthViewTest; friend class CalendarModelFunctionTest; + friend class CalendarViewTest; + friend class CalendarViewAnimationTest; // Methods for dumping various event containers/representations to logs. void DebugDumpEventLarge(const char* prefix, @@ -207,6 +212,12 @@ base::Time start_of_month, CalendarEventFetchInternalErrorCode error); + // Inserts month into `pending_fetches_`. For testing only. + void InsertPendingFetchesForTesting(base::Time start_of_month); + + // Deletes month from `pending_fetches_`. For testing only. + void DeletePendingFetchesForTesting(base::Time start_of_month); + // Internal storage for fetched events, with each fetched month having a // map of days to events. MonthToEventsMap event_months_;
diff --git a/ash/system/time/calendar_month_view.cc b/ash/system/time/calendar_month_view.cc index 28f9e177..fc99f70 100644 --- a/ash/system/time/calendar_month_view.cc +++ b/ash/system/time/calendar_month_view.cc
@@ -76,7 +76,8 @@ base::Time date, base::TimeDelta time_difference, bool is_grayed_out_date, - int row_index) + int row_index, + bool is_fetched) : views::LabelButton( views::Button::PressedCallback( base::BindRepeating(&CalendarDateCellView::OnDateCellActivated, @@ -86,6 +87,7 @@ date_(date), grayed_out_(is_grayed_out_date), row_index_(row_index), + is_fetched_(is_fetched), time_difference_(time_difference), calendar_view_controller_(calendar_view_controller) { SetHorizontalAlignment(gfx::ALIGN_CENTER); @@ -97,7 +99,7 @@ DisableFocus(); if (!grayed_out_) { - if (calendar_utils::IsActiveUser()) { + if (calendar_utils::IsActiveUser() && is_fetched_) { event_number_ = calendar_view_controller_->GetEventNumber(date_); } SetTooltipAndAccessibleName(); @@ -207,18 +209,23 @@ if (!calendar_utils::IsActiveUser()) { tool_tip_ = formatted_date; } else { - const int tooltip_id = - event_number_ == 1 ? IDS_ASH_CALENDAR_DATE_CELL_TOOLTIP - : IDS_ASH_CALENDAR_DATE_CELL_PLURAL_EVENTS_TOOLTIP; - tool_tip_ = l10n_util::GetStringFUTF16( - tooltip_id, formatted_date, - base::UTF8ToUTF16(base::NumberToString(event_number_))); + if (is_fetched_) { + const int tooltip_id = + event_number_ == 1 ? IDS_ASH_CALENDAR_DATE_CELL_TOOLTIP + : IDS_ASH_CALENDAR_DATE_CELL_PLURAL_EVENTS_TOOLTIP; + tool_tip_ = l10n_util::GetStringFUTF16( + tooltip_id, formatted_date, + base::UTF8ToUTF16(base::NumberToString(event_number_))); + } else { + const int tooltip_id = IDS_ASH_CALENDAR_DATE_CELL_LOADING_TOOLTIP; + tool_tip_ = l10n_util::GetStringFUTF16(tooltip_id, formatted_date); + } } SetTooltipText(tool_tip_); SetAccessibleName(tool_tip_); } -void CalendarDateCellView::MaybeSchedulePaint() { +void CalendarDateCellView::UpdateFetchStatus(bool is_fetched) { // No need to re-paint the grayed out cells, since here should be no change // for them. if (grayed_out_) @@ -229,12 +236,23 @@ return; } - // Early return if the event number doesn't change. - const int event_number = calendar_view_controller_->GetEventNumber(date_); - if (event_number_ == event_number) + // If the fetching status remains unfetched, no need to schedule repaint. + if (!is_fetched_ && !is_fetched) return; - event_number_ = event_number; + // If the events are fetched, gets the event number and checks if the event + // number has been changed. If the event number hasn't been changed and the + // events have been fetched before (i.e. a re-fetch with no event number + // change), no need to repaint. In all other cases, schedules a repaint. + if (is_fetched) { + const int event_number = calendar_view_controller_->GetEventNumber(date_); + if (event_number_ == event_number && is_fetched_) + return; + + event_number_ = event_number; + } + + is_fetched_ = is_fetched; SetTooltipAndAccessibleName(); SchedulePaint(); } @@ -340,6 +358,8 @@ // Fetch events for the month. fetch_month_ = first_day_of_month_local.UTCMidnight(); FetchEvents(fetch_month_); + bool is_fetched = + calendar_view_controller_->isSuccessfullyFetched(fetch_month_); // TODO(https://crbug.com/1236276): Extract the following 3 parts (while // loops) into a method. @@ -348,7 +368,8 @@ while (current_date_exploded.month % 12 == (first_day_of_month_exploded.month - 1) % 12) { AddDateCellToLayout(current_date, column, - /*is_in_current_month=*/false, /*row_index=*/0); + /*is_in_current_month=*/false, /*row_index=*/0, + /*is_fetched=*/is_fetched); MoveToNextDay(column, current_date, current_date_local, current_date_exploded); } @@ -362,7 +383,8 @@ } auto* cell = AddDateCellToLayout(current_date, column, /*is_in_current_month=*/true, - /*row_index=*/row_number - 1); + /*row_index=*/row_number - 1, + /*is_fetched=*/is_fetched); // Add the first non-grayed-out cell of the row to the `focused_cells_`. if (column == 0 || current_date_exploded.day_of_month == 1) { focused_cells_.push_back(cell); @@ -385,6 +407,15 @@ // To receive the fetched events. scoped_calendar_model_observer_.Observe(calendar_model_); + // Gets the fetched status again in case the events are fetched in the middle + // of rendering date cells. + bool updated_is_fetched = + calendar_view_controller_->isSuccessfullyFetched(fetch_month_); + + // If the fetching status changed, schedule repaint. + if (updated_is_fetched != is_fetched) + UpdateIsFetchedAndRepaint(updated_is_fetched); + if (calendar_utils::GetDayOfWeek(current_date) == calendar_utils::kFirstDayOfWeekString) return; @@ -406,7 +437,8 @@ // Next column is generated. AddDateCellToLayout(current_date, column, /*is_in_current_month=*/false, - /*row_index=*/row_number); + /*row_index=*/row_number, + /*is_fetched=*/is_fetched); MoveToNextDay(column, current_date, current_date_local, current_date_exploded); } @@ -425,21 +457,23 @@ const base::Time start_time, const google_apis::calendar::EventList* events) { if (status == CalendarModel::kSuccess && start_time == fetch_month_) - SchedulePaintChildren(); + UpdateIsFetchedAndRepaint(true); } CalendarDateCellView* CalendarMonthView::AddDateCellToLayout( base::Time current_date, int column, bool is_in_current_month, - int row_index) { + int row_index, + bool is_fetched) { auto* layout_manager = static_cast<views::TableLayout*>(GetLayoutManager()); if (column == 0) layout_manager->AddRows(1, views::TableLayout::kFixedSize); return AddChildView(std::make_unique<CalendarDateCellView>( calendar_view_controller_, current_date, calendar_utils::GetTimeDifference(current_date), - /*is_grayed_out_date=*/!is_in_current_month, /*row_index=*/row_index)); + /*is_grayed_out_date=*/!is_in_current_month, /*row_index=*/row_index, + /*is_fetched=*/is_fetched)); } void CalendarMonthView::EnableFocus() { @@ -452,9 +486,10 @@ static_cast<CalendarDateCellView*>(cell)->DisableFocus(); } -void CalendarMonthView::SchedulePaintChildren() { +void CalendarMonthView::UpdateIsFetchedAndRepaint(bool updated_is_fetched) { for (auto* cell : children()) - static_cast<CalendarDateCellView*>(cell)->MaybeSchedulePaint(); + static_cast<CalendarDateCellView*>(cell)->UpdateFetchStatus( + updated_is_fetched); } BEGIN_METADATA(CalendarDateCellView, views::View)
diff --git a/ash/system/time/calendar_month_view.h b/ash/system/time/calendar_month_view.h index 0296f39c..7a28a0c 100644 --- a/ash/system/time/calendar_month_view.h +++ b/ash/system/time/calendar_month_view.h
@@ -30,7 +30,8 @@ base::Time date, base::TimeDelta time_difference, bool is_grayed_out_date, - int row_index); + int row_index, + bool is_fetched); CalendarDateCellView(const CalendarDateCellView& other) = delete; CalendarDateCellView& operator=(const CalendarDateCellView& other) = delete; ~CalendarDateCellView() override; @@ -55,8 +56,8 @@ // Sets the tooltip label and a11y label based on the `event_number_`. void SetTooltipAndAccessibleName(); - // Schedule paint the cell to show the event dot. - void MaybeSchedulePaint(); + // Updates the fetching status and checks if needs to repaint. + void UpdateFetchStatus(bool is_fetched); // When focusing on the date cell for the first time, it shows "Use arrow keys // to navigate between dates" as instructions. @@ -90,6 +91,9 @@ // The row index in the current month for this date cell. Starts from 0. const int row_index_; + // If the events of this date cell's month view have been fetched. + bool is_fetched_; + // If the current cell is selected. bool is_selected_ = false; @@ -132,9 +136,6 @@ // Disable each cell's focus behavior. void DisableFocus(); - // Re-paints the child cells. - void SchedulePaintChildren(); - // Gets the cells of each row that should be first focused on. std::vector<CalendarDateCellView*> focused_cells() { return focused_cells_; } @@ -144,13 +145,19 @@ // Returns the index of this month view's last row. int last_row_index() const { return last_row_index_; } + // Updates is_fetched_ for each date cell and schedules repaint. + void UpdateIsFetchedAndRepaint(bool updated_is_fetched); + private: + // For unit tests. + friend class CalendarMonthViewTest; // Adds the `current_date`'s `CalendarDateCellView` to the table layout and // returns it. CalendarDateCellView* AddDateCellToLayout(base::Time current_date, int column, bool is_in_current_month, - int row_index); + int row_index, + bool is_fetched); // Fetches events. void FetchEvents(const base::Time& month);
diff --git a/ash/system/time/calendar_month_view_unittest.cc b/ash/system/time/calendar_month_view_unittest.cc index ecbff79e..6596568 100644 --- a/ash/system/time/calendar_month_view_unittest.cc +++ b/ash/system/time/calendar_month_view_unittest.cc
@@ -83,7 +83,7 @@ } void UploadEvents() { - Shell::Get()->system_tray_model()->calendar_model()->InsertEventsForTesting( + calendar_month_view_->calendar_model_->InsertEventsForTesting( CreateMockEventList().get()); } @@ -96,6 +96,26 @@ CalendarMonthView* month_view() { return calendar_month_view_.get(); } CalendarViewController* controller() { return controller_.get(); } + void InsertPendingFetches(base::Time start_of_month) { + calendar_month_view_->calendar_model_->InsertPendingFetchesForTesting( + start_of_month); + } + + void DeletePendingFetches(base::Time start_of_month) { + calendar_month_view_->calendar_model_->DeletePendingFetchesForTesting( + start_of_month); + } + + void NotifyObservers(base::Time start_of_month) { + for (auto& observer : calendar_month_view_->calendar_model_->observers_) + observer.OnEventsFetched(CalendarModel::kSuccess, start_of_month, + nullptr); + } + + CalendarModel::MonthToEventsMap event_months() { + return calendar_month_view_->calendar_model_->event_months_; + } + static base::Time FakeTimeNow() { return fake_time_; } static void SetFakeNow(base::Time fake_now) { fake_time_ = fake_now; } @@ -260,6 +280,8 @@ /*thread_ticks_override=*/nullptr); CreateMonthView(date, u"America/Los_Angeles"); + // Used to fetch events and notify observers. + base::Time date_midnight = date.UTCMidnight(); TriggerPaint(); // Grayed out cell. Sep 2nd is the 33 one in this calendar, which is with @@ -274,30 +296,50 @@ EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetText()); - EXPECT_EQ(u"Wednesday, August 18, 2021, 0 events", + EXPECT_EQ(u"Wednesday, August 18, 2021, Loading events.", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetTooltipText()); - // After events are fetched before re-painting the event number is not - // updated. - UploadEvents(); + InsertPendingFetches(date_midnight); + // Grayed out cell. Sep 2nd is the 33 one in this calendar, which is with + // index 32. EXPECT_EQ(u"2", static_cast<CalendarDateCellView*>(month_view()->children()[32]) ->GetText()); EXPECT_EQ(u"", static_cast<CalendarDateCellView*>(month_view()->children()[32]) ->GetTooltipText()); + // Regular cell. The 18th child is the cell 18 which is with index 17. EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetText()); - EXPECT_EQ(u"Wednesday, August 18, 2021, 0 events", + EXPECT_EQ(u"Wednesday, August 18, 2021, Loading events.", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetTooltipText()); - // After re-painting, the event numbers are updated for regular cells, not for - // grayed out cells. - month_view()->SchedulePaintChildren(); - TriggerPaint(); + // After events are fetched before the observers are notified the event number + // is not updated. + DeletePendingFetches(date_midnight); + UploadEvents(); + // Grayed out cell. Sep 2nd is the 33 one in this calendar, which is with + // index 32. + EXPECT_EQ(u"2", + static_cast<CalendarDateCellView*>(month_view()->children()[32]) + ->GetText()); + EXPECT_EQ(u"", + static_cast<CalendarDateCellView*>(month_view()->children()[32]) + ->GetTooltipText()); + // Regular cell. The 18th child is the cell 18 which is with index 17. + EXPECT_EQ(u"18", + static_cast<CalendarDateCellView*>(month_view()->children()[17]) + ->GetText()); + EXPECT_EQ(u"Wednesday, August 18, 2021, Loading events.", + static_cast<CalendarDateCellView*>(month_view()->children()[17]) + ->GetTooltipText()); + + // After notifying observers and repainting, the event numbers are updated for + // regular cells, not for grayed out cells. + NotifyObservers(date_midnight); EXPECT_EQ(u"2", static_cast<CalendarDateCellView*>(month_view()->children()[32]) ->GetText()); @@ -326,12 +368,14 @@ &CalendarMonthViewTest::FakeTimeNow, /*time_ticks_override=*/nullptr, /*thread_ticks_override=*/nullptr); + // Used to fetch events and notify observers. + base::Time date_midnight = date.UTCMidnight(); + // Sets the timezone to "America/Los_Angeles"; CreateMonthView(date, u"America/Los_Angeles"); TriggerPaint(); UploadEvents(); - month_view()->SchedulePaintChildren(); - TriggerPaint(); + NotifyObservers(date_midnight); EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) @@ -374,10 +418,12 @@ /*thread_ticks_override=*/nullptr); CreateMonthView(date, u"America/Los_Angeles"); + // Used to fetch events and notify observers. + base::Time date_midnight = date.UTCMidnight(); + TriggerPaint(); UploadEvents(); - month_view()->SchedulePaintChildren(); - TriggerPaint(); + NotifyObservers(date_midnight); EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) ->GetText()); @@ -388,7 +434,7 @@ // Changes user session to inactive. Should not show event number. GetSessionControllerClient()->SetSessionState( session_manager::SessionState::OOBE); - month_view()->SchedulePaintChildren(); + month_view()->UpdateIsFetchedAndRepaint(false); TriggerPaint(); EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17]) @@ -399,7 +445,7 @@ GetSessionControllerClient()->SetSessionState( session_manager::SessionState::LOCKED); - month_view()->SchedulePaintChildren(); + month_view()->UpdateIsFetchedAndRepaint(false); TriggerPaint(); EXPECT_EQ(u"18", static_cast<CalendarDateCellView*>(month_view()->children()[17])
diff --git a/ash/system/time/calendar_utils.cc b/ash/system/time/calendar_utils.cc index cb7b64e..93fca4c 100644 --- a/ash/system/time/calendar_utils.cc +++ b/ash/system/time/calendar_utils.cc
@@ -240,7 +240,7 @@ return GetStartOfMonthUTC(GetStartOfMonthUTC(date) + base::Days(33)); } -bool IsActiveUser() { +ASH_EXPORT bool IsActiveUser() { absl::optional<user_manager::UserType> user_type = Shell::Get()->session_controller()->GetUserType(); return (user_type && *user_type == user_manager::USER_TYPE_REGULAR) &&
diff --git a/ash/system/time/calendar_view.cc b/ash/system/time/calendar_view.cc index 818754f..da82fa3e 100644 --- a/ash/system/time/calendar_view.cc +++ b/ash/system/time/calendar_view.cc
@@ -3,14 +3,13 @@ // found in the LICENSE file. #include "ash/system/time/calendar_view.h" + #include <memory> #include "ash/public/cpp/ash_typography.h" -#include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/icon_button.h" #include "ash/style/pill_button.h" -#include "ash/system/model/system_tray_model.h" #include "ash/system/time/calendar_event_list_view.h" #include "ash/system/time/calendar_metrics.h" #include "ash/system/time/calendar_month_view.h" @@ -39,6 +38,7 @@ #include "ui/views/animation/animation_builder.h" #include "ui/views/controls/label.h" #include "ui/views/controls/scroll_view.h" +#include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/table_layout.h" #include "ui/views/view.h" @@ -61,6 +61,9 @@ // The offset for `month_label_` to make it align with `month_header`. constexpr int kMonthLabelPaddingOffset = -1; +// The cool-down time for calling `UpdateOnScreenMonthMap()` after scrolling. +constexpr base::TimeDelta kScrollingSettledTimeout = base::Milliseconds(100); + // Duration of the delay for modifying opacity. constexpr base::TimeDelta kDelayVisibilityAnimationDuration = base::Milliseconds(200); @@ -76,6 +79,10 @@ // The cool-down time for enabling animation. constexpr base::TimeDelta kAnimationDisablingTimeout = base::Milliseconds(500); +// The multiplier used to reduce velocity of flings on the calendar view. +// Without this, CalendarView will scroll a few years per fast swipe. +constexpr float kCalendarScrollFlingMultiplier = 0.25f; + constexpr char kMonthViewScrollOneMonthAnimationHistogram[] = "Ash.CalendarView.ScrollOneMonth.MonthView.AnimationSmoothness"; @@ -329,6 +336,11 @@ : TrayDetailedView(delegate), controller_(controller), calendar_view_controller_(std::make_unique<CalendarViewController>()), + scrolling_settled_timer_( + FROM_HERE, + kScrollingSettledTimeout, + base::BindRepeating(&CalendarView::UpdateOnScreenMonthMap, + base::Unretained(this))), header_animation_restart_timer_( FROM_HERE, kAnimationDisablingTimeout, @@ -352,8 +364,16 @@ SetFocusBehavior(FocusBehavior::ALWAYS); GetViewAccessibility().OverrideName(GetClassName()); + // Since there's no separator in the `CalendarView`, first sets + // `has_separator` in `TrayDetailedView` to false. + IgnoreSeparator(); + CreateTitleRow(IDS_ASH_CALENDAR_TITLE); + // Adds the progress bar to layout when initialization to avoid changing the + // layout while reading the bounds of it. + ShowProgress(-1, false); + // Add the header. header_ = new CalendarHeaderView( calendar_view_controller_->GetOnScreenMonthName(), @@ -405,6 +425,9 @@ scroll_view_->SetDrawOverflowIndicator(false); scroll_view_->SetVerticalScrollBarMode( views::ScrollView::ScrollBarMode::kHiddenButEnabled); + scroll_view_->vertical_scroll_bar()->SetFlingMultiplier( + kCalendarScrollFlingMultiplier); + scroll_view_->SetFocusBehavior(FocusBehavior::NEVER); on_contents_scrolled_subscription_ = scroll_view_->AddContentsScrolledCallback(base::BindRepeating( @@ -427,6 +450,7 @@ SetMonthViews(); + scoped_calendar_model_observer_.Observe(calendar_model_); scoped_calendar_view_controller_observer_.Observe( calendar_view_controller_.get()); scoped_view_observer_.AddObservation(scroll_view_); @@ -495,19 +519,18 @@ void CalendarView::SetMonthViews() { previous_label_ = AddLabelWithId(LabelType::PREVIOUS); previous_month_ = - AddMonth(calendar_view_controller_->GetPreviousMonthFirstDayLocal(1)); + AddMonth(calendar_view_controller_->GetPreviousMonthFirstDayUTC(1)); current_label_ = AddLabelWithId(LabelType::CURRENT); current_month_ = - AddMonth(calendar_view_controller_->GetOnScreenMonthFirstDayLocal()); + AddMonth(calendar_view_controller_->GetOnScreenMonthFirstDayUTC()); next_label_ = AddLabelWithId(LabelType::NEXT); - next_month_ = - AddMonth(calendar_view_controller_->GetNextMonthFirstDayLocal(1)); + next_month_ = AddMonth(calendar_view_controller_->GetNextMonthFirstDayUTC(1)); next_next_label_ = AddLabelWithId(LabelType::NEXTNEXT); next_next_month_ = AddMonth( - calendar_view_controller_->GetNextMonthFirstDayLocal(/*num_months=*/2)); + calendar_view_controller_->GetNextMonthFirstDayUTC(/*num_months=*/2)); } int CalendarView::PositionOfCurrentMonth() const { @@ -564,26 +587,10 @@ views::AnimationBuilder() .SetPreemptionStrategy( ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET) - .OnEnded(base::BindOnce( - [](base::WeakPtr<CalendarView> calendar_view) { - if (!calendar_view) - return; - calendar_view->SetShouldMonthsAnimateAndScrollEnabled( - /*enabled=*/true); - calendar_view->ResetToToday(); - calendar_view->FadeInCurrentMonth(); - }, - weak_factory_.GetWeakPtr())) - .OnAborted(base::BindOnce( - [](base::WeakPtr<CalendarView> calendar_view) { - if (!calendar_view) - return; - calendar_view->SetShouldMonthsAnimateAndScrollEnabled( - /*enabled=*/true); - calendar_view->ResetToToday(); - calendar_view->FadeInCurrentMonth(); - }, - weak_factory_.GetWeakPtr())) + .OnEnded(base::BindOnce(&CalendarView::OnResetToTodayAnimationComplete, + weak_factory_.GetWeakPtr())) + .OnAborted(base::BindOnce(&CalendarView::OnResetToTodayAnimationComplete, + weak_factory_.GetWeakPtr())) .Once() .SetDuration(calendar_utils::kResetToTodayFadeAnimationDuration) .SetOpacity(header_, 0.0f) @@ -637,6 +644,69 @@ } } +void CalendarView::UpdateOnScreenMonthMap() { + base::Time current_date = calendar_view_controller_->currently_shown_date(); + base::Time start_time = calendar_utils::GetStartOfMonthUTC( + current_date + calendar_utils::GetTimeDifference(current_date)); + + MaybeAddOnScreenMonth(start_time); + + std::set<base::Time> updated_on_screen_month; + updated_on_screen_month.insert(start_time); + + // Checks if `next_month_` is in the visible view. If so, adds it to + // `on_screen_month_` if not already presents. + if (scroll_view_->GetVisibleRect().bottom() >= next_month_->y()) { + base::Time next_start_time = + calendar_utils::GetStartOfNextMonthUTC(start_time); + updated_on_screen_month.insert(next_start_time); + MaybeAddOnScreenMonth(next_start_time); + + // Checks if `next_next_month_` is in the visible view. If so, adds it to + // `on_screen_month_` if not already presents. + if (scroll_view_->GetVisibleRect().bottom() >= next_next_month_->y()) { + base::Time next_next_start_time = + calendar_utils::GetStartOfNextMonthUTC(next_start_time); + updated_on_screen_month.insert(next_next_start_time); + MaybeAddOnScreenMonth(next_next_start_time); + } + } + + // Checks if all months in `on_screen_month_` is within the visible window. If + // not, removes it from the map. + for (auto it = on_screen_month_.begin(); it != on_screen_month_.end();) { + if (updated_on_screen_month.find(it->first) == + updated_on_screen_month.end()) { + it = on_screen_month_.erase(it); + continue; + } + // Increments the iterator here to avoid a crash since the iterator will + // be modified in the loop body. + ++it; + } + + MaybeUpdateLoadingBarVisibility(); +} + +void CalendarView::MaybeAddOnScreenMonth(base::Time start_of_month) { + if (on_screen_month_.find(start_of_month) == on_screen_month_.end()) + on_screen_month_.emplace( + start_of_month, calendar_model_->FindFetchingStatus(start_of_month)); +} + +void CalendarView::MaybeUpdateLoadingBarVisibility() { + for (auto& it : on_screen_month_) { + // If there's an on-screen month that hasn't finished fetching and it's not + // on the lock screen, the loading bar should be visible. + if (it.second != CalendarModel::kSuccess && + it.second != CalendarModel::kNa) { + ShowProgress(-1, true); + return; + } + } + ShowProgress(-1, false); +} + void CalendarView::FadeInCurrentMonth() { if (!should_months_animate_) return; @@ -688,6 +758,7 @@ header_->layer()->GetAnimator()->StopAnimating(); header_->layer()->SetOpacity(1.0f); header_->layer()->SetTransform(gfx::Transform()); + scrolling_settled_timer_.Reset(); if (!should_header_animate_) header_animation_restart_timer_.Reset(); } @@ -781,6 +852,11 @@ // Request focus to enable the user to quickly press enter to see todays // events. If the view was not shown via keyboard, this will be a no-op. RequestFocus(); + + // Reset the timer here to invoke `UpdateOnScreenMonthMap()` manually after + // 'kScrollingSettledTimeout` since layout will be finalized after a few + // iterations and `on_screen_month_` only wants the final result. + scrolling_settled_timer_.Reset(); } void CalendarView::OnViewFocused(View* observed_view) { @@ -864,6 +940,7 @@ if (!calendar_view) return; calendar_view->set_should_header_animate(true); + calendar_view->reset_scrolling_settled_timer(); }, weak_factory_.GetWeakPtr())) .OnAborted(base::BindOnce( @@ -886,6 +963,16 @@ .SetOpacity(header_, 1.0f); } +void CalendarView::OnEventsFetched( + const CalendarModel::FetchingStatus status, + const base::Time start_time, + const google_apis::calendar::EventList* events) { + if (on_screen_month_.find(start_time) != on_screen_month_.end()) + on_screen_month_[start_time] = status; + + MaybeUpdateLoadingBarVisibility(); +} + void CalendarView::OpenEventList() { // Don't show the the `event_list_` view for unlogged in users. if (!calendar_utils::IsActiveUser()) @@ -1011,7 +1098,7 @@ void CalendarView::ScrollUpOneMonth() { calendar_view_controller_->UpdateMonth( - calendar_view_controller_->GetPreviousMonthFirstDayLocal(1)); + calendar_view_controller_->GetPreviousMonthFirstDayUTC(1)); content_view_->RemoveChildViewT(next_next_label_); content_view_->RemoveChildViewT(next_next_month_); @@ -1023,7 +1110,7 @@ current_month_ = previous_month_; previous_month_ = - AddMonth(calendar_view_controller_->GetPreviousMonthFirstDayLocal(1), + AddMonth(calendar_view_controller_->GetPreviousMonthFirstDayUTC(1), /*add_at_front=*/true); if (IsDateCellViewFocused()) previous_month_->EnableFocus(); @@ -1052,7 +1139,7 @@ previous_label_->GetPreferredSize().height(); calendar_view_controller_->UpdateMonth( - calendar_view_controller_->GetNextMonthFirstDayLocal(1)); + calendar_view_controller_->GetNextMonthFirstDayUTC(1)); content_view_->RemoveChildViewT(previous_label_); content_view_->RemoveChildViewT(previous_month_); @@ -1066,7 +1153,7 @@ next_next_label_ = AddLabelWithId(LabelType::NEXTNEXT); next_next_month_ = AddMonth( - calendar_view_controller_->GetNextMonthFirstDayLocal(/*num_months=*/2)); + calendar_view_controller_->GetNextMonthFirstDayUTC(/*num_months=*/2)); if (IsDateCellViewFocused()) next_next_month_->EnableFocus(); @@ -1432,6 +1519,10 @@ base::AutoReset<bool> disable_header_animation(&should_header_animate_, false); + + // Reset the timer to update the `on_screen_month_` map after scrolling. + scrolling_settled_timer_.Reset(); + // Scrolls to the previous month if the current label is moving down and // passing the top of the visible area. if (scroll_view_->GetVisibleRect().y() <= current_label_->y()) { @@ -1529,6 +1620,17 @@ FocusTodayOrFirstDateCell(); } +void CalendarView::OnResetToTodayAnimationComplete() { + SetShouldMonthsAnimateAndScrollEnabled(/*enabled=*/true); + ResetToToday(); + FadeInCurrentMonth(); + // There's a corner case when the `current_month_` doesn't change, + // the `on_screen_month_` map won't be updated since + // `OnMonthChanged` won't be called and the timer won't be reset. So + // we manually call the timer to update `on_screen_month_`. + reset_scrolling_settled_timer(); +} + void CalendarView::FocusTodayOrFirstDateCell() { previous_month_->EnableFocus(); current_month_->EnableFocus();
diff --git a/ash/system/time/calendar_view.h b/ash/system/time/calendar_view.h index 6fe03f7..5a177b8 100644 --- a/ash/system/time/calendar_view.h +++ b/ash/system/time/calendar_view.h
@@ -8,13 +8,20 @@ #include <string> #include "ash/ash_export.h" +#include "ash/shell.h" +#include "ash/strings/grit/ash_strings.h" +#include "ash/system/model/system_tray_model.h" +#include "ash/system/time/calendar_model.h" #include "ash/system/time/calendar_view_controller.h" #include "ash/system/tray/tray_detailed_view.h" #include "ash/system/unified/unified_system_tray_controller.h" #include "base/callback_list.h" #include "base/memory/weak_ptr.h" #include "base/scoped_multi_source_observation.h" +#include "base/scoped_observation.h" #include "base/timer/timer.h" +#include "calendar_model.h" +#include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/view.h" @@ -61,7 +68,8 @@ }; // This view displays a scrollable calendar. -class ASH_EXPORT CalendarView : public CalendarViewController::Observer, +class ASH_EXPORT CalendarView : public CalendarModel::Observer, + public CalendarViewController::Observer, public TrayDetailedView, public views::ViewObserver { public: @@ -73,6 +81,11 @@ CalendarView& operator=(const CalendarView& other) = delete; ~CalendarView() override; + // CalendarModel::Observer: + void OnEventsFetched(const CalendarModel::FetchingStatus status, + const base::Time start_time, + const google_apis::calendar::EventList* events) override; + // CalendarViewController::Observer: void OnMonthChanged() override; void OpenEventList() override; @@ -205,6 +218,17 @@ // animation. void ResetToToday(); + // Updates the on-screen month map with the current months on screen. + void UpdateOnScreenMonthMap(); + + // If the key `start_of_month` is not in the map, insert it with the value as + // the fetching status of `start_of_month`. + void MaybeAddOnScreenMonth(base::Time start_of_month); + + // Checks if all months in the visible window have finished fetching. If so, + // stop showing the loading bar. + void MaybeUpdateLoadingBarVisibility(); + // Fades in current month. void FadeInCurrentMonth(); @@ -253,6 +277,11 @@ void OnOpenEventListAnimationComplete(); void OnCloseEventListAnimationComplete(); + // Animates the month and scrolls back to today and resets the + // `scrolling_settled_timer_` to update the `on_screen_month_` map after the + // resetting to today animation. + void OnResetToTodayAnimationComplete(); + // Focuses todays DateCellView, or the first available one in // `current_month_`. void FocusTodayOrFirstDateCell(); @@ -269,6 +298,8 @@ UnifiedSystemTrayController* controller_; std::unique_ptr<CalendarViewController> calendar_view_controller_; + // Reset `scrolling_settled_timer_`. + void reset_scrolling_settled_timer() { scrolling_settled_timer_.Reset(); } // The content of the `scroll_view_`, which carries months and month labels. // Owned by `CalendarView`. @@ -290,6 +321,9 @@ IconButton* up_button_ = nullptr; IconButton* down_button_ = nullptr; CalendarEventListView* event_list_view_ = nullptr; + std::map<base::Time, CalendarModel::FetchingStatus> on_screen_month_; + CalendarModel* calendar_model_ = + Shell::Get()->system_tray_model()->calendar_model(); // If it `is_resetting_scroll_`, we don't calculate the scroll position and we // don't need to check if we need to update the month or not. @@ -311,6 +345,10 @@ // Whether the Calendar View is scrolling. bool is_calendar_view_scrolling_ = false; + // Timer that fires when the calendar view is settled on, i.e. finished + // scrolling to, a currently-visible month + base::RetainingOneShotTimer scrolling_settled_timer_; + // Timers that enable the updating month/header animations. When the month // keeps getting changed, the animation will be disabled and the cool-down // duration is `kAnimationDisablingTimeout` ms to enable the next animation. @@ -318,6 +356,8 @@ base::RetainingOneShotTimer months_animation_restart_timer_; base::CallbackListSubscription on_contents_scrolled_subscription_; + base::ScopedObservation<CalendarModel, CalendarModel::Observer> + scoped_calendar_model_observer_{this}; base::ScopedObservation<CalendarViewController, CalendarViewController::Observer> scoped_calendar_view_controller_observer_{this};
diff --git a/ash/system/time/calendar_view_controller.cc b/ash/system/time/calendar_view_controller.cc index c17d5c5..5e8dae4 100644 --- a/ash/system/time/calendar_view_controller.cc +++ b/ash/system/time/calendar_view_controller.cc
@@ -95,7 +95,7 @@ observer.OnMonthChanged(); } -base::Time CalendarViewController::GetOnScreenMonthFirstDayLocal() { +base::Time CalendarViewController::GetOnScreenMonthFirstDayUTC() { base::TimeDelta time_difference = calendar_utils::GetTimeDifference(currently_shown_date_); return calendar_utils::GetFirstDayOfMonth(currently_shown_date_ + @@ -103,10 +103,9 @@ time_difference; } -base::Time CalendarViewController::GetPreviousMonthFirstDayLocal( +base::Time CalendarViewController::GetPreviousMonthFirstDayUTC( unsigned int num_months) { - base::Time prev, - current = ApplyTimeDifference(GetOnScreenMonthFirstDayLocal()); + base::Time prev, current = ApplyTimeDifference(GetOnScreenMonthFirstDayUTC()); DCHECK_GE(num_months, 1UL); @@ -117,10 +116,9 @@ return prev - calendar_utils::GetTimeDifference(prev); } -base::Time CalendarViewController::GetNextMonthFirstDayLocal( +base::Time CalendarViewController::GetNextMonthFirstDayUTC( unsigned int num_months) { - base::Time next, - current = ApplyTimeDifference(GetOnScreenMonthFirstDayLocal()); + base::Time next, current = ApplyTimeDifference(GetOnScreenMonthFirstDayUTC()); DCHECK_GE(num_months, 1UL); @@ -132,11 +130,11 @@ } std::u16string CalendarViewController::GetPreviousMonthName() { - return calendar_utils::GetMonthName(GetPreviousMonthFirstDayLocal(1)); + return calendar_utils::GetMonthName(GetPreviousMonthFirstDayUTC(1)); } std::u16string CalendarViewController::GetNextMonthName(int num_months) { - return calendar_utils::GetMonthName(GetNextMonthFirstDayLocal(num_months)); + return calendar_utils::GetMonthName(GetNextMonthFirstDayUTC(num_months)); } std::u16string CalendarViewController::GetOnScreenMonthName() const { @@ -230,6 +228,13 @@ calendar_utils::GetMonthNameAndYear(selected_date_.value()); } +bool CalendarViewController::isSuccessfullyFetched(base::Time start_of_month) { + return Shell::Get() + ->system_tray_model() + ->calendar_model() + ->FindFetchingStatus(start_of_month) == CalendarModel::kSuccess; +} + base::Time CalendarViewController::ApplyTimeDifference(base::Time date) { return date + calendar_utils::GetTimeDifference(date); }
diff --git a/ash/system/time/calendar_view_controller.h b/ash/system/time/calendar_view_controller.h index 36382c2..462d5a9 100644 --- a/ash/system/time/calendar_view_controller.h +++ b/ash/system/time/calendar_view_controller.h
@@ -52,16 +52,17 @@ // Updates the `currently_shown_date_`. void UpdateMonth(const base::Time current_month_first_date); - // Gets the first day of the `currently_shown_date_`'s month, in local time. - base::Time GetOnScreenMonthFirstDayLocal(); + // Gets the first day of the `currently_shown_date_`'s month, in UTC time. + // Time difference is applied. + base::Time GetOnScreenMonthFirstDayUTC(); // Gets the first day of the nth-previous month based on the - // `currently_shown_date_`'s month, in local time. - base::Time GetPreviousMonthFirstDayLocal(unsigned int num_months); + // `currently_shown_date_`'s month, in UTC time. Time difference is applied. + base::Time GetPreviousMonthFirstDayUTC(unsigned int num_months); // Gets the first day of the nth-next month based on the - // `currently_shown_date_`'s month, in local time. - base::Time GetNextMonthFirstDayLocal(unsigned int num_months); + // `currently_shown_date_`'s month, in UTC time. Time difference is applied. + base::Time GetNextMonthFirstDayUTC(unsigned int num_months); // Gets the month name of the `currently_shown_date_`'s month. std::u16string GetOnScreenMonthName() const; @@ -141,6 +142,9 @@ // `CalendarView` if the month should be updated when a date is selected. bool IsSelectedDateInCurrentMonth(); + // Returns whether the events for `start_of_month` is fetched or not. + bool isSuccessfullyFetched(base::Time start_of_month); + private: // For unit tests. friend class CalendarMonthViewTest;
diff --git a/ash/system/time/calendar_view_controller_unittest.cc b/ash/system/time/calendar_view_controller_unittest.cc index b350e73a6..9a68879 100644 --- a/ash/system/time/calendar_view_controller_unittest.cc +++ b/ash/system/time/calendar_view_controller_unittest.cc
@@ -31,7 +31,7 @@ controller->UpdateMonth(date); base::Time::Exploded first_day_exploded; - base::Time first_day = controller->GetOnScreenMonthFirstDayLocal(); + base::Time first_day = controller->GetOnScreenMonthFirstDayUTC(); first_day.LocalExplode(&first_day_exploded); std::u16string month_name = controller->GetOnScreenMonthName(); @@ -41,7 +41,7 @@ EXPECT_EQ(u"August", month_name); base::Time::Exploded previous_first_day_exploded; - base::Time previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + base::Time previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_first_day.LocalExplode(&previous_first_day_exploded); std::u16string previous_month_name = controller->GetPreviousMonthName(); @@ -51,7 +51,7 @@ EXPECT_EQ(u"July", previous_month_name); base::Time::Exploded next_first_day_exploded; - base::Time next_first_day = controller->GetNextMonthFirstDayLocal(1); + base::Time next_first_day = controller->GetNextMonthFirstDayUTC(1); next_first_day.LocalExplode(&next_first_day_exploded); std::u16string next_month_name = controller->GetNextMonthName(); @@ -72,7 +72,7 @@ controller->UpdateMonth(last_month_date); base::Time::Exploded january_first_day_exploded; - base::Time january_first_day = controller->GetNextMonthFirstDayLocal(1); + base::Time january_first_day = controller->GetNextMonthFirstDayUTC(1); january_first_day.LocalExplode(&january_first_day_exploded); std::u16string january_month_name = controller->GetNextMonthName(); @@ -89,7 +89,7 @@ controller->UpdateMonth(first_month_date); base::Time::Exploded dec_first_day_exploded; - base::Time dec_first_day = controller->GetPreviousMonthFirstDayLocal(1); + base::Time dec_first_day = controller->GetPreviousMonthFirstDayUTC(1); dec_first_day.LocalExplode(&dec_first_day_exploded); std::u16string dec_month_name = controller->GetPreviousMonthName(); @@ -113,9 +113,9 @@ controller->UpdateMonth(current_month_date); - base::Time previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + base::Time previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); std::u16string previous_month_name = controller->GetPreviousMonthName(); - base::Time next_first_day = controller->GetNextMonthFirstDayLocal(1); + base::Time next_first_day = controller->GetNextMonthFirstDayUTC(1); std::u16string next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"March 1, 2022", @@ -127,9 +127,9 @@ // Set timezone to Pacific Daylight Time. Mar 13th is the daylight saving // starts day. ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"PST"); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"March 1, 2022", @@ -146,9 +146,9 @@ controller->UpdateMonth(current_month_date2); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"February 1, 2022", @@ -159,9 +159,9 @@ // Set the timezone back to GMT. ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"GMT"); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"March 1, 2022", @@ -177,9 +177,9 @@ controller->UpdateMonth(current_month_date3); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"October 1, 2022", @@ -192,9 +192,9 @@ // Set timezone to Pacific Daylight Time. Nov 6th is the daylight saving // ends day. ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"PST"); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"October 1, 2022", @@ -212,9 +212,9 @@ controller->UpdateMonth(current_month_date4); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"September 1, 2022", @@ -226,9 +226,9 @@ // Set the timezone back to GMT. ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(u"GMT"); - previous_first_day = controller->GetPreviousMonthFirstDayLocal(1); + previous_first_day = controller->GetPreviousMonthFirstDayUTC(1); previous_month_name = controller->GetPreviousMonthName(); - next_first_day = controller->GetNextMonthFirstDayLocal(1); + next_first_day = controller->GetNextMonthFirstDayUTC(1); next_month_name = controller->GetNextMonthName(); EXPECT_EQ(u"October 1, 2022",
diff --git a/ash/system/time/calendar_view_unittest.cc b/ash/system/time/calendar_view_unittest.cc index 855f978..33e5d56fb 100644 --- a/ash/system/time/calendar_view_unittest.cc +++ b/ash/system/time/calendar_view_unittest.cc
@@ -4,6 +4,7 @@ #include "ash/system/time/calendar_view.h" +#include "ash/components/settings/timezone_settings.h" #include "ash/constants/ash_features.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" @@ -12,6 +13,7 @@ #include "ash/system/message_center/unified_message_center_bubble.h" #include "ash/system/message_center/unified_message_center_view.h" #include "ash/system/time/calendar_event_list_view.h" +#include "ash/system/time/calendar_model.h" #include "ash/system/time/calendar_month_view.h" #include "ash/system/time/calendar_unittest_utils.h" #include "ash/system/time/calendar_utils.h" @@ -43,6 +45,7 @@ namespace { constexpr char kTestUser[] = "user@test"; +constexpr int kLoadingBarIndex = 2; } // namespace @@ -1139,6 +1142,9 @@ void UpdateMonth(base::Time date) { calendar_view_->calendar_view_controller()->UpdateMonth(date); + // Advances the time to allow `on_screen_month_` to update. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); calendar_view_->content_view_->RemoveAllChildViews(); calendar_view_->SetMonthViews(); } @@ -1188,6 +1194,30 @@ views::ScrollView* scroll_view() { return calendar_view_->scroll_view_; } views::View* event_list_view() { return calendar_view_->event_list_view_; } + std::map<base::Time, CalendarModel::FetchingStatus> on_screen_month() { + return calendar_view_->on_screen_month_; + } + + CalendarModel::MonthToEventsMap event_months() { + return calendar_view_->calendar_model_->event_months_; + } + + void InsertPendingFetches(base::Time start_of_month) { + calendar_view_->calendar_model_->InsertPendingFetchesForTesting( + start_of_month); + } + + void DeletePendingFetches(base::Time start_of_month) { + calendar_view_->calendar_model_->DeletePendingFetchesForTesting( + start_of_month); + } + + void NotifyObservers(base::Time start_of_month) { + for (auto& observer : calendar_view_->calendar_model_->observers_) + observer.OnEventsFetched(CalendarModel::kSuccess, start_of_month, + nullptr); + } + private: std::unique_ptr<views::Widget> widget_; // Owned by `widget_`. @@ -1499,6 +1529,199 @@ EXPECT_EQ(1.0f, header()->layer()->opacity()); } +// Tests that the loading bar becomes visible when any of the on screen months +// has not finished fetching and becomes invisible once all months on screen +// have finished fetching events. +TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForOneMonthOnScreen) { + base::Time date; + ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); + + // Sets the timezone to "America/Los_Angeles". + ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID( + u"America/Los_Angeles"); + + // Tests when the `CalendarView` size is small to hold only one month on + // screen. + UpdateDisplay("800x200"); + CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + + EXPECT_EQ(1U, on_screen_month().size()); + + // Sets the fetching status of current month to be kFetching, and tests the + // loading bar is visible. + base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); + base::Time current_date = + calendar_view()->calendar_view_controller()->currently_shown_date(); + base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( + current_date + calendar_utils::GetTimeDifference(current_date)); + EXPECT_EQ(start_of_month, start_of_current_month); + + InsertPendingFetches(start_of_current_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status to be kSuccess, and tests the loading bar is + // invisible. + DeletePendingFetches(start_of_current_month); + // A fake `empty_event_map` just for test. + CalendarModel::SingleMonthEventMap empty_event_map; + event_months().emplace(start_of_month, empty_event_map); + NotifyObservers(start_of_current_month); + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); +} + +TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForTwoMonthsOnScreen) { + base::Time date; + ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); + + // Sets the timezone to "America/Los_Angeles". + ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID( + u"America/Los_Angeles"); + + // Tests when the `CalendarView` has two months on screen. + UpdateDisplay("800x600"); + CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + + EXPECT_EQ(2U, on_screen_month().size()); + + // Sets the fetching status of both months to be kFetching, and tests the + // loading bar is visible. + base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); + base::Time current_date = + calendar_view()->calendar_view_controller()->currently_shown_date(); + base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( + current_date + calendar_utils::GetTimeDifference(current_date)); + base::Time start_of_next_month = + calendar_utils::GetStartOfNextMonthUTC(start_of_current_month); + EXPECT_EQ(start_of_month, start_of_current_month); + + InsertPendingFetches(start_of_current_month); + InsertPendingFetches(start_of_next_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status of one month to be kSuccess, and tests the loading + // bar is visible. + DeletePendingFetches(start_of_current_month); + // A fake `empty_event_map` just for test. + CalendarModel::SingleMonthEventMap empty_event_map; + event_months().emplace(start_of_current_month, empty_event_map); + NotifyObservers(start_of_current_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status for both months to be kSuccess, and tests the + // loading bar is invisible. + DeletePendingFetches(start_of_next_month); + event_months().emplace(start_of_next_month, empty_event_map); + NotifyObservers(start_of_next_month); + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); +} + +TEST_F(CalendarViewAnimationTest, LoadingBarVisibilityForThreeMonthsOnScreen) { + base::Time date; + ASSERT_TRUE(base::Time::FromString("04 May 2022 15:00 GMT", &date)); + + // Sets the timezone to "America/Los_Angeles". + ash::system::TimezoneSettings::GetInstance()->SetTimezoneFromID( + u"America/Los_Angeles"); + + // Tests when the `CalendarView` has three months on screen. + UpdateDisplay("800x1000"); + CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + + EXPECT_EQ(3U, on_screen_month().size()); + + // Sets the fetching status of all months to be kFetching, and tests the + // loading bar is visible. + base::Time start_of_month = calendar_utils::GetStartOfMonthUTC(date); + base::Time current_date = + calendar_view()->calendar_view_controller()->currently_shown_date(); + base::Time start_of_current_month = calendar_utils::GetStartOfMonthUTC( + current_date + calendar_utils::GetTimeDifference(current_date)); + base::Time start_of_next_month = + calendar_utils::GetStartOfNextMonthUTC(start_of_current_month); + base::Time start_of_next_next_month = + calendar_utils::GetStartOfNextMonthUTC(start_of_next_month); + EXPECT_EQ(start_of_month, start_of_current_month); + + InsertPendingFetches(start_of_current_month); + InsertPendingFetches(start_of_next_month); + InsertPendingFetches(start_of_next_next_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status of one month to be kSuccess, and tests the loading + // bar is visible. + DeletePendingFetches(start_of_current_month); + // A fake `empty_event_map` just for test. + CalendarModel::SingleMonthEventMap empty_event_map; + event_months().emplace(start_of_current_month, empty_event_map); + NotifyObservers(start_of_current_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status for two months to be kSuccess, and tests the + // loading bar is visible. + DeletePendingFetches(start_of_next_month); + event_months().emplace(start_of_next_month, empty_event_map); + NotifyObservers(start_of_next_month); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Sets the fetching status for all months to be kSuccess, and tests the + // loading bar is invisible. + DeletePendingFetches(start_of_next_next_month); + event_months().emplace(start_of_next_next_month, empty_event_map); + NotifyObservers(start_of_next_next_month); + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); +} + +// Tests the loading bar visibility for different user sessions. +TEST_F(CalendarViewAnimationTest, + LoadingBarVisibilityForDifferentUserSessions) { + base::Time date; + // Create a monthview based on May, 9th 2022. + ASSERT_TRUE(base::Time::FromString("9 May 2022 10:00 GMT", &date)); + + // Tests when the screen is locked, the loading bar is invisible. + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOCKED); + + CreateCalendarView(); + // Advances the time to allow `on_screen_month_` to initialize. + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Tests when the user starts the login process, the loading bar is invisible. + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOGIN_PRIMARY); + + CreateCalendarView(); + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + EXPECT_FALSE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); + + // Tests when the user is logged in, the loading bar is visible. + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::ACTIVE); + + CreateCalendarView(); + task_environment()->FastForwardBy( + calendar_test_utils::kAnimationSettleDownDuration); + UpdateMonth(date); + EXPECT_TRUE(calendar_view()->children()[kLoadingBarIndex]->GetVisible()); +} + // Tests that the EventListView does not crash if shown during the initial open. TEST_F(CalendarViewAnimationTest, QuickShowEventListInitialOpen) { ui::ScopedAnimationDurationScaleMode test_duration_mode(
diff --git a/ash/system/tray/tray_detailed_view.cc b/ash/system/tray/tray_detailed_view.cc index a44ddbb..c1aa5bb 100644 --- a/ash/system/tray/tray_detailed_view.cc +++ b/ash/system/tray/tray_detailed_view.cc
@@ -4,11 +4,14 @@ #include "ash/system/tray/tray_detailed_view.h" +#include <cstring> +#include <string> #include <utility> #include "ash/public/cpp/ash_view_ids.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" +#include "ash/system/time/calendar_view.h" #include "ash/system/tray/detailed_view_delegate.h" #include "ash/system/tray/hover_highlight_view.h" #include "ash/system/tray/system_menu_button.h" @@ -25,6 +28,7 @@ #include "ui/compositor/paint_recorder.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" +#include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/skia_paint_util.h" @@ -283,6 +287,11 @@ HandleViewClicked(sender); } +void TrayDetailedView::OverrideProgressBarAccessibleName( + const std::u16string& name) { + progress_bar_accessible_name_ = name; +} + void TrayDetailedView::CreateTitleRow(int string_id) { DCHECK(!tri_view_); @@ -294,8 +303,14 @@ AddChildViewAt(tri_view_, 0); - // Do not add a separator below the calendar title. - if (string_id != IDS_ASH_CALENDAR_TITLE) { + // If this view doesn't have a separator, adds an empty view as a placeholder + // so that the views below won't move up when the `progress_bar_` becomes + // invisible. + if (!has_separator_) { + auto buffer_view = std::make_unique<views::View>(); + buffer_view->SetPreferredSize(gfx::Size(1, kTitleRowProgressBarHeight)); + AddChildViewAt(std::move(buffer_view), kTitleRowSeparatorIndex); + } else { AddChildViewAt(delegate_->CreateTitleSeparator(), kTitleRowSeparatorIndex); } @@ -394,8 +409,8 @@ std::make_unique<views::ProgressBar>(kTitleRowProgressBarHeight), kTitleRowSeparatorIndex + 1); progress_bar_->GetViewAccessibility().OverrideName( - l10n_util::GetStringUTF16( - IDS_ASH_STATUS_TRAY_NETWORK_PROGRESS_ACCESSIBLE_NAME)); + progress_bar_accessible_name_.value_or(l10n_util::GetStringUTF16( + IDS_ASH_STATUS_TRAY_PROGRESS_BAR_ACCESSIBLE_NAME))); progress_bar_->SetVisible(false); progress_bar_->SetForegroundColor( AshColorProvider::Get()->GetContentLayerColor( @@ -447,6 +462,10 @@ delegate_->CloseBubble(); } +void TrayDetailedView::IgnoreSeparator() { + has_separator_ = false; +} + void TrayDetailedView::Layout() { views::View::Layout(); if (scroller_ && !scroller_->is_bounded())
diff --git a/ash/system/tray/tray_detailed_view.h b/ash/system/tray/tray_detailed_view.h index b58eb924..d7fc47b 100644 --- a/ash/system/tray/tray_detailed_view.h +++ b/ash/system/tray/tray_detailed_view.h
@@ -47,6 +47,9 @@ // Don't override this --- override HandleViewClicked. void OnViewClicked(views::View* sender) final; + // Setter for `progress_bar_` accessibility label. + void OverrideProgressBarAccessibleName(const std::u16string& name); + protected: // views::View: void Layout() override; @@ -126,6 +129,11 @@ views::ScrollView* scroller() const { return scroller_; } views::View* scroll_content() const { return scroll_content_; } + // Gets called in the constructor of the `CalendarView`, or any other views in + // the future that don't have a separator to modify the value of + // `has_separator` to false. + void IgnoreSeparator(); + private: friend class TrayDetailedViewTest; @@ -155,6 +163,13 @@ views::Label* sub_header_label_ = nullptr; views::ImageView* sub_header_image_view_ = nullptr; const gfx::VectorIcon* sub_header_icon_ = nullptr; + + // Gets modified to false in the constructor of the view if it doesn't have a + // separator. + bool has_separator_ = true; + + // The accessible name for the `progress_bar_`. + absl::optional<std::u16string> progress_bar_accessible_name_; }; } // namespace ash
diff --git a/ash/webui/diagnostics_ui/resources/data_point.html b/ash/webui/diagnostics_ui/resources/data_point.html index 419624f..4cc06cb 100644 --- a/ash/webui/diagnostics_ui/resources/data_point.html +++ b/ash/webui/diagnostics_ui/resources/data_point.html
@@ -1,7 +1,5 @@ <style include="diagnostics-shared diagnostics-fonts"> :host([orientation=horizontal]) { - --diagnostics-data-point-subtitle-color: var(--cros-text-color-primary); - --diagnostics-data-point-title-color: var(--cros-text-color-secondary); line-height: 18px; } @@ -23,7 +21,7 @@ } .header { - color: var(--diagnostics-data-point-title-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight); @@ -48,7 +46,7 @@ } .value { - color: var(--diagnostics-data-point-subtitle-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/diagnostics_card.html b/ash/webui/diagnostics_ui/resources/diagnostics_card.html index 8d80785..5fb9b6e 100644 --- a/ash/webui/diagnostics_ui/resources/diagnostics_card.html +++ b/ash/webui/diagnostics_ui/resources/diagnostics_card.html
@@ -16,7 +16,7 @@ } ::slotted([slot=title]) { - color: var(--diagnostics-card-title-text-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 14px; font-weight: var(--diagnostics-medium-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/diagnostics_card_frame.html b/ash/webui/diagnostics_ui/resources/diagnostics_card_frame.html index 9200bdb..600c56e 100644 --- a/ash/webui/diagnostics_ui/resources/diagnostics_card_frame.html +++ b/ash/webui/diagnostics_ui/resources/diagnostics_card_frame.html
@@ -5,7 +5,7 @@ } ::slotted([slot=title]) { - color: var(--diagnostics-card-title-text-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 14px; font-weight: var(--diagnostics-medium-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/diagnostics_fonts_css.html b/ash/webui/diagnostics_ui/resources/diagnostics_fonts_css.html index dee4f1b..9bef3e18 100644 --- a/ash/webui/diagnostics_ui/resources/diagnostics_fonts_css.html +++ b/ash/webui/diagnostics_ui/resources/diagnostics_fonts_css.html
@@ -6,20 +6,6 @@ --diagnostics-regular-font-weight: 400; --diagnostics-medium-font-weight: 500; - - --diagnostics-header-text-color: var(--cros-text-color-primary); - --diagnostics-card-title-text-color: var(--cros-text-color-secondary); - --diagnostics-overview-text-color: var(--cros-text-color-secondary); - --diagnostics-data-point-title-color: var(--cros-text-color-primary); - --diagnostics-data-point-subtitle-color: var(--cros-text-color-secondary); - --diagnostics-routine-additional-message-color: var(--cros-text-color-primary); - --diagnostics-routine-name-color: var(--cros-text-color-primary); - --diagnostics-chart-legend-color: var(--cros-text-color-primary); - --diagnostics-chart-title-color: var(--cros-text-color-secondary); - --diagnostics-test-status-text-color: var(--cros-text-color-secondary); - --diagnostics-caution-banner-text-color: var(--cros-text-color-primary); - --diagnostics-link-text-color: var(--cros-link-color); - --diagnostics-settings-link-text-color: var(--cros-text-color-secondary); } </style> </template>
diff --git a/ash/webui/diagnostics_ui/resources/diagnostics_shared_css.html b/ash/webui/diagnostics_ui/resources/diagnostics_shared_css.html index cd499d2e..58a23b8 100644 --- a/ash/webui/diagnostics_ui/resources/diagnostics_shared_css.html +++ b/ash/webui/diagnostics_ui/resources/diagnostics_shared_css.html
@@ -91,7 +91,7 @@ .diagnostics-chip { background-color: var(--diagnostics-chip-bg-color); border-radius: 16px; - color: var(--diagnostics-overview-text-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight); @@ -143,7 +143,7 @@ } .diagnostics-caution-banner-font { - color: var(--diagnostics-caution-banner-text-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 14px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/input_card.html b/ash/webui/diagnostics_ui/resources/input_card.html index 6abe741..c391ca0 100644 --- a/ash/webui/diagnostics_ui/resources/input_card.html +++ b/ash/webui/diagnostics_ui/resources/input_card.html
@@ -22,11 +22,11 @@ } .device-name { - color: var(--diagnostics-data-point-title-color); + color: var(--cros-text-color-primary); } .device-description { - color: var(--diagnostics-data-point-subtitle-color); + color: var(--cros-text-color-secondary); } </style> <diagnostics-card-frame>
diff --git a/ash/webui/diagnostics_ui/resources/ip_config_info_drawer.html b/ash/webui/diagnostics_ui/resources/ip_config_info_drawer.html index d14882a..2a0cede 100644 --- a/ash/webui/diagnostics_ui/resources/ip_config_info_drawer.html +++ b/ash/webui/diagnostics_ui/resources/ip_config_info_drawer.html
@@ -4,7 +4,7 @@ } #drawerTitle { - color: var(--diagnostics-header-text-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/network_list.html b/ash/webui/diagnostics_ui/resources/network_list.html index 0245395..cb1f55b 100644 --- a/ash/webui/diagnostics_ui/resources/network_list.html +++ b/ash/webui/diagnostics_ui/resources/network_list.html
@@ -22,7 +22,7 @@ } #settingsLink { - color: var(--diagnostics-settings-link-text-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 14px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/network_troubleshooting.html b/ash/webui/diagnostics_ui/resources/network_troubleshooting.html index 8c23923..4bb155f 100644 --- a/ash/webui/diagnostics_ui/resources/network_troubleshooting.html +++ b/ash/webui/diagnostics_ui/resources/network_troubleshooting.html
@@ -1,6 +1,6 @@ <style include="diagnostics-shared"> #troubleshootingText { - color: var(--diagnostics-header-text-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight); @@ -18,7 +18,7 @@ } #troubleshootingLinkText { - color: var(--diagnostics-link-text-color); + color: var(--cros-link-color); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/percent_bar_chart.html b/ash/webui/diagnostics_ui/resources/percent_bar_chart.html index 8785bfe..44604f6 100644 --- a/ash/webui/diagnostics_ui/resources/percent_bar_chart.html +++ b/ash/webui/diagnostics_ui/resources/percent_bar_chart.html
@@ -1,6 +1,6 @@ <style include="diagnostics-shared diagnostics-fonts"> #chartName { - color: var(--diagnostics-chart-title-color); + color: var(--cros-text-color-secondary); display: inline-block; font-family: var(--diagnostics-roboto-font-family); font-size: 13px;
diff --git a/ash/webui/diagnostics_ui/resources/realtime_cpu_chart.html b/ash/webui/diagnostics_ui/resources/realtime_cpu_chart.html index f2548df..db05b6f 100644 --- a/ash/webui/diagnostics_ui/resources/realtime_cpu_chart.html +++ b/ash/webui/diagnostics_ui/resources/realtime_cpu_chart.html
@@ -53,7 +53,7 @@ } #chart-legend { - color: var(--diagnostics-chart-legend-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 12px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/routine_result_entry.html b/ash/webui/diagnostics_ui/resources/routine_result_entry.html index 2d28b119..bb40d18 100644 --- a/ash/webui/diagnostics_ui/resources/routine_result_entry.html +++ b/ash/webui/diagnostics_ui/resources/routine_result_entry.html
@@ -55,7 +55,7 @@ #routine { align-items: center; - color: var(--diagnostics-routine-name-color); + color: var(--cros-text-color-primary); display: inline-flex; font-family: var(--diagnostics-roboto-font-family); font-size: 13px;
diff --git a/ash/webui/diagnostics_ui/resources/routine_section.html b/ash/webui/diagnostics_ui/resources/routine_section.html index e2e85ce7..079d554 100644 --- a/ash/webui/diagnostics_ui/resources/routine_section.html +++ b/ash/webui/diagnostics_ui/resources/routine_section.html
@@ -1,6 +1,6 @@ <style include="diagnostics-shared"> #additionalMessage { - color: var(--diagnostics-routine-additional-message-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight); @@ -55,7 +55,7 @@ } #testStatusText { - color: var(--diagnostics-test-status-text-color); + color: var(--cros-text-color-secondary); font-family: var(--diagnostics-roboto-font-family); font-size: 13px; font-weight: var(--diagnostics-regular-font-weight);
diff --git a/ash/webui/diagnostics_ui/resources/system_page.html b/ash/webui/diagnostics_ui/resources/system_page.html index 6cb7e658..d2dda60 100644 --- a/ash/webui/diagnostics_ui/resources/system_page.html +++ b/ash/webui/diagnostics_ui/resources/system_page.html
@@ -40,7 +40,7 @@ #header { align-self: flex-start; - color: var(--diagnostics-header-text-color); + color: var(--cros-text-color-primary); font-family: var(--diagnostics-roboto-font-family); font-size: 16px; font-weight: var(--diagnostics-medium-font-weight);
diff --git a/ash/webui/personalization_app/resources/trusted/ambient/ambient_subpage_element.html b/ash/webui/personalization_app/resources/trusted/ambient/ambient_subpage_element.html index 4d276495..97252c0 100644 --- a/ash/webui/personalization_app/resources/trusted/ambient/ambient_subpage_element.html +++ b/ash/webui/personalization_app/resources/trusted/ambient/ambient_subpage_element.html
@@ -4,6 +4,7 @@ } #container { height: 100%; + margin-block-end: 48px; } #mainSettings { display: grid;
diff --git a/ash/webui/personalization_app/resources/trusted/personalization_main_element.html b/ash/webui/personalization_app/resources/trusted/personalization_main_element.html index 6616ae2..9313c15 100644 --- a/ash/webui/personalization_app/resources/trusted/personalization_main_element.html +++ b/ash/webui/personalization_app/resources/trusted/personalization_main_element.html
@@ -7,7 +7,7 @@ '. . rbg-keyboard . .' '. . . . .'; grid-template-columns: 1fr minmax(24px, 72px) minmax(480px, 960px) minmax(24px, 72px) 1fr; - grid-template-rows: 108px 1fr auto 12px; + grid-template-rows: 108px 1fr auto 32px; height: 100%; position: relative; width: 100%;
diff --git a/ash/webui/sample_system_web_app_ui/untrusted_sample_system_web_app_ui.cc b/ash/webui/sample_system_web_app_ui/untrusted_sample_system_web_app_ui.cc index 78c03bc..09d71958 100644 --- a/ash/webui/sample_system_web_app_ui/untrusted_sample_system_web_app_ui.cc +++ b/ash/webui/sample_system_web_app_ui/untrusted_sample_system_web_app_ui.cc
@@ -58,7 +58,7 @@ mojo::PendingReceiver<mojom::sample_swa::ParentTrustedPage> parent_trusted_page) { // Find the parent frame's controller. - auto* chrome_frame = web_ui()->GetWebContents()->GetMainFrame(); + auto* chrome_frame = web_ui()->GetWebContents()->GetPrimaryMainFrame(); if (!chrome_frame) return;
diff --git a/ash/wm/collision_detection/collision_detection_utils.cc b/ash/wm/collision_detection/collision_detection_utils.cc index 1ba5305..5867689 100644 --- a/ash/wm/collision_detection/collision_detection_utils.cc +++ b/ash/wm/collision_detection/collision_detection_utils.cc
@@ -4,9 +4,11 @@ #include "ash/wm/collision_detection/collision_detection_utils.h" +#include "ash/app_list/app_list_controller_impl.h" #include "ash/capture_mode/capture_mode_camera_controller.h" #include "ash/capture_mode/capture_mode_controller.h" #include "ash/capture_mode/capture_mode_session.h" +#include "ash/constants/ash_features.h" #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/public/cpp/shelf_types.h" #include "ash/public/cpp/shell_window_ids.h" @@ -88,9 +90,10 @@ auto* shelf = Shelf::ForWindow(root_window); auto* shelf_window = shelf->GetWindow(); if (shelf->IsVisible() && - !ShouldIgnoreWindowForCollision(shelf_window, priority)) + !ShouldIgnoreWindowForCollision(shelf_window, priority)) { rects.push_back(ComputeCollisionRectFromBounds( shelf_window->GetTargetBounds(), shelf_window->parent())); + } // Explicitly add popup notifications as they are not in the notification // tray. @@ -100,9 +103,10 @@ if (window->IsVisible() && !window->GetTargetBounds().IsEmpty() && window->GetName() == AshMessagePopupCollection::kMessagePopupWidgetName && - !ShouldIgnoreWindowForCollision(window, priority)) + !ShouldIgnoreWindowForCollision(window, priority)) { rects.push_back(ComputeCollisionRectFromBounds( window->GetTargetBounds(), window->parent())); + } } // The hotseat doesn't span the whole width of the display, but to allow @@ -194,6 +198,18 @@ camera_preview_window->parent())); } + // Avoid clamshell-mode launcher bubble. + auto* app_list_controller = Shell::Get()->app_list_controller(); + if (features::IsProductivityLauncherEnabled() && + !Shell::Get()->IsInTabletMode() && + app_list_controller->GetTargetVisibility(display.id())) { + aura::Window* window = app_list_controller->GetWindow(); + if (window) { + rects.push_back(ComputeCollisionRectFromBounds(window->GetTargetBounds(), + window->parent())); + } + } + return rects; }
diff --git a/ash/wm/collision_detection/collision_detection_utils_unittest.cc b/ash/wm/collision_detection/collision_detection_utils_unittest.cc index ac55165..a7879525f 100644 --- a/ash/wm/collision_detection/collision_detection_utils_unittest.cc +++ b/ash/wm/collision_detection/collision_detection_utils_unittest.cc
@@ -6,8 +6,10 @@ #include <memory> +#include "ash/constants/ash_features.h" #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/keyboard/ui/test/keyboard_test_util.h" +#include "ash/public/cpp/app_list/app_list_controller.h" #include "ash/public/cpp/keyboard/keyboard_switches.h" #include "ash/root_window_controller.h" #include "ash/shelf/shelf.h" @@ -20,6 +22,7 @@ #include "ash/wm/window_state.h" #include "ash/wm/wm_event.h" #include "base/callback_helpers.h" +#include "base/test/scoped_feature_list.h" #include "ui/aura/window.h" #include "ui/display/scoped_display_for_new_windows.h" #include "ui/gfx/geometry/insets.h" @@ -99,6 +102,29 @@ EXPECT_TRUE(area.Contains(moved_bounds)); } +TEST_F(CollisionDetectionUtilsTest, AvoidObstaclesAvoidsClamshellLauncher) { + base::test::ScopedFeatureList feature_list(features::kProductivityLauncher); + + UpdateDisplay("1000x900"); + AppListController* app_list_controller = AppListController::Get(); + app_list_controller->ShowAppList(); + + display::Display display = GetPrimaryDisplay(); + gfx::Rect movement_area = CollisionDetectionUtils::GetMovementArea(display); + gfx::Rect bubble_bounds = + app_list_controller->GetWindow()->GetBoundsInScreen(); + // Start with bounds that overlap the bubble window. + gfx::Rect bounds = gfx::Rect(bubble_bounds.x(), bubble_bounds.y(), 100, 100); + gfx::Rect moved_bounds = CollisionDetectionUtils::GetRestingPosition( + display, bounds, + CollisionDetectionUtils::RelativePriority::kPictureInPicture); + + // Expect that the returned bounds don't intersect the bubble window but also + // don't leave the PIP movement area. + EXPECT_FALSE(moved_bounds.Intersects(bubble_bounds)); + EXPECT_TRUE(movement_area.Contains(moved_bounds)); +} + class CollisionDetectionUtilsDisplayTest : public AshTestBase, public ::testing::WithParamInterface<
diff --git a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc index 2c62b4e..80f0299 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc
@@ -4,9 +4,9 @@ #include "ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h"
diff --git a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl.cc b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl.cc index 41c1434..07669e6 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl.cc
@@ -4,9 +4,9 @@ #include "ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/public/cpp/back_gesture_contextual_nudge_delegate.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.h"
diff --git a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl_unittest.cc b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl_unittest.cc index 922d8960..0a36973c 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl_unittest.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge_controller_impl_unittest.cc
@@ -6,8 +6,8 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/test_shell_delegate.h"
diff --git a/ash/wm/gestures/back_gesture/back_gesture_event_handler.cc b/ash/wm/gestures/back_gesture/back_gesture_event_handler.cc index f523535..94a267f 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_event_handler.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_event_handler.cc
@@ -7,11 +7,11 @@ #include "ash/app_list/app_list_controller_impl.h" #include "ash/constants/app_types.h" #include "ash/constants/ash_features.h" +#include "ash/controls/contextual_tooltip.h" #include "ash/display/screen_orientation_controller.h" #include "ash/keyboard/keyboard_util.h" #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/session/session_controller_impl.h" -#include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/system/model/system_tray_model.h"
diff --git a/ash/wm/workspace/workspace_layout_manager.cc b/ash/wm/workspace/workspace_layout_manager.cc index e5506ea..fa47f15 100644 --- a/ash/wm/workspace/workspace_layout_manager.cc +++ b/ash/wm/workspace/workspace_layout_manager.cc
@@ -9,6 +9,8 @@ #include "ash/accessibility/accessibility_controller_impl.h" #include "ash/accessibility/autoclick/autoclick_controller.h" +#include "ash/app_list/app_list_controller_impl.h" +#include "ash/constants/ash_features.h" #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/public/cpp/shell_window_ids.h" @@ -117,9 +119,14 @@ shelf_container_ = window->GetRootWindow()->GetChildById(kShellWindowId_ShelfContainer); root_window_controller_->shelf()->AddObserver(this); + Shell::Get()->app_list_controller()->AddObserver(this); } WorkspaceLayoutManager::~WorkspaceLayoutManager() { + // WorkspaceLayoutManagers for the primary display are destroyed after + // AppListControllerImpl. Their observers are removed in OnShellDestroying(). + if (Shell::Get()->app_list_controller()) + Shell::Get()->app_list_controller()->RemoveObserver(this); root_window_controller_->shelf()->RemoveObserver(this); if (root_window_) root_window_->RemoveObserver(this); @@ -466,8 +473,13 @@ UpdateAlwaysOnTop(is_pinned ? pinned_window : nullptr); } +void WorkspaceLayoutManager::OnShellDestroying() { + Shell::Get()->app_list_controller()->RemoveObserver(this); +} + ////////////////////////////////////////////////////////////////////////////// // WorkspaceLayoutManager, ShelfObserver implementation: + void WorkspaceLayoutManager::OnAutoHideStateChanged( ShelfAutoHideState new_state) { NotifySystemUiAreaChanged(); @@ -479,6 +491,22 @@ } ////////////////////////////////////////////////////////////////////////////// +// WorkspaceLayoutManager, AppListControllerObserver implementation: + +void WorkspaceLayoutManager::OnAppListVisibilityChanged(bool shown, + int64_t display_id) { + if (display::Screen::GetScreen()->GetDisplayNearestWindow(window_).id() != + display_id) { + return; + } + if (features::IsProductivityLauncherEnabled() && + !Shell::Get()->IsInTabletMode()) { + // Adjust PIP window if needed. + NotifySystemUiAreaChanged(); + } +} + +////////////////////////////////////////////////////////////////////////////// // WorkspaceLayoutManager, private: void WorkspaceLayoutManager::AdjustAllWindowsBoundsForWorkAreaChange(
diff --git a/ash/wm/workspace/workspace_layout_manager.h b/ash/wm/workspace/workspace_layout_manager.h index 3e1c6a1..50ec4ffc 100644 --- a/ash/wm/workspace/workspace_layout_manager.h +++ b/ash/wm/workspace/workspace_layout_manager.h
@@ -9,6 +9,7 @@ #include <memory> #include "ash/ash_export.h" +#include "ash/public/cpp/app_list/app_list_controller_observer.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/shelf/shelf_observer.h" #include "ash/shell_observer.h" @@ -33,7 +34,8 @@ public display::DisplayObserver, public ShellObserver, public WindowStateObserver, - public ShelfObserver { + public ShelfObserver, + public AppListControllerObserver { public: // |window| is the container for this layout manager. explicit WorkspaceLayoutManager(aura::Window* window); @@ -97,12 +99,16 @@ void OnFullscreenStateChanged(bool is_fullscreen, aura::Window* container) override; void OnPinnedStateChanged(aura::Window* pinned_window) override; + void OnShellDestroying() override; // ShelfObserver: void OnAutoHideStateChanged(ShelfAutoHideState new_state) override; void OnHotseatStateChanged(HotseatState old_state, HotseatState new_state) override; + // AppListControllerObserver: + void OnAppListVisibilityChanged(bool shown, int64_t display_id) override; + private: friend class WorkspaceControllerTestApi; typedef std::set<aura::Window*> WindowSet;
diff --git a/ash/wm/workspace/workspace_layout_manager_unittest.cc b/ash/wm/workspace/workspace_layout_manager_unittest.cc index 197970c..d68216b 100644 --- a/ash/wm/workspace/workspace_layout_manager_unittest.cc +++ b/ash/wm/workspace/workspace_layout_manager_unittest.cc
@@ -17,6 +17,7 @@ #include "ash/keyboard/ui/keyboard_ui_controller.h" #include "ash/keyboard/ui/keyboard_util.h" #include "ash/keyboard/ui/test/keyboard_test_util.h" +#include "ash/public/cpp/app_list/app_list_controller.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/keyboard/keyboard_switches.h" #include "ash/public/cpp/shelf_config.h" @@ -54,6 +55,7 @@ #include "ash/wm/workspace_controller_test_api.h" #include "base/callback_helpers.h" #include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/focus_client.h" @@ -2007,6 +2009,22 @@ EXPECT_GE(test_state()->num_system_ui_area_changes(), 1); } +// Expect that showing the clamshell bubble launcher triggers as system UI area +// change event. +TEST_F(WorkspaceLayoutManagerSystemUiAreaTest, + SystemUiAreaChangeOnClamshellLauncherVisibilityChange) { + base::test::ScopedFeatureList feature_list(features::kProductivityLauncher); + ASSERT_FALSE(Shell::Get()->IsInTabletMode()); + + AppListController* app_list_controller = AppListController::Get(); + app_list_controller->ShowAppList(); + EXPECT_GE(test_state()->num_system_ui_area_changes(), 1); + test_state()->reset_num_system_ui_area_changes(); + + app_list_controller->DismissAppList(); + EXPECT_GE(test_state()->num_system_ui_area_changes(), 1); +} + // Expect that showing and hiding the keyboard triggers a system ui area // change event. TEST_F(WorkspaceLayoutManagerSystemUiAreaTest,
diff --git a/base/files/file_proxy.cc b/base/files/file_proxy.cc index 432761f..647fb5d 100644 --- a/base/files/file_proxy.cc +++ b/base/files/file_proxy.cc
@@ -95,7 +95,7 @@ CreateOrOpenHelper(const CreateOrOpenHelper&) = delete; CreateOrOpenHelper& operator=(const CreateOrOpenHelper&) = delete; - void RunWork(const FilePath& file_path, int file_flags) { + void RunWork(const FilePath& file_path, uint32_t file_flags) { file_.Initialize(file_path, file_flags); error_ = file_.IsValid() ? File::FILE_OK : file_.error_details(); } @@ -175,7 +175,7 @@ public: ReadHelper(FileProxy* proxy, File file, int bytes_to_read) : FileHelper(proxy, std::move(file)), - buffer_(new char[bytes_to_read]), + buffer_(new char[static_cast<size_t>(bytes_to_read)]), bytes_to_read_(bytes_to_read) {} ReadHelper(const ReadHelper&) = delete; ReadHelper& operator=(const ReadHelper&) = delete; @@ -204,9 +204,9 @@ const char* buffer, int bytes_to_write) : FileHelper(proxy, std::move(file)), - buffer_(new char[bytes_to_write]), + buffer_(new char[static_cast<size_t>(bytes_to_write)]), bytes_to_write_(bytes_to_write) { - memcpy(buffer_.get(), buffer, bytes_to_write); + memcpy(buffer_.get(), buffer, static_cast<size_t>(bytes_to_write)); } WriteHelper(const WriteHelper&) = delete; WriteHelper& operator=(const WriteHelper&) = delete; @@ -239,7 +239,7 @@ } bool FileProxy::CreateOrOpen(const FilePath& file_path, - int file_flags, + uint32_t file_flags, StatusCallback callback) { DCHECK(!file_.IsValid()); CreateOrOpenHelper* helper = new CreateOrOpenHelper(this, File());
diff --git a/base/files/file_proxy.h b/base/files/file_proxy.h index ae92a4b..14b0791a 100644 --- a/base/files/file_proxy.h +++ b/base/files/file_proxy.h
@@ -59,7 +59,7 @@ // // This returns false if task posting to |task_runner| has failed. bool CreateOrOpen(const FilePath& file_path, - int file_flags, + uint32_t file_flags, StatusCallback callback); // Creates a temporary file for writing. The path and an open file are
diff --git a/base/files/file_util.cc b/base/files/file_util.cc index a186a6c..b3d4ffc5 100644 --- a/base/files/file_util.cc +++ b/base/files/file_util.cc
@@ -101,7 +101,8 @@ std::vector<char> buffer(kBufferSize); for (;;) { - int bytes_read = infile.ReadAtCurrentPos(buffer.data(), buffer.size()); + int bytes_read = + infile.ReadAtCurrentPos(buffer.data(), static_cast<int>(buffer.size())); if (bytes_read < 0) { return false; } @@ -112,7 +113,8 @@ int bytes_written_per_read = 0; do { int bytes_written_partial = outfile.WriteAtCurrentPos( - &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read); + &buffer[static_cast<size_t>(bytes_written_per_read)], + bytes_read - bytes_written_per_read); if (bytes_written_partial < 0) { return false; } @@ -228,8 +230,8 @@ // Many files have incorrect size (proc files etc). Hence, the file is read // sequentially as opposed to a one-shot read, using file size as a hint for // chunk size if available. - constexpr int64_t kDefaultChunkSize = 1 << 16; - int64_t chunk_size = kDefaultChunkSize - 1; + constexpr size_t kDefaultChunkSize = 1 << 16; + size_t chunk_size = kDefaultChunkSize - 1; ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); #if BUILDFLAG(IS_WIN) BY_HANDLE_FILE_INFORMATION file_info = {}; @@ -237,25 +239,25 @@ reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream))), &file_info)) { LARGE_INTEGER size; - size.HighPart = file_info.nFileSizeHigh; + size.HighPart = static_cast<LONG>(file_info.nFileSizeHigh); size.LowPart = file_info.nFileSizeLow; if (size.QuadPart > 0) - chunk_size = size.QuadPart; + chunk_size = static_cast<size_t>(size.QuadPart); } #else // BUILDFLAG(IS_WIN) // In cases where the reported file size is 0, use a smaller chunk size to // minimize memory allocated and cost of string::resize() in case the read // size is small (i.e. proc files). If the file is larger than this, the read // loop will reset |chunk_size| to kDefaultChunkSize. - constexpr int64_t kSmallChunkSize = 4096; + constexpr size_t kSmallChunkSize = 4096; chunk_size = kSmallChunkSize - 1; stat_wrapper_t file_info = {}; if (!File::Fstat(fileno(stream), &file_info) && file_info.st_size > 0) - chunk_size = file_info.st_size; + chunk_size = static_cast<size_t>(file_info.st_size); #endif // BUILDFLAG(IS_WIN) // We need to attempt to read at EOF for feof flag to be set so here we // use |chunk_size| + 1. - chunk_size = std::min<uint64_t>(chunk_size, max_size) + 1; + chunk_size = std::min(chunk_size, max_size) + 1; size_t bytes_read_this_pass; size_t bytes_read_so_far = 0; bool read_status = true; @@ -345,7 +347,7 @@ bool TouchFile(const FilePath& path, const Time& last_accessed, const Time& last_modified) { - int flags = File::FLAG_OPEN | File::FLAG_WRITE_ATTRIBUTES; + uint32_t flags = File::FLAG_OPEN | File::FLAG_WRITE_ATTRIBUTES; #if BUILDFLAG(IS_WIN) // On Windows, FILE_FLAG_BACKUP_SEMANTICS is needed to open a directory.
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc index 6fdd30a..00ca6d5b7 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -88,7 +88,7 @@ (recursive || !info.IsDirectory())) { ::SetFileAttributes( current.value().c_str(), - info.find_data().dwFileAttributes & ~FILE_ATTRIBUTE_READONLY); + info.find_data().dwFileAttributes & ~DWORD{FILE_ATTRIBUTE_READONLY}); } DWORD this_result = ERROR_SUCCESS; @@ -151,7 +151,7 @@ return false; } if (attrs & FILE_ATTRIBUTE_READONLY) { - SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY); + SetFileAttributes(dest, attrs & ~DWORD{FILE_ATTRIBUTE_READONLY}); } return true; } @@ -274,7 +274,7 @@ // Clear the read-only bit if it is set. if ((attr & FILE_ATTRIBUTE_READONLY) && !::SetFileAttributes(path.value().c_str(), - attr & ~FILE_ATTRIBUTE_READONLY)) { + attr & ~DWORD{FILE_ATTRIBUTE_READONLY})) { // It's possible for |path| to be gone now under a race with other deleters. return ReturnLastErrorOrSuccessOnNotFound(); } @@ -812,7 +812,9 @@ ULARGE_INTEGER size; size.HighPart = attr.nFileSizeHigh; size.LowPart = attr.nFileSizeLow; - results->size = size.QuadPart; + // TODO(crbug.com/1333521): Change Info::size to uint64_t and eliminate this + // cast. + results->size = checked_cast<int64_t>(size.QuadPart); results->is_directory = (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; @@ -879,12 +881,15 @@ FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)); - if (!file.is_valid()) + if (!file.is_valid() || max_size < 0) return -1; DWORD read; - if (::ReadFile(file.get(), data, max_size, &read, NULL)) - return read; + if (::ReadFile(file.get(), data, static_cast<DWORD>(max_size), &read, NULL)) { + // TODO(crbug.com/1333521): Change to return some type with a uint64_t size + // and eliminate this cast. + return checked_cast<int>(read); + } return -1; } @@ -894,15 +899,16 @@ win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)); - if (!file.is_valid()) { - DPLOG(WARNING) << "CreateFile failed for path " << filename.value(); + if (!file.is_valid() || size < 0) { + DPLOG(WARNING) << "WriteFile failed for path " << filename.value(); return -1; } DWORD written; - BOOL result = ::WriteFile(file.get(), data, size, &written, NULL); + BOOL result = + ::WriteFile(file.get(), data, static_cast<DWORD>(size), &written, NULL); if (result && static_cast<int>(written) == size) - return written; + return static_cast<int>(written); if (!result) { // WriteFile failed. @@ -995,7 +1001,8 @@ bool SetNonBlocking(int fd) { unsigned long nonblocking = 1; - if (ioctlsocket(fd, FIONBIO, &nonblocking) == 0) + if (ioctlsocket(static_cast<SOCKET>(fd), static_cast<long>(FIONBIO), + &nonblocking) == 0) return true; return false; }
diff --git a/base/files/file_win.cc b/base/files/file_win.cc index b6f4385c..0c90a3a 100644 --- a/base/files/file_win.cc +++ b/base/files/file_win.cc
@@ -62,21 +62,25 @@ ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); DCHECK(IsValid()); DCHECK(!async_); - if (size < 0) + if (size < 0 || offset < 0) return -1; SCOPED_FILE_TRACE_WITH_SIZE("Read", size); - LARGE_INTEGER offset_li; - offset_li.QuadPart = offset; + ULARGE_INTEGER offset_li; + offset_li.QuadPart = static_cast<uint64_t>(offset); OVERLAPPED overlapped = {}; overlapped.Offset = offset_li.LowPart; overlapped.OffsetHigh = offset_li.HighPart; DWORD bytes_read; - if (::ReadFile(file_.get(), data, size, &bytes_read, &overlapped)) - return bytes_read; + if (::ReadFile(file_.get(), data, static_cast<DWORD>(size), &bytes_read, + &overlapped)) { + // TODO(crbug.com/1333521): Change to return some type with a uint64_t size + // and eliminate this cast. + return checked_cast<int>(bytes_read); + } if (ERROR_HANDLE_EOF == GetLastError()) return 0; @@ -93,8 +97,12 @@ SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPos", size); DWORD bytes_read; - if (::ReadFile(file_.get(), data, size, &bytes_read, NULL)) - return bytes_read; + if (::ReadFile(file_.get(), data, static_cast<DWORD>(size), &bytes_read, + NULL)) { + // TODO(crbug.com/1333521): Change to return some type with a uint64_t size + // and eliminate this cast. + return checked_cast<int>(bytes_read); + } if (ERROR_HANDLE_EOF == GetLastError()) return 0; @@ -115,19 +123,22 @@ ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); DCHECK(IsValid()); DCHECK(!async_); + if (size < 0 || offset < 0) + return -1; SCOPED_FILE_TRACE_WITH_SIZE("Write", size); - LARGE_INTEGER offset_li; - offset_li.QuadPart = offset; + ULARGE_INTEGER offset_li; + offset_li.QuadPart = static_cast<uint64_t>(offset); OVERLAPPED overlapped = {}; overlapped.Offset = offset_li.LowPart; overlapped.OffsetHigh = offset_li.HighPart; DWORD bytes_written; - if (::WriteFile(file_.get(), data, size, &bytes_written, &overlapped)) - return bytes_written; + if (::WriteFile(file_.get(), data, static_cast<DWORD>(size), &bytes_written, + &overlapped)) + return static_cast<int>(bytes_written); return -1; } @@ -142,8 +153,9 @@ SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPos", size); DWORD bytes_written; - if (::WriteFile(file_.get(), data, size, &bytes_written, NULL)) - return bytes_written; + if (::WriteFile(file_.get(), data, static_cast<DWORD>(size), &bytes_written, + NULL)) + return static_cast<int>(bytes_written); return -1; } @@ -218,10 +230,12 @@ if (!GetFileInformationByHandle(file_.get(), &file_info)) return false; - LARGE_INTEGER size; + ULARGE_INTEGER size; size.HighPart = file_info.nFileSizeHigh; size.LowPart = file_info.nFileSizeLow; - info->size = size.QuadPart; + // TODO(crbug.com/1333521): Change Info::size to uint64_t and eliminate this + // cast. + info->size = checked_cast<int64_t>(size.QuadPart); info->is_directory = (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; info->is_symbolic_link = false; // Windows doesn't have symbolic links. @@ -341,7 +355,8 @@ case ERROR_DISK_CORRUPT: // The disk structure is corrupted and unreadable. return FILE_ERROR_IO; default: - UmaHistogramSparse("PlatformFile.UnknownErrors.Windows", last_error); + UmaHistogramSparse("PlatformFile.UnknownErrors.Windows", + static_cast<int>(last_error)); // This function should only be called for errors. DCHECK_NE(static_cast<DWORD>(ERROR_SUCCESS), last_error); return FILE_ERROR_FAILED;
diff --git a/base/files/important_file_writer.cc b/base/files/important_file_writer.cc index c7b5037a..7018d4c5 100644 --- a/base/files/important_file_writer.cc +++ b/base/files/important_file_writer.cc
@@ -193,7 +193,8 @@ int bytes_written = 0; for (const char *scan = data.data(), *const end = scan + data.length(); scan < end; scan += bytes_written) { - const int write_amount = std::min(kMaxWriteAmount, end - scan); + const int write_amount = + static_cast<int>(std::min(kMaxWriteAmount, end - scan)); bytes_written = tmp_file.WriteAtCurrentPos(scan, write_amount); if (bytes_written != write_amount) { DPLOG(WARNING) << "Failed to write " << write_amount << " bytes to temp "
diff --git a/base/files/memory_mapped_file.cc b/base/files/memory_mapped_file.cc index f1fbe30..4a13ba84 100644 --- a/base/files/memory_mapped_file.cc +++ b/base/files/memory_mapped_file.cc
@@ -134,11 +134,13 @@ size_t* aligned_size, int32_t* offset) { // Sadly, on Windows, the mmap alignment is not just equal to the page size. - auto mask = SysInfo::VMAllocationGranularity() - 1; + uint64_t mask = SysInfo::VMAllocationGranularity() - 1; DCHECK(IsValueInRangeForNumericType<int32_t>(mask)); - *offset = start & mask; - *aligned_start = start & ~mask; - *aligned_size = (size + *offset + mask) & ~mask; + *offset = static_cast<int32_t>(static_cast<uint64_t>(start) & mask); + *aligned_start = static_cast<int64_t>(static_cast<uint64_t>(start) & ~mask); + // The DCHECK above means bit 31 is not set in `mask`, which in turn means + // *offset is positive. Therefore this cast is safe. + *aligned_size = (size + static_cast<size_t>(*offset) + mask) & ~mask; } #endif // !BUILDFLAG(IS_NACL)
diff --git a/base/files/memory_mapped_file_win.cc b/base/files/memory_mapped_file_win.cc index 3e3b0ea..1e2607b5 100644 --- a/base/files/memory_mapped_file_win.cc +++ b/base/files/memory_mapped_file_win.cc
@@ -12,6 +12,7 @@ #include "base/files/file_path.h" #include "base/logging.h" +#include "base/numerics/checked_math.h" #include "base/threading/scoped_blocking_call.h" #include "base/win/pe_image.h" @@ -61,7 +62,7 @@ if (!file_.IsValid()) return false; - int flags = 0; + DWORD flags = 0; ULARGE_INTEGER size = {}; switch (access) { case READ_ONLY: @@ -83,7 +84,7 @@ if (!file_mapping_.is_valid()) return false; - LARGE_INTEGER map_start = {}; + ULARGE_INTEGER map_start = {}; SIZE_T map_size = 0; int32_t data_offset = 0; @@ -105,17 +106,16 @@ size_t ignored = 0U; CalculateVMAlignedBoundaries(region.offset, region.size, &aligned_start, &ignored, &data_offset); - int64_t full_map_size = region.size + data_offset; + base::CheckedNumeric<SIZE_T> full_map_size = region.size; + full_map_size += data_offset; // Ensure that the casts below in the MapViewOfFile call are sane. - if (aligned_start < 0 || full_map_size < 0 || - !IsValueInRangeForNumericType<SIZE_T>( - static_cast<uint64_t>(full_map_size))) { + if (aligned_start < 0 || !full_map_size.IsValid()) { DLOG(ERROR) << "Region bounds are not valid for MapViewOfFile"; return false; } - map_start.QuadPart = aligned_start; - map_size = static_cast<SIZE_T>(full_map_size); + map_start.QuadPart = static_cast<uint64_t>(aligned_start); + map_size = full_map_size.ValueOrDie(); length_ = region.size; }
diff --git a/base/memory/shared_memory_mapping_unittest.cc b/base/memory/shared_memory_mapping_unittest.cc index c7fc6d04..c6085039 100644 --- a/base/memory/shared_memory_mapping_unittest.cc +++ b/base/memory/shared_memory_mapping_unittest.cc
@@ -151,7 +151,13 @@ // the creation of a 1GB shared memory region, but don't allow the region to be // mapped. #if !BUILDFLAG(IS_IOS) -TEST_F(SharedMemoryMappingTest, TotalMappedSizeLimit) { +// TODO(crbug.com/1334079) Fix flakiness and re-enable on Linux and ChromeOS. +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) +#define MAYBE_TotalMappedSizeLimit DISABLED_TotalMappedSizeLimit +#else +#define MAYBE_TotalMappedSizeLimit TotalMappedSizeLimit +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) +TEST_F(SharedMemoryMappingTest, MAYBE_TotalMappedSizeLimit) { // Nothing interesting to test if the address space isn't 64 bits, since // there's no real limit enforced on 32 bits other than complete address // space exhaustion.
diff --git a/base/process/process_util_unittest.cc b/base/process/process_util_unittest.cc index 8dcbc4c..3ca900d6 100644 --- a/base/process/process_util_unittest.cc +++ b/base/process/process_util_unittest.cc
@@ -1432,7 +1432,8 @@ } #if defined(CLONE_NEWUSER) && defined(CLONE_NEWPID) -TEST_F(ProcessUtilTest, CloneFlags) { +// TODO(crbug.com/1334073) Enable the test once the bug is fixed. +TEST_F(ProcessUtilTest, DISABLED_CloneFlags) { if (!PathExists(FilePath("/proc/self/ns/user")) || !PathExists(FilePath("/proc/self/ns/pid"))) { // User or PID namespaces are not supported.
diff --git a/base/strings/safe_sprintf_unittest.cc b/base/strings/safe_sprintf_unittest.cc index eaa0a02..550bcaaf 100644 --- a/base/strings/safe_sprintf_unittest.cc +++ b/base/strings/safe_sprintf_unittest.cc
@@ -337,22 +337,23 @@ // Pointer char addr[20]; - sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)buf); + snprintf(addr, sizeof(addr), "0x%llX", (unsigned long long)(uintptr_t)buf); SafeSPrintf(buf, "%p", buf); EXPECT_EQ(std::string(addr), std::string(buf)); SafeSPrintf(buf, "%p", (const char *)buf); EXPECT_EQ(std::string(addr), std::string(buf)); - sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)sprintf); - SafeSPrintf(buf, "%p", sprintf); + snprintf(addr, sizeof(addr), "0x%llX", + (unsigned long long)(uintptr_t)snprintf); + SafeSPrintf(buf, "%p", snprintf); EXPECT_EQ(std::string(addr), std::string(buf)); // Padding for pointers is a little more complicated because of the "0x" // prefix. Padding with '0' zeros is relatively straight-forward, but // padding with ' ' spaces requires more effort. - sprintf(addr, "0x%017llX", (unsigned long long)(uintptr_t)buf); + snprintf(addr, sizeof(addr), "0x%017llX", (unsigned long long)(uintptr_t)buf); SafeSPrintf(buf, "%019p", buf); EXPECT_EQ(std::string(addr), std::string(buf)); - sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)buf); + snprintf(addr, sizeof(addr), "0x%llX", (unsigned long long)(uintptr_t)buf); memset(addr, ' ', (char*)memmove(addr + sizeof(addr) - strlen(addr) - 1, addr, strlen(addr)+1) - addr); @@ -427,8 +428,8 @@ EXPECT_EQ('X', tmp[i]); // The text that was generated by SafeSPrintf() should always match the - // equivalent text generated by sprintf(). Please note that the format - // string for sprintf() is not complicated, as it does not have the + // equivalent text generated by snprintf(). Please note that the format + // string for snprintf() is not complicated, as it does not have the // benefit of getting type information from the C++ compiler. // // N.B.: It would be so much cleaner to use snprintf(). But unfortunately, @@ -436,10 +437,10 @@ // are all really awkward. char ref[256]; CHECK_LE(sz, sizeof(ref)); - sprintf(ref, "A long string: %%d 00DEADBEEF %lld 0x%llX <NULL>", - static_cast<long long>(std::numeric_limits<intptr_t>::min()), - static_cast<unsigned long long>( - reinterpret_cast<uintptr_t>(PrintLongString))); + snprintf(ref, sizeof(ref), "A long string: %%d 00DEADBEEF %lld 0x%llX <NULL>", + static_cast<long long>(std::numeric_limits<intptr_t>::min()), + static_cast<unsigned long long>( + reinterpret_cast<uintptr_t>(PrintLongString))); ref[sz-1] = '\000'; #if defined(NDEBUG) @@ -448,7 +449,7 @@ const size_t kSSizeMax = internal::GetSafeSPrintfSSizeMaxForTest(); #endif - // Compare the output from SafeSPrintf() to the one from sprintf(). + // Compare the output from SafeSPrintf() to the one from snprintf(). EXPECT_EQ(std::string(ref).substr(0, kSSizeMax-1), std::string(tmp.get())); // We allocated a slightly larger buffer, so that we could perform some
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc index 7c8cf62..3bbc6e9 100644 --- a/base/strings/string_util.cc +++ b/base/strings/string_util.cc
@@ -254,14 +254,6 @@ return internal::DoIsStringUTF8<IsValidCodepoint>(str); } -bool LowerCaseEqualsASCII(StringPiece str, StringPiece lowercase_ascii) { - return internal::DoLowerCaseEqualsASCII(str, lowercase_ascii); -} - -bool LowerCaseEqualsASCII(StringPiece16 str, StringPiece lowercase_ascii) { - return internal::DoLowerCaseEqualsASCII(str, lowercase_ascii); -} - bool EqualsASCII(StringPiece16 str, StringPiece ascii) { return std::equal(ascii.begin(), ascii.end(), str.begin(), str.end()); }
diff --git a/base/strings/string_util.h b/base/strings/string_util.h index 87009d7..174e2a5 100644 --- a/base/strings/string_util.h +++ b/base/strings/string_util.h
@@ -337,13 +337,6 @@ BASE_EXPORT bool IsStringASCII(WStringPiece str); #endif -// Compare the lower-case form of the given string against the given -// previously-lower-cased ASCII string (typically a constant). -BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece str, - StringPiece lowercase_ascii); -BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece16 str, - StringPiece lowercase_ascii); - // Performs a case-sensitive string compare of the given 16-bit string against // the given 8-bit ASCII string (typically a constant). The behavior is // undefined if the |ascii| string is not ASCII.
diff --git a/base/strings/string_util_internal.h b/base/strings/string_util_internal.h index d5fc93a..9b998915 100644 --- a/base/strings/string_util_internal.h +++ b/base/strings/string_util_internal.h
@@ -242,28 +242,6 @@ return true; } -// Implementation note: Normally this function will be called with a hardcoded -// constant for the lowercase_ascii parameter. Constructing a StringPiece from -// a C constant requires running strlen, so the result will be two passes -// through the buffers, one to file the length of lowercase_ascii, and one to -// compare each letter. -// -// This function could have taken a const char* to avoid this and only do one -// pass through the string. But the strlen is faster than the case-insensitive -// compares and lets us early-exit in the case that the strings are different -// lengths (will often be the case for non-matches). So whether one approach or -// the other will be faster depends on the case. -// -// The hardcoded strings are typically very short so it doesn't matter, and the -// string piece gives additional flexibility for the caller (doesn't have to be -// null terminated) so we choose the StringPiece route. -template <typename T, typename CharT = typename T::value_type> -inline bool DoLowerCaseEqualsASCII(T str, StringPiece lowercase_ascii) { - return std::equal( - str.begin(), str.end(), lowercase_ascii.begin(), lowercase_ascii.end(), - [](auto lhs, auto rhs) { return ToLowerASCII(lhs) == rhs; }); -} - template <typename T, typename CharT = typename T::value_type> bool StartsWithT(T str, T search_for, CompareCase case_sensitivity) { if (search_for.size() > str.size())
diff --git a/base/strings/string_util_unittest.cc b/base/strings/string_util_unittest.cc index 7304421..d892bb1 100644 --- a/base/strings/string_util_unittest.cc +++ b/base/strings/string_util_unittest.cc
@@ -660,22 +660,6 @@ EXPECT_EQ(u"CC2", ToUpperASCII(u"Cc2")); } -TEST(StringUtilTest, LowerCaseEqualsASCII) { - static const struct { - const char* src_a; - const char* dst; - } lowercase_cases[] = { - { "FoO", "foo" }, - { "foo", "foo" }, - { "FOO", "foo" }, - }; - - for (const auto& i : lowercase_cases) { - EXPECT_TRUE(LowerCaseEqualsASCII(ASCIIToUTF16(i.src_a), i.dst)); - EXPECT_TRUE(LowerCaseEqualsASCII(i.src_a, i.dst)); - } -} - TEST(StringUtilTest, FormatBytesUnlocalized) { static const struct { int64_t bytes;
diff --git a/base/strings/string_util_win.cc b/base/strings/string_util_win.cc index 139ea47..3baac22 100644 --- a/base/strings/string_util_win.cc +++ b/base/strings/string_util_win.cc
@@ -71,10 +71,6 @@ return input.find_first_not_of(characters) == StringPiece::npos; } -bool LowerCaseEqualsASCII(WStringPiece str, StringPiece lowercase_ascii) { - return internal::DoLowerCaseEqualsASCII(str, lowercase_ascii); -} - bool EqualsASCII(WStringPiece str, StringPiece ascii) { return std::equal(ascii.begin(), ascii.end(), str.begin(), str.end()); }
diff --git a/base/strings/string_util_win.h b/base/strings/string_util_win.h index dc2d824c..908c0b9 100644 --- a/base/strings/string_util_win.h +++ b/base/strings/string_util_win.h
@@ -157,9 +157,6 @@ BASE_EXPORT bool ContainsOnlyChars(WStringPiece input, WStringPiece characters); -BASE_EXPORT bool LowerCaseEqualsASCII(WStringPiece str, - StringPiece lowercase_ascii); - BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii); BASE_EXPORT bool StartsWith(
diff --git a/base/task/common/task_annotator.cc b/base/task/common/task_annotator.cc index e324358..8e1f15af 100644 --- a/base/task/common/task_annotator.cc +++ b/base/task/common/task_annotator.cc
@@ -196,8 +196,8 @@ auto* annotator = event->set_chrome_task_annotator(); annotator->set_ipc_hash(task.ipc_hash); if (!task.delayed_run_time.is_null()) { - annotator->set_task_delay_us( - (task.delayed_run_time - task.queue_time).InMicroseconds()); + annotator->set_task_delay_us(static_cast<uint64_t>( + (task.delayed_run_time - task.queue_time).InMicroseconds())); } } #endif // BUILDFLAG(ENABLE_BASE_TRACING)
diff --git a/base/task/sequence_manager/sequence_manager.cc b/base/task/sequence_manager/sequence_manager.cc index ba21b8482..cbb31946 100644 --- a/base/task/sequence_manager/sequence_manager.cc +++ b/base/task/sequence_manager/sequence_manager.cc
@@ -91,14 +91,6 @@ per_priority_same_thread_task_delay_val; return *this; } - -SequenceManager::Settings::Builder& -SequenceManager::Settings::Builder::SetRandomTaskSelectionSeed( - int random_task_selection_seed_val) { - settings_.random_task_selection_seed = random_task_selection_seed_val; - return *this; -} - #endif // DCHECK_IS_ON() SequenceManager::Settings SequenceManager::Settings::Builder::Build() {
diff --git a/base/task/sequence_manager/sequence_manager.h b/base/task/sequence_manager/sequence_manager.h index 155eb75c..6bf2b3e 100644 --- a/base/task/sequence_manager/sequence_manager.h +++ b/base/task/sequence_manager/sequence_manager.h
@@ -129,12 +129,6 @@ // Like the above but for same thread posting. std::array<TimeDelta, TaskQueue::kQueuePriorityCount> per_priority_same_thread_task_delay; - - // If not zero this seeds a PRNG used by the task selection logic to choose - // a random TaskQueue for a given priority rather than the TaskQueue with - // the oldest EnqueueOrder. - int random_task_selection_seed = 0; - #endif // DCHECK_IS_ON() }; @@ -312,12 +306,6 @@ Builder& SetPerPrioritySameThreadTaskDelay( std::array<TimeDelta, TaskQueue::kQueuePriorityCount> per_priority_same_thread_task_delay); - - // If not zero this seeds a PRNG used by the task selection logic to choose a - // random TaskQueue for a given priority rather than the TaskQueue with the - // oldest EnqueueOrder. - Builder& SetRandomTaskSelectionSeed(int random_task_selection_seed); - #endif // DCHECK_IS_ON() Settings Build();
diff --git a/base/task/sequence_manager/sequence_manager_impl.cc b/base/task/sequence_manager/sequence_manager_impl.cc index 4d9e8cf..aaaeccb 100644 --- a/base/task/sequence_manager/sequence_manager_impl.cc +++ b/base/task/sequence_manager/sequence_manager_impl.cc
@@ -105,10 +105,6 @@ // enabling advanced metrics. const double kThreadSamplingRateForRecordingCPUTime = 0.0001; -// Magic value to protect against memory corruption and bail out -// early when detected. -constexpr int kMemoryCorruptionSentinelValue = 0xdeadbeef; - void ReclaimMemoryFromQueue(internal::TaskQueueImpl* queue, LazyNow* lazy_now) { queue->ReclaimMemory(lazy_now->Now()); // If the queue was shut down as a side-effect of reclaiming memory, |queue| @@ -213,7 +209,6 @@ add_queue_time_to_tasks_(settings_.add_queue_time_to_tasks), empty_queues_to_reload_(associated_thread_), - memory_corruption_sentinel_(kMemoryCorruptionSentinelValue), main_thread_only_(this, associated_thread_, settings_, settings_.clock), clock_(settings_.clock) { TRACE_EVENT_OBJECT_CREATED_WITH_ID( @@ -647,8 +642,6 @@ absl::optional<SequenceManagerImpl::SelectedTask> SequenceManagerImpl::SelectNextTaskImpl(LazyNow& lazy_now, SelectTaskOption option) { - CHECK(Validate()); - DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"), "SequenceManagerImpl::SelectNextTask"); @@ -1251,10 +1244,6 @@ return settings_.message_loop_type == type; } -NOINLINE bool SequenceManagerImpl::Validate() { - return memory_corruption_sentinel_ == kMemoryCorruptionSentinelValue; -} - void SequenceManagerImpl::EnableCrashKeys(const char* async_stack_crash_key) { DCHECK(!main_thread_only().async_stack_crash_key); #if !BUILDFLAG(IS_NACL) @@ -1295,8 +1284,9 @@ *(--pos) = ' '; pos = PrependHexAddress(pos - 1, pending_task.posted_from.program_counter()); DCHECK_GE(pos, buffer); - debug::SetCrashKeyString(main_thread_only().async_stack_crash_key, - StringPiece(pos, buffer_end - pos)); + debug::SetCrashKeyString( + main_thread_only().async_stack_crash_key, + StringPiece(pos, static_cast<size_t>(buffer_end - pos))); #endif // BUILDFLAG(IS_NACL) }
diff --git a/base/task/sequence_manager/sequence_manager_impl.h b/base/task/sequence_manager/sequence_manager_impl.h index f81bf9c..d3180ba 100644 --- a/base/task/sequence_manager/sequence_manager_impl.h +++ b/base/task/sequence_manager/sequence_manager_impl.h
@@ -460,12 +460,6 @@ AtomicFlagSet empty_queues_to_reload_; - // A check to bail out early during memory corruption. - // https://crbug.com/757940 - bool Validate(); - - volatile int32_t memory_corruption_sentinel_; - MainThreadOnly main_thread_only_; MainThreadOnly& main_thread_only() { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
diff --git a/base/task/sequence_manager/task_queue_impl.cc b/base/task/sequence_manager/task_queue_impl.cc index 25c9633..8163162 100644 --- a/base/task/sequence_manager/task_queue_impl.cc +++ b/base/task/sequence_manager/task_queue_impl.cc
@@ -835,21 +835,28 @@ StringPrintf("0x%" PRIx64, static_cast<uint64_t>(reinterpret_cast<uintptr_t>(this)))); state.SetBoolKey("enabled", IsQueueEnabled()); - state.SetIntKey("any_thread_.immediate_incoming_queuesize", - any_thread_.immediate_incoming_queue.size()); - state.SetIntKey("delayed_incoming_queue_size", - main_thread_only().delayed_incoming_queue.size()); - state.SetIntKey("immediate_work_queue_size", - main_thread_only().immediate_work_queue->Size()); - state.SetIntKey("delayed_work_queue_size", - main_thread_only().delayed_work_queue->Size()); + // TODO(crbug.com/1334256): Make base::Value able to store an int64_t and + // remove the various static_casts below. + state.SetIntKey( + "any_thread_.immediate_incoming_queuesize", + static_cast<int>(any_thread_.immediate_incoming_queue.size())); + state.SetIntKey( + "delayed_incoming_queue_size", + static_cast<int>(main_thread_only().delayed_incoming_queue.size())); + state.SetIntKey( + "immediate_work_queue_size", + static_cast<int>(main_thread_only().immediate_work_queue->Size())); + state.SetIntKey( + "delayed_work_queue_size", + static_cast<int>(main_thread_only().delayed_work_queue->Size())); - state.SetIntKey("any_thread_.immediate_incoming_queuecapacity", - any_thread_.immediate_incoming_queue.capacity()); + state.SetIntKey( + "any_thread_.immediate_incoming_queuecapacity", + static_cast<int>(any_thread_.immediate_incoming_queue.capacity())); state.SetIntKey("immediate_work_queue_capacity", - immediate_work_queue()->Capacity()); + static_cast<int>(immediate_work_queue()->Capacity())); state.SetIntKey("delayed_work_queue_capacity", - delayed_work_queue()->Capacity()); + static_cast<int>(delayed_work_queue()->Capacity())); if (!main_thread_only().delayed_incoming_queue.empty()) { TimeDelta delay_to_next_task = @@ -862,7 +869,8 @@ Value fence_state(Value::Type::DICTIONARY); fence_state.SetIntKey( "enqueue_order", - main_thread_only().current_fence->task_order().enqueue_order()); + static_cast<int>( + main_thread_only().current_fence->task_order().enqueue_order())); fence_state.SetBoolKey("activated_in_wake_up", !main_thread_only() .current_fence->task_order() @@ -1069,7 +1077,7 @@ Value state(Value::Type::DICTIONARY); state.SetStringKey("posted_from", task.posted_from.ToString()); if (task.enqueue_order_set()) - state.SetIntKey("enqueue_order", task.enqueue_order()); + state.SetIntKey("enqueue_order", static_cast<int>(task.enqueue_order())); state.SetIntKey("sequence_num", task.sequence_num); state.SetBoolKey("nestable", task.nestable == Nestable::kNestable); state.SetBoolKey("is_high_res", task.is_high_res); @@ -1516,7 +1524,8 @@ auto* proto = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>() ->set_chrome_task_posted_to_disabled_queue(); proto->set_task_queue_name(task_queue_name); - proto->set_time_since_disabled_ms(time_since_disabled.InMilliseconds()); + proto->set_time_since_disabled_ms( + checked_cast<uint64_t>(time_since_disabled.InMilliseconds())); proto->set_ipc_hash(pending_task.ipc_hash); proto->set_source_location_iid( base::trace_event::InternedSourceLocation::Get(
diff --git a/base/task/sequence_manager/task_queue_impl.h b/base/task/sequence_manager/task_queue_impl.h index ad03f59..30bb789 100644 --- a/base/task/sequence_manager/task_queue_impl.h +++ b/base/task/sequence_manager/task_queue_impl.h
@@ -594,7 +594,7 @@ // to index into // SequenceManager::Settings::per_priority_cross_thread_task_delay to apply // a priority specific delay for debugging purposes. - int queue_set_index = 0; + size_t queue_set_index = 0; #endif TracingOnly tracing_only;
diff --git a/base/task/sequence_manager/task_queue_selector.cc b/base/task/sequence_manager/task_queue_selector.cc index f9d8046..adba952 100644 --- a/base/task/sequence_manager/task_queue_selector.cc +++ b/base/task/sequence_manager/task_queue_selector.cc
@@ -23,12 +23,8 @@ scoped_refptr<AssociatedThreadId> associated_thread, const SequenceManager::Settings& settings) : associated_thread_(std::move(associated_thread)), -#if DCHECK_IS_ON() - random_task_selection_(settings.random_task_selection_seed != 0), -#endif delayed_work_queue_sets_("delayed", this, settings), - immediate_work_queue_sets_("immediate", this, settings) { -} + immediate_work_queue_sets_("immediate", this, settings) {} TaskQueueSelector::~TaskQueueSelector() = default; @@ -188,21 +184,11 @@ // but the resulting queue must be the lower one. if (option == SelectTaskOption::kSkipDelayedTask) { WorkQueue* queue = -#if DCHECK_IS_ON() - random_task_selection_ - ? ChooseImmediateOnlyWithPriority<SetOperationRandom>(priority) - : -#endif - ChooseImmediateOnlyWithPriority<SetOperationOldest>(priority); + ChooseImmediateOnlyWithPriority<SetOperationOldest>(priority); return queue; } - WorkQueue* queue = -#if DCHECK_IS_ON() - random_task_selection_ ? ChooseWithPriority<SetOperationRandom>(priority) - : -#endif - ChooseWithPriority<SetOperationOldest>(priority); + WorkQueue* queue = ChooseWithPriority<SetOperationOldest>(priority); // If we have selected a delayed task while having an immediate task of the // same priority, increase the starvation count. @@ -249,7 +235,7 @@ } void TaskQueueSelector::SetImmediateStarvationCountForTest( - size_t immediate_starvation_count) { + int immediate_starvation_count) { immediate_starvation_count_ = immediate_starvation_count; }
diff --git a/base/task/sequence_manager/task_queue_selector.h b/base/task/sequence_manager/task_queue_selector.h index 81bd983..13ee8b0 100644 --- a/base/task/sequence_manager/task_queue_selector.h +++ b/base/task/sequence_manager/task_queue_selector.h
@@ -104,11 +104,11 @@ // This method will force select an immediate task if those are being // starved by delayed tasks. - void SetImmediateStarvationCountForTest(size_t immediate_starvation_count); + void SetImmediateStarvationCountForTest(int immediate_starvation_count); // Maximum number of delayed tasks tasks which can be run while there's a // waiting non-delayed task. - static const size_t kMaxDelayedStarvationTasks = 3; + static const int kMaxDelayedStarvationTasks = 3; // Tracks which priorities are currently active, meaning there are pending // runnable tasks with that priority. Because there are only a handful of @@ -154,16 +154,6 @@ } }; -#if DCHECK_IS_ON() - struct SetOperationRandom { - static absl::optional<WorkQueueAndTaskOrder> GetWithPriority( - const WorkQueueSets& sets, - TaskQueue::QueuePriority priority) { - return sets.GetRandomQueueAndTaskOrderInSet(priority); - } - }; -#endif // DCHECK_IS_ON() - template <typename SetOperation> WorkQueue* ChooseWithPriority(TaskQueue::QueuePriority priority) const { // Select an immediate work queue if we are starving immediate tasks. @@ -233,10 +223,6 @@ scoped_refptr<AssociatedThreadId> associated_thread_; -#if DCHECK_IS_ON() - const bool random_task_selection_ = false; -#endif - // Count of the number of sets (delayed or immediate) for each priority. // Should only contain 0, 1 or 2. std::array<int, TaskQueue::kQueuePriorityCount> non_empty_set_counts_ = {{0}}; @@ -249,7 +235,7 @@ WorkQueueSets delayed_work_queue_sets_; WorkQueueSets immediate_work_queue_sets_; - size_t immediate_starvation_count_ = 0; + int immediate_starvation_count_ = 0; raw_ptr<Observer> task_queue_selector_observer_ = nullptr; // Not owned. };
diff --git a/base/task/sequence_manager/thread_controller.cc b/base/task/sequence_manager/thread_controller.cc index c9aad86..6f181dca 100644 --- a/base/task/sequence_manager/thread_controller.cc +++ b/base/task/sequence_manager/thread_controller.cc
@@ -110,7 +110,8 @@ // thread_controller_sample_metadata_ when yielding back to a parent RunLevel // (which is active by definition as it is currently running this one). if (is_nested_) { - thread_controller_sample_metadata_.Set(++thread_controller_active_id_); + thread_controller_sample_metadata_.Set( + static_cast<int64_t>(++thread_controller_active_id_)); } } @@ -144,7 +145,8 @@ TRACE_EVENT_BEGIN0("base", "ThreadController active"); // Overriding the annotation from the previous RunLevel is intentional. Only // the top RunLevel is ever updated, which holds the relevant state. - thread_controller_sample_metadata_.Set(++thread_controller_active_id_); + thread_controller_sample_metadata_.Set( + static_cast<int64_t>(++thread_controller_active_id_)); } else { thread_controller_sample_metadata_.Remove(); TRACE_EVENT_END0("base", "ThreadController active");
diff --git a/base/task/sequence_manager/wake_up_queue.cc b/base/task/sequence_manager/wake_up_queue.cc index 5e51c26..5ecac60 100644 --- a/base/task/sequence_manager/wake_up_queue.cc +++ b/base/task/sequence_manager/wake_up_queue.cc
@@ -134,7 +134,10 @@ Value WakeUpQueue::AsValue(TimeTicks now) const { Value state(Value::Type::DICTIONARY); state.SetStringKey("name", GetName()); - state.SetIntKey("registered_delay_count", wake_up_queue_.size()); + // TODO(crbug.com/1334256): Make base::Value able to store an int64_t and + // remove this cast. + state.SetIntKey("registered_delay_count", + checked_cast<int>(wake_up_queue_.size())); if (!wake_up_queue_.empty()) { TimeDelta delay = wake_up_queue_.top().wake_up.time - now; state.SetDoubleKey("next_delay_ms", delay.InMillisecondsF());
diff --git a/base/task/sequence_manager/work_queue_sets.cc b/base/task/sequence_manager/work_queue_sets.cc index a10577c..c84f07b1 100644 --- a/base/task/sequence_manager/work_queue_sets.cc +++ b/base/task/sequence_manager/work_queue_sets.cc
@@ -16,12 +16,7 @@ WorkQueueSets::WorkQueueSets(const char* name, Observer* observer, const SequenceManager::Settings& settings) - : name_(name), -#if DCHECK_IS_ON() - last_rand_(settings.random_task_selection_seed), -#endif - observer_(observer) { -} + : name_(name), observer_(observer) {} WorkQueueSets::~WorkQueueSets() = default; @@ -159,23 +154,6 @@ return WorkQueueAndTaskOrder(*oldest.value, oldest.key); } -#if DCHECK_IS_ON() -absl::optional<WorkQueueAndTaskOrder> -WorkQueueSets::GetRandomQueueAndTaskOrderInSet(size_t set_index) const { - DCHECK_LT(set_index, work_queue_heaps_.size()); - if (work_queue_heaps_[set_index].empty()) - return absl::nullopt; - const OldestTaskOrder& chosen = - work_queue_heaps_[set_index] - .begin()[Random() % work_queue_heaps_[set_index].size()]; -#if DCHECK_IS_ON() - absl::optional<TaskOrder> key = chosen.value->GetFrontTaskOrder(); - DCHECK(key && chosen.key == *key); -#endif - return WorkQueueAndTaskOrder(*chosen.value, chosen.key); -} -#endif - bool WorkQueueSets::IsSetEmpty(size_t set_index) const { DCHECK_LT(set_index, work_queue_heaps_.size()) << " set_index = " << set_index;
diff --git a/base/task/sequence_manager/work_queue_sets.h b/base/task/sequence_manager/work_queue_sets.h index 555baac..0753cd4 100644 --- a/base/task/sequence_manager/work_queue_sets.h +++ b/base/task/sequence_manager/work_queue_sets.h
@@ -79,12 +79,6 @@ absl::optional<WorkQueueAndTaskOrder> GetOldestQueueAndTaskOrderInSet( size_t set_index) const; -#if DCHECK_IS_ON() - // O(1) - absl::optional<WorkQueueAndTaskOrder> GetRandomQueueAndTaskOrderInSet( - size_t set_index) const; -#endif - // O(1) bool IsSetEmpty(size_t set_index) const; @@ -127,27 +121,6 @@ TaskQueue::kQueuePriorityCount> work_queue_heaps_; -#if DCHECK_IS_ON() - static inline uint64_t MurmurHash3(uint64_t value) { - value ^= value >> 33; - value *= uint64_t{0xFF51AFD7ED558CCD}; - value ^= value >> 33; - value *= uint64_t{0xC4CEB9FE1A85EC53}; - value ^= value >> 33; - return value; - } - - // This is for a debugging feature which lets us randomize task selection. Its - // not for production use. - // TODO(alexclarke): Use a seedable PRNG from ::base if one is added. - uint64_t Random() const { - last_rand_ = MurmurHash3(last_rand_); - return last_rand_; - } - - mutable uint64_t last_rand_; -#endif - const raw_ptr<Observer> observer_; };
diff --git a/base/task/single_thread_task_executor.cc b/base/task/single_thread_task_executor.cc index e8aa7093..1a4fac39 100644 --- a/base/task/single_thread_task_executor.cc +++ b/base/task/single_thread_task_executor.cc
@@ -43,7 +43,7 @@ return default_task_queue_->task_runner(); } -void SingleThreadTaskExecutor::SetWorkBatchSize(size_t work_batch_size) { +void SingleThreadTaskExecutor::SetWorkBatchSize(int work_batch_size) { sequence_manager_->SetWorkBatchSize(work_batch_size); }
diff --git a/base/task/single_thread_task_executor.h b/base/task/single_thread_task_executor.h index 6afc964..b52bd475 100644 --- a/base/task/single_thread_task_executor.h +++ b/base/task/single_thread_task_executor.h
@@ -51,7 +51,7 @@ // asks its delegate to DoWork(). Defaults to 1. Can be increased in some // scenarios where the native pump (i.e. not MessagePumpType::DEFAULT) has // high overhead and yielding to native isn't critical. - void SetWorkBatchSize(size_t work_batch_size); + void SetWorkBatchSize(int work_batch_size); private: explicit SingleThreadTaskExecutor(MessagePumpType type,
diff --git a/base/task/thread_pool/initialization_util.cc b/base/task/thread_pool/initialization_util.cc index 026a686..a2fa8e9 100644 --- a/base/task/thread_pool/initialization_util.cc +++ b/base/task/thread_pool/initialization_util.cc
@@ -12,12 +12,13 @@ namespace base { -int RecommendedMaxNumberOfThreadsInThreadGroup(int min, - int max, - double cores_multiplier, - int offset) { - const int num_of_cores = SysInfo::NumberOfProcessors(); - const int threads = std::ceil<int>(num_of_cores * cores_multiplier) + offset; +size_t RecommendedMaxNumberOfThreadsInThreadGroup(size_t min, + size_t max, + double cores_multiplier, + size_t offset) { + const auto num_of_cores = static_cast<size_t>(SysInfo::NumberOfProcessors()); + const size_t threads = + std::ceil<size_t>(num_of_cores * cores_multiplier) + offset; return clamp(threads, min, max); }
diff --git a/base/task/thread_pool/initialization_util.h b/base/task/thread_pool/initialization_util.h index 62486f2e..bf26e4c 100644 --- a/base/task/thread_pool/initialization_util.h +++ b/base/task/thread_pool/initialization_util.h
@@ -5,17 +5,19 @@ #ifndef BASE_TASK_THREAD_POOL_INITIALIZATION_UTIL_H_ #define BASE_TASK_THREAD_POOL_INITIALIZATION_UTIL_H_ +#include <stddef.h> + #include "base/base_export.h" namespace base { // Computes a value that may be used as the maximum number of threads in a // ThreadGroup. Developers may use other methods to choose this maximum. -BASE_EXPORT int RecommendedMaxNumberOfThreadsInThreadGroup( - int min, - int max, - double cores_multiplier, - int offset); +BASE_EXPORT size_t +RecommendedMaxNumberOfThreadsInThreadGroup(size_t min, + size_t max, + double cores_multiplier, + size_t offset); } // namespace base
diff --git a/base/task/thread_pool/job_task_source.cc b/base/task/thread_pool/job_task_source.cc index 75cb72c..8529e31 100644 --- a/base/task/thread_pool/job_task_source.cc +++ b/base/task/thread_pool/job_task_source.cc
@@ -54,6 +54,8 @@ JobTaskSource::State::Value JobTaskSource::State::IncrementWorkerCount() { uint32_t value_before_add = value_.fetch_add(kWorkerCountIncrement, std::memory_order_relaxed); + // The worker count must not overflow a uint8_t. + DCHECK((value_before_add >> kWorkerCountBitOffset) < ((1 << 8) - 1)); return {value_before_add}; } @@ -296,7 +298,7 @@ uint32_t assigned_task_ids = assigned_task_ids_.load(std::memory_order_relaxed); uint32_t new_assigned_task_ids = 0; - uint8_t task_id = 0; + int task_id = 0; // memory_order_acquire on success, matched with memory_order_release in // ReleaseTaskId() so that operations done by previous threads that had // the same task_id become visible to the current thread. @@ -308,7 +310,7 @@ } while (!assigned_task_ids_.compare_exchange_weak( assigned_task_ids, new_assigned_task_ids, std::memory_order_acquire, std::memory_order_relaxed)); - return task_id; + return static_cast<uint8_t>(task_id); } void JobTaskSource::ReleaseTaskId(uint8_t task_id) {
diff --git a/base/task/thread_pool/job_task_source.h b/base/task/thread_pool/job_task_source.h index 576d81b4..9cb03b6fc 100644 --- a/base/task/thread_pool/job_task_source.h +++ b/base/task/thread_pool/job_task_source.h
@@ -103,7 +103,9 @@ << kWorkerCountBitOffset; struct Value { - size_t worker_count() const { return value >> kWorkerCountBitOffset; } + uint8_t worker_count() const { + return static_cast<uint8_t>(value >> kWorkerCountBitOffset); + } // Returns true if canceled. bool is_canceled() const { return value & kCanceledMask; }
diff --git a/base/task/thread_pool/priority_queue.cc b/base/task/thread_pool/priority_queue.cc index fe6b5273..729f836 100644 --- a/base/task/thread_pool/priority_queue.cc +++ b/base/task/thread_pool/priority_queue.cc
@@ -8,6 +8,7 @@ #include "base/check_op.h" #include "base/memory/ptr_util.h" +#include "base/stl_util.h" namespace base { namespace internal { @@ -193,12 +194,12 @@ } void PriorityQueue::DecrementNumTaskSourcesForPriority(TaskPriority priority) { - DCHECK_GT(num_task_sources_per_priority_[static_cast<int>(priority)], 0U); - --num_task_sources_per_priority_[static_cast<int>(priority)]; + DCHECK_GT(num_task_sources_per_priority_[base::to_underlying(priority)], 0U); + --num_task_sources_per_priority_[base::to_underlying(priority)]; } void PriorityQueue::IncrementNumTaskSourcesForPriority(TaskPriority priority) { - ++num_task_sources_per_priority_[static_cast<int>(priority)]; + ++num_task_sources_per_priority_[base::to_underlying(priority)]; } } // namespace internal
diff --git a/base/task/thread_pool/thread_group_impl.cc b/base/task/thread_pool/thread_group_impl.cc index e010855..3fb7a4e5 100644 --- a/base/task/thread_pool/thread_group_impl.cc +++ b/base/task/thread_pool/thread_group_impl.cc
@@ -387,8 +387,8 @@ } void ThreadGroupImpl::Start( - int max_tasks, - int max_best_effort_tasks, + size_t max_tasks, + size_t max_best_effort_tasks, TimeDelta suggested_reclaim_time, scoped_refptr<SingleThreadTaskRunner> service_thread_task_runner, WorkerThreadObserver* worker_thread_observer, @@ -763,7 +763,8 @@ if (outer_->num_tasks_before_detach_histogram_) { executor->ScheduleAddHistogramSample( outer_->num_tasks_before_detach_histogram_, - worker_only().num_tasks_since_last_detach); + saturated_cast<HistogramBase::Sample>( + worker_only().num_tasks_since_last_detach)); } worker->Cleanup(); outer_->idle_workers_stack_.Remove(worker);
diff --git a/base/task/thread_pool/thread_group_impl.h b/base/task/thread_pool/thread_group_impl.h index 0952b0ca..b54c1721d 100644 --- a/base/task/thread_pool/thread_group_impl.h +++ b/base/task/thread_pool/thread_group_impl.h
@@ -78,8 +78,8 @@ // `synchronous_thread_start_for_testing` is true if this ThreadGroupImpl // should synchronously wait for OnMainEntry() after starting each worker. Can // only be called once. CHECKs on failure. - void Start(int max_tasks, - int max_best_effort_tasks, + void Start(size_t max_tasks, + size_t max_best_effort_tasks, TimeDelta suggested_reclaim_time, scoped_refptr<SingleThreadTaskRunner> service_thread_task_runner, WorkerThreadObserver* worker_thread_observer,
diff --git a/base/task/thread_pool/thread_group_native.cc b/base/task/thread_pool/thread_group_native.cc index 9147058..c149f1b3b 100644 --- a/base/task/thread_pool/thread_group_native.cc +++ b/base/task/thread_pool/thread_group_native.cc
@@ -172,8 +172,7 @@ // active at one time. Consequently, we cannot report a true value here. // Instead, the values were chosen to match // ThreadPoolInstance::StartWithDefaultParams. - const int num_cores = SysInfo::NumberOfProcessors(); - return std::max(3, num_cores - 1); + return static_cast<size_t>(std::max(3, SysInfo::NumberOfProcessors() - 1)); } void ThreadGroupNative::DidUpdateCanRunPolicy() {
diff --git a/base/task/thread_pool/thread_pool_impl.cc b/base/task/thread_pool/thread_pool_impl.cc index 22cf7cd..a765598 100644 --- a/base/task/thread_pool/thread_pool_impl.cc +++ b/base/task/thread_pool/thread_pool_impl.cc
@@ -52,7 +52,7 @@ constexpr EnvironmentParams kBackgroundPoolEnvironmentParams{ "Background", base::ThreadPriority::BACKGROUND}; -constexpr int kMaxBestEffortTasks = 2; +constexpr size_t kMaxBestEffortTasks = 2; // Indicates whether BEST_EFFORT tasks are disabled by a command line switch. bool HasDisableBestEffortTasksSwitch() { @@ -135,7 +135,7 @@ // The max number of concurrent BEST_EFFORT tasks is |kMaxBestEffortTasks|, // unless the max number of foreground threads is lower. - const int max_best_effort_tasks = + const size_t max_best_effort_tasks = std::min(kMaxBestEffortTasks, init_params.max_num_foreground_threads); // Start the service thread. On platforms that support it (POSIX except NaCL @@ -322,7 +322,7 @@ g_synchronous_thread_start_for_testing = enabled; } -int ThreadPoolImpl::GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( +size_t ThreadPoolImpl::GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( const TaskTraits& traits) const { // This method does not support getting the maximum number of BEST_EFFORT // tasks that can run concurrently in a pool.
diff --git a/base/task/thread_pool/thread_pool_impl.h b/base/task/thread_pool/thread_pool_impl.h index d6fca6c6..1af9db91 100644 --- a/base/task/thread_pool/thread_pool_impl.h +++ b/base/task/thread_pool/thread_pool_impl.h
@@ -66,7 +66,7 @@ WorkerThreadObserver* worker_thread_observer) override; bool WasStarted() const final; bool WasStartedUnsafe() const final; - int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + size_t GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( const TaskTraits& traits) const override; void Shutdown() override; void FlushForTesting() override;
diff --git a/base/task/thread_pool/thread_pool_impl_unittest.cc b/base/task/thread_pool/thread_pool_impl_unittest.cc index 5a127a6..19b3116 100644 --- a/base/task/thread_pool/thread_pool_impl_unittest.cc +++ b/base/task/thread_pool/thread_pool_impl_unittest.cc
@@ -63,7 +63,7 @@ namespace { -constexpr int kMaxNumForegroundThreads = 4; +constexpr size_t kMaxNumForegroundThreads = 4; struct TraitsExecutionModePair { TraitsExecutionModePair(const TaskTraits& traits, @@ -304,7 +304,7 @@ } void StartThreadPool( - int max_num_foreground_threads = kMaxNumForegroundThreads, + size_t max_num_foreground_threads = kMaxNumForegroundThreads, TimeDelta reclaim_time = Seconds(30)) { SetupFeatures(); @@ -817,10 +817,10 @@ {MayBlock(), TaskPriority::BEST_EFFORT}); }); - const int expected_max = + const size_t expected_max = GetGroupTypes().foreground_type == test::GroupType::GENERIC ? kMaxNumForegroundThreads - : std::max(3, SysInfo::NumberOfProcessors() - 1); + : static_cast<size_t>(std::max(3, SysInfo::NumberOfProcessors() - 1)); EXPECT_EQ(expected_max, thread_pool_->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( @@ -1437,7 +1437,7 @@ // thread per pool, it is possible that tasks don't run in order even if // threads got tasks from the PriorityQueue in order. Therefore, enforce a // maximum of 1 thread per pool. - constexpr int kLocalMaxNumForegroundThreads = 1; + constexpr size_t kLocalMaxNumForegroundThreads = 1; test->StartThreadPool(kLocalMaxNumForegroundThreads); auto task_runners_and_events =
diff --git a/base/task/thread_pool/thread_pool_instance.cc b/base/task/thread_pool/thread_pool_instance.cc index b492b3c..a1c77bc 100644 --- a/base/task/thread_pool/thread_pool_instance.cc +++ b/base/task/thread_pool/thread_pool_instance.cc
@@ -23,7 +23,7 @@ } // namespace -ThreadPoolInstance::InitParams::InitParams(int max_num_foreground_threads_in) +ThreadPoolInstance::InitParams::InitParams(size_t max_num_foreground_threads_in) : max_num_foreground_threads(max_num_foreground_threads_in) {} ThreadPoolInstance::InitParams::~InitParams() = default; @@ -64,8 +64,8 @@ // * The system is utilized maximally by foreground threads. // * The main thread is assumed to be busy, cap foreground workers at // |num_cores - 1|. - const int num_cores = SysInfo::NumberOfProcessors(); - const int max_num_foreground_threads = std::max(3, num_cores - 1); + const size_t max_num_foreground_threads = + static_cast<size_t>(std::max(3, SysInfo::NumberOfProcessors() - 1)); Start({max_num_foreground_threads}); } #endif // !BUILDFLAG(IS_NACL)
diff --git a/base/task/thread_pool/thread_pool_instance.h b/base/task/thread_pool/thread_pool_instance.h index f02b893..a4e5024 100644 --- a/base/task/thread_pool/thread_pool_instance.h +++ b/base/task/thread_pool/thread_pool_instance.h
@@ -57,12 +57,12 @@ #endif // BUILDFLAG(IS_WIN) }; - InitParams(int max_num_foreground_threads_in); + InitParams(size_t max_num_foreground_threads_in); ~InitParams(); // Maximum number of unblocked tasks that can run concurrently in the // foreground thread group. - int max_num_foreground_threads; + size_t max_num_foreground_threads; // Whether COM is initialized when running sequenced and parallel tasks. CommonThreadPoolEnvironment common_thread_pool_environment = @@ -244,7 +244,7 @@ // n/GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated() items. // // TODO(fdoray): Remove this method. https://crbug.com/687264 - virtual int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + virtual size_t GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( const TaskTraits& traits) const = 0; // Starts/stops a fence that prevents scheduling of tasks of any / BEST_EFFORT
diff --git a/base/task/thread_pool/thread_pool_perftest.cc b/base/task/thread_pool/thread_pool_perftest.cc index 17689b9e..802d5f1 100644 --- a/base/task/thread_pool/thread_pool_perftest.cc +++ b/base/task/thread_pool/thread_pool_perftest.cc
@@ -148,7 +148,7 @@ void StartThreadPool(size_t num_running_threads, size_t num_posting_threads, base::RepeatingClosure post_action) { - ThreadPoolInstance::Get()->Start({static_cast<int>(num_running_threads)}); + ThreadPoolInstance::Get()->Start({num_running_threads}); base::RepeatingClosure done = BarrierClosure( num_posting_threads,
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index a0f7a241..c676df61 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -1453,7 +1453,7 @@ fprintf(stdout, "Using %zu parallel jobs.\n", parallel_jobs_); fflush(stdout); - CreateAndStartThreadPool(static_cast<int>(parallel_jobs_)); + CreateAndStartThreadPool(parallel_jobs_); std::vector<std::string> positive_file_filter; std::vector<std::string> positive_gtest_filter; @@ -1747,7 +1747,7 @@ return result; } -void TestLauncher::CreateAndStartThreadPool(int num_parallel_jobs) { +void TestLauncher::CreateAndStartThreadPool(size_t num_parallel_jobs) { base::ThreadPoolInstance::Create("TestLauncher"); base::ThreadPoolInstance::Get()->Start({num_parallel_jobs}); }
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h index 63d7400..cbbcda4 100644 --- a/base/test/launcher/test_launcher.h +++ b/base/test/launcher/test_launcher.h
@@ -221,7 +221,7 @@ // Creates and starts a ThreadPoolInstance with |num_parallel_jobs| dedicated // to foreground blocking tasks (corresponds to the traits used to launch and // wait for child processes). virtual to mock in testing. - virtual void CreateAndStartThreadPool(int num_parallel_jobs); + virtual void CreateAndStartThreadPool(size_t num_parallel_jobs); // Callback to receive result of a test. // |result_file| is a path to xml file written by child process.
diff --git a/base/test/launcher/test_launcher_unittest.cc b/base/test/launcher/test_launcher_unittest.cc index 15de857..0a5776d 100644 --- a/base/test/launcher/test_launcher_unittest.cc +++ b/base/test/launcher/test_launcher_unittest.cc
@@ -73,7 +73,7 @@ size_t parallel_jobs) : TestLauncher(launcher_delegate, parallel_jobs) {} - void CreateAndStartThreadPool(int parallel_jobs) override {} + void CreateAndStartThreadPool(size_t parallel_jobs) override {} MOCK_METHOD4(LaunchChildGTestProcess, void(scoped_refptr<TaskRunner> task_runner,
diff --git a/build/PRESUBMIT.py b/build/PRESUBMIT.py index 5bdd1ddd..5be696d 100644 --- a/build/PRESUBMIT.py +++ b/build/PRESUBMIT.py
@@ -17,7 +17,9 @@ r'(.+/)?BUILD\.gn', r'.+\.gni', ] - bad_pattern = input_api.re.compile(r'^[^#]*//(base|third_party|components)') + blocklist_pattern = input_api.re.compile( + r'^[^#]*//(?:base|third_party|components)') + allowlist_pattern = input_api.re.compile(r'^[^#]*//third_party/junit') warning_message = textwrap.dedent(""" The //build directory is meant to be as hermetic as possible so that @@ -36,7 +38,7 @@ for f in input_api.AffectedSourceFiles(FilterFile): local_path = f.LocalPath() for line_number, line in f.ChangedContents(): - if (bad_pattern.search(line)): + if blocklist_pattern.search(line) and not allowlist_pattern.search(line): problems.append('%s:%d\n %s' % (local_path, line_number, line.strip())) if problems:
diff --git a/build/android/BUILD.gn b/build/android/BUILD.gn index b30bd50..2475f7d 100644 --- a/build/android/BUILD.gn +++ b/build/android/BUILD.gn
@@ -53,6 +53,14 @@ # be created when creating an apk. jar_excluded_patterns += [ "*/NativeLibraries.class" ] } + + junit_binary("build_junit_tests") { + sources = [ "junit/src/org/chromium/build/IncrementalJavacTest.java" ] + deps = [ + "//build/android/test/incremental_javac_gn:no_signature_change_prebuilt_java", + "//third_party/junit", + ] + } } python_library("devil_chromium_py") {
diff --git a/build/android/java/test/IncrementalJavacTest.java b/build/android/junit/src/org/chromium/build/IncrementalJavacTest.java similarity index 81% rename from build/android/java/test/IncrementalJavacTest.java rename to build/android/junit/src/org/chromium/build/IncrementalJavacTest.java index c83178aa..b1daa55 100644 --- a/build/android/java/test/IncrementalJavacTest.java +++ b/build/android/junit/src/org/chromium/build/IncrementalJavacTest.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package test; +package org.chromium.build; import static org.junit.Assert.assertEquals; @@ -10,13 +10,15 @@ import org.junit.runner.RunWith; import org.robolectric.annotation.Config; -import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.testing.local.LocalRobolectricTestRunner; + +import test.NoSignatureChangeIncrementalJavacTestHelper; /** * Checks that build picked up changes to * {@link NoSignatureChangeIncrementalJavacTestHelper#foo()}. */ -@RunWith(BaseRobolectricTestRunner.class) +@RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE) public final class IncrementalJavacTest { @Test
diff --git a/build/android/pylib/results/report_results.py b/build/android/pylib/results/report_results.py index 56eefac4..da6aeb7 100644 --- a/build/android/pylib/results/report_results.py +++ b/build/android/pylib/results/report_results.py
@@ -108,17 +108,17 @@ logging.critical('*' * 80) logging.critical('Summary') logging.critical('*' * 80) - for line in results.GetGtestForm().splitlines(): - color = black_on_white - if 'FAILED' in line: - # Red on white, dim. - color = (logging_utils.BACK.WHITE, logging_utils.FORE.RED, - logging_utils.STYLE.DIM) - elif 'PASSED' in line: - # Green on white, dim. - color = (logging_utils.BACK.WHITE, logging_utils.FORE.GREEN, - logging_utils.STYLE.DIM) - with logging_utils.OverrideColor(logging.CRITICAL, color): + # Assign uniform color, depending on presence of 'FAILED' over lines. + if any('FAILED' in line for line in results.GetGtestForm().splitlines()): + # Red on white, dim. + color = (logging_utils.BACK.WHITE, logging_utils.FORE.RED, + logging_utils.STYLE.DIM) + else: + # Green on white, dim. + color = (logging_utils.BACK.WHITE, logging_utils.FORE.GREEN, + logging_utils.STYLE.DIM) + with logging_utils.OverrideColor(logging.CRITICAL, color): + for line in results.GetGtestForm().splitlines(): logging.critical(line) logging.critical('*' * 80)
diff --git a/build/android/pylib/utils/logging_utils.py b/build/android/pylib/utils/logging_utils.py index 10891ec..33d1114 100644 --- a/build/android/pylib/utils/logging_utils.py +++ b/build/android/pylib/utils/logging_utils.py
@@ -24,6 +24,7 @@ # pylint: disable=no-member color_map = { logging.DEBUG: (FORE.CYAN), + logging.INFO: (), # Use default style. logging.WARNING: (FORE.YELLOW), logging.ERROR: (FORE.RED), logging.CRITICAL: (BACK.RED),
diff --git a/build/android/test/BUILD.gn b/build/android/test/BUILD.gn index 9edb6bfa..8e33dd3 100644 --- a/build/android/test/BUILD.gn +++ b/build/android/test/BUILD.gn
@@ -6,90 +6,78 @@ import("missing_symbol_test.gni") import("nocompile_gn/nocompile_sources.gni") -if (enable_java_templates) { - group("android_nocompile_tests") { - testonly = true +group("android_nocompile_tests") { + testonly = true - # No-compile tests use an output directory dedicated to no-compile tests. - # All test suites use targets in nocompile_gn/BUILD.gn in order to share the - # same target output directory and avoid running 'gn gen' for each - # android_nocompile_test_suite(). - deps = [ - ":android_lint_tests", - ":android_lookup_dep_tests", - ] - } + # No-compile tests use an output directory dedicated to no-compile tests. + # All test suites use targets in nocompile_gn/BUILD.gn in order to share the + # same target output directory and avoid running 'gn gen' for each + # android_nocompile_test_suite(). + deps = [ + ":android_lint_tests", + ":android_lookup_dep_tests", + ] +} - android_nocompile_test_suite("android_lint_tests") { - # Depend on lint script so that the action is re-run whenever the script is modified. - pydeps = [ "//build/android/gyp/lint.pydeps" ] +android_nocompile_test_suite("android_lint_tests") { + # Depend on lint script so that the action is re-run whenever the script is modified. + pydeps = [ "//build/android/gyp/lint.pydeps" ] - tests = [ - { - target = "nocompile_gn:default_locale_lint_test" - nocompile_sources = - rebase_path(default_locale_lint_test_nocompile_sources, - "", - "nocompile_gn") - expected_compile_output_regex = "Warning:.*DefaultLocale" - }, - { - target = "nocompile_gn:new_api_lint_test" - nocompile_sources = - rebase_path(new_api_lint_test_nocompile_sources, "", "nocompile_gn") - expected_compile_output_regex = "Error:.*NewApi" - }, - ] - } + tests = [ + { + target = "nocompile_gn:default_locale_lint_test" + nocompile_sources = + rebase_path(default_locale_lint_test_nocompile_sources, + "", + "nocompile_gn") + expected_compile_output_regex = "Warning:.*DefaultLocale" + }, + { + target = "nocompile_gn:new_api_lint_test" + nocompile_sources = + rebase_path(new_api_lint_test_nocompile_sources, "", "nocompile_gn") + expected_compile_output_regex = "Error:.*NewApi" + }, + ] +} - android_nocompile_test_suite("android_lookup_dep_tests") { - sources = [ rebase_path( - missing_symbol_generated_importer_template_nocompile_source, - "", - "nocompile_gn") ] +android_nocompile_test_suite("android_lookup_dep_tests") { + sources = + [ rebase_path(missing_symbol_generated_importer_template_nocompile_source, + "", + "nocompile_gn") ] - tests = [ - { - target = "nocompile_gn:import_child_missing_symbol_test_java" - nocompile_sources = - rebase_path(import_child_missing_symbol_test_nocompile_sources, - "", - "nocompile_gn") - expected_compile_output_regex = "error: package test\.missing_symbol\.sub does not exist\nHint: Add \"//build/android/test/nocompile_gn:sub_b_java\" to deps of //build/android/test/nocompile_gn:import_child_missing_symbol_test_java" - }, - { - target = "nocompile_gn:import_parent_missing_symbol_test_java" - nocompile_sources = [] - expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.B\nHint: Add \"//build/android/test/nocompile_gn:b_java\" to deps of //build/android/test/nocompile_gn:import_parent_missing_symbol_test_java" - }, - { - target = "nocompile_gn:import_turbine_missing_symbol_test_java" - nocompile_sources = - rebase_path(import_turbine_missing_symbol_test_nocompile_sources, - "", - "nocompile_gn") - expected_compile_output_regex = "error: symbol not found test\.missing_symbol\.B\nHint: Add \"//build/android/test/nocompile_gn:b_java\" to deps of //build/android/test/nocompile_gn:import_turbine_missing_symbol_test_java" - }, - { - target = "nocompile_gn:prebuilt_missing_symbol_test_java" - nocompile_sources = [] - expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.C\nHint: Add \"//build/android/test/nocompile_gn:c_prebuilt_java\" to deps of //build/android/test/nocompile_gn:prebuilt_missing_symbol_test_java" - }, - { - target = "nocompile_gn:cpp_template_missing_symbol_test_java" - nocompile_sources = [] - expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.D\nHint: Add \"//build/android/test/nocompile_gn:d_java\" to deps of //build/android/test/nocompile_gn:cpp_template_missing_symbol_test_java" - }, - ] - } - - # Tests that builds which use incremental javac are valid. - junit_binary("incremental_javac_junit_tests") { - sources = [ "../java/test/IncrementalJavacTest.java" ] - deps = [ - "incremental_javac_gn:no_signature_change_prebuilt_java", - "//base:base_junit_test_support", - "//third_party/junit", - ] - } + tests = [ + { + target = "nocompile_gn:import_child_missing_symbol_test_java" + nocompile_sources = + rebase_path(import_child_missing_symbol_test_nocompile_sources, + "", + "nocompile_gn") + expected_compile_output_regex = "error: package test\.missing_symbol\.sub does not exist\nHint: Add \"//build/android/test/nocompile_gn:sub_b_java\" to deps of //build/android/test/nocompile_gn:import_child_missing_symbol_test_java" + }, + { + target = "nocompile_gn:import_parent_missing_symbol_test_java" + nocompile_sources = [] + expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.B\nHint: Add \"//build/android/test/nocompile_gn:b_java\" to deps of //build/android/test/nocompile_gn:import_parent_missing_symbol_test_java" + }, + { + target = "nocompile_gn:import_turbine_missing_symbol_test_java" + nocompile_sources = + rebase_path(import_turbine_missing_symbol_test_nocompile_sources, + "", + "nocompile_gn") + expected_compile_output_regex = "error: symbol not found test\.missing_symbol\.B\nHint: Add \"//build/android/test/nocompile_gn:b_java\" to deps of //build/android/test/nocompile_gn:import_turbine_missing_symbol_test_java" + }, + { + target = "nocompile_gn:prebuilt_missing_symbol_test_java" + nocompile_sources = [] + expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.C\nHint: Add \"//build/android/test/nocompile_gn:c_prebuilt_java\" to deps of //build/android/test/nocompile_gn:prebuilt_missing_symbol_test_java" + }, + { + target = "nocompile_gn:cpp_template_missing_symbol_test_java" + nocompile_sources = [] + expected_compile_output_regex = "error: cannot find symbol test\.missing_symbol\.D\nHint: Add \"//build/android/test/nocompile_gn:d_java\" to deps of //build/android/test/nocompile_gn:cpp_template_missing_symbol_test_java" + }, + ] }
diff --git a/build/fuchsia/binary_size_differ.py b/build/fuchsia/binary_size_differ.py index 80c3a0bb..379fd44 100755 --- a/build/fuchsia/binary_size_differ.py +++ b/build/fuchsia/binary_size_differ.py
@@ -23,36 +23,32 @@ from common import GetHostToolPathFromPlatform, GetHostArchFromPlatform from common import SDK_ROOT, DIR_SOURCE_ROOT -from binary_sizes import GetPackageSizes, ReadPackageBlobsJson -from binary_sizes import PACKAGES_SIZE_FILE +from binary_sizes import ReadPackageSizesJson +from binary_sizes import PACKAGES_SIZES_FILE _MAX_DELTA_BYTES = 12 * 1024 # 12 KiB _TRYBOT_DOC = 'https://chromium.googlesource.com/chromium/src/+/main/docs/speed/binary_size/fuchsia_binary_size_trybot.md' -def GetPackageBlobsFromFile(blob_file_path): - return GetPackageSizes(ReadPackageBlobsJson(blob_file_path)) - - -def ComputePackageDiffs(before_blobs_file, after_blobs_file): +def ComputePackageDiffs(before_sizes_file, after_sizes_file): '''Computes difference between after and before diff, for each package.''' - before_blobs = GetPackageBlobsFromFile(before_blobs_file) - after_blobs = GetPackageBlobsFromFile(after_blobs_file) + before_sizes = ReadPackageSizesJson(before_sizes_file) + after_sizes = ReadPackageSizesJson(after_sizes_file) - assert before_blobs.keys() == after_blobs.keys(), ( + assert before_sizes.keys() == after_sizes.keys(), ( 'Package files cannot' ' be compared with different packages: ' - '%s vs %s' % (before_blobs.keys(), after_blobs.keys())) + '%s vs %s' % (before_sizes.keys(), after_sizes.keys())) growth = {'compressed': {}, 'uncompressed': {}} status_code = 0 summary = '' - for package_name in before_blobs: - growth['compressed'][package_name] = (after_blobs[package_name].compressed - - before_blobs[package_name].compressed) + for package_name in before_sizes: + growth['compressed'][package_name] = (after_sizes[package_name].compressed - + before_sizes[package_name].compressed) growth['uncompressed'][package_name] = ( - after_blobs[package_name].uncompressed - - before_blobs[package_name].uncompressed) + after_sizes[package_name].uncompressed - + before_sizes[package_name].uncompressed) if growth['compressed'][package_name] >= _MAX_DELTA_BYTES: if status_code == 1 and not summary: summary = 'Size check failed! The following package(s) are affected:\n' @@ -109,20 +105,21 @@ (args.before_dir, args.after_dir)) test_name = 'sizes' - before_blobs_file = os.path.join(args.before_dir, test_name, - PACKAGES_SIZE_FILE) - after_blobs_file = os.path.join(args.after_dir, test_name, PACKAGES_SIZE_FILE) - if not os.path.isfile(before_blobs_file): - raise Exception('Could not find before blobs file: "%s"' % - (before_blobs_file)) + before_sizes_file = os.path.join(args.before_dir, test_name, + PACKAGES_SIZES_FILE) + after_sizes_file = os.path.join(args.after_dir, test_name, + PACKAGES_SIZES_FILE) + if not os.path.isfile(before_sizes_file): + raise Exception('Could not find before sizes file: "%s"' % + (before_sizes_file)) - if not os.path.isfile(after_blobs_file): - raise Exception('Could not find after blobs file: "%s"' % - (after_blobs_file)) + if not os.path.isfile(after_sizes_file): + raise Exception('Could not find after sizes file: "%s"' % + (after_sizes_file)) test_completed = False try: - growth = ComputePackageDiffs(before_blobs_file, after_blobs_file) + growth = ComputePackageDiffs(before_sizes_file, after_sizes_file) test_completed = True with open(args.results_path, 'wt') as results_file: json.dump(growth, results_file)
diff --git a/build/fuchsia/binary_size_differ_test.py b/build/fuchsia/binary_size_differ_test.py index 205f827..6c015f29 100755 --- a/build/fuchsia/binary_size_differ_test.py +++ b/build/fuchsia/binary_size_differ_test.py
@@ -59,6 +59,13 @@ is_counted=original_blob.is_counted) blobs[package][name] = new_blob + def ChangePackageSize(self, packages, name, increase): + original_package = packages[name] + new_package = binary_sizes.PackageSizes( + compressed=original_package.compressed + increase, + uncompressed=original_package.uncompressed) + packages[name] = new_package + def testComputePackageDiffs(self): # TODO(1309977): Disabled on Windows because Windows doesn't allow opening a # NamedTemporaryFile by name. @@ -68,6 +75,8 @@ before_file.write(_EXAMPLE_BLOBS_BEFORE) before_file.flush() blobs = binary_sizes.ReadPackageBlobsJson(before_file.name) + sizes = binary_sizes.GetPackageSizes(blobs) + binary_sizes.WritePackageSizesJson(before_file.name, sizes) # No change. growth = binary_size_differ.ComputePackageDiffs(before_file.name, @@ -79,10 +88,9 @@ after_file.close() try: # Increase a blob, but below the limit. - other_blobs = copy.deepcopy(blobs) - self.ChangeBlobSize(other_blobs, 'web_engine', 'locales/ru.pak', - 8 * 1024) - binary_sizes.WritePackageBlobsJson(after_file.name, other_blobs) + other_sizes = copy.deepcopy(sizes) + self.ChangePackageSize(other_sizes, 'web_engine', 8 * 1024) + binary_sizes.WritePackageSizesJson(after_file.name, other_sizes) growth = binary_size_differ.ComputePackageDiffs(before_file.name, after_file.name) @@ -90,35 +98,12 @@ self.assertEqual(growth['compressed']['web_engine'], 8 * 1024) # Increase beyond the limit (adds another 8k) - self.ChangeBlobSize(other_blobs, 'web_engine', 'locales/ru.pak', - 8 * 1024 + 1) - binary_sizes.WritePackageBlobsJson(after_file.name, other_blobs) + self.ChangePackageSize(other_sizes, 'web_engine', 8 * 1024 + 1) + binary_sizes.WritePackageSizesJson(after_file.name, other_sizes) growth = binary_size_differ.ComputePackageDiffs(before_file.name, after_file.name) self.assertEqual(growth['status_code'], 1) self.assertEqual(growth['compressed']['web_engine'], 16 * 1024 + 1) - - other_blobs = copy.deepcopy(blobs) - # Increase the limit of multiple blobs. - self.ChangeBlobSize(other_blobs, 'web_engine', 'locales/ru.pak', - (8 * 1024 + 1)) - self.ChangeBlobSize(other_blobs, 'web_engine', 'locales/ta.pak', - (8 * 1024)) - binary_sizes.WritePackageBlobsJson(after_file.name, other_blobs) - growth = binary_size_differ.ComputePackageDiffs(before_file.name, - after_file.name) - self.assertEqual(growth['status_code'], 1) - self.assertEqual(growth['compressed']['web_engine'], 16 * 1024 + 1) - - other_blobs = copy.deepcopy(blobs) - # Increase the limit of is_counted=false does not increase limit. - self.ChangeBlobSize(other_blobs, 'web_engine', 'meta.far', (16 * 1024)) - binary_sizes.WritePackageBlobsJson(after_file.name, other_blobs) - growth = binary_size_differ.ComputePackageDiffs(before_file.name, - after_file.name) - self.assertEqual(growth['status_code'], 0) - self.assertEqual(growth['compressed']['web_engine'], 0) - finally: os.remove(after_file.name)
diff --git a/build/fuchsia/binary_sizes.py b/build/fuchsia/binary_sizes.py index 81a371c9..332eb9d 100755 --- a/build/fuchsia/binary_sizes.py +++ b/build/fuchsia/binary_sizes.py
@@ -24,7 +24,8 @@ from common import GetHostToolPathFromPlatform, GetHostArchFromPlatform from common import SDK_ROOT, DIR_SOURCE_ROOT -PACKAGES_SIZE_FILE = 'package_blobs.json' +PACKAGES_BLOBS_FILE = 'package_blobs.json' +PACKAGES_SIZES_FILE = 'package_sizes.json' # Structure representing the compressed and uncompressed sizes for a Fuchsia # package. @@ -234,6 +235,41 @@ json.dump(formatted_blob_stats_per_package, json_file, indent=2) +def WritePackageSizesJson(json_path, package_sizes): + """Writes package sizes into a human-readable JSON format. + + JSON data is a dictionary of each package name being a key, with + the following keys within the sub-object: + 'compressed': compressed size of the package in bytes. + 'uncompressed': uncompressed size of the package in bytes. + """ + formatted_package_sizes = {} + for package, size_info in package_sizes.items(): + formatted_package_sizes[package] = { + 'uncompressed': size_info.uncompressed, + 'compressed': size_info.compressed + } + with (open(json_path, 'w')) as json_file: + json.dump(formatted_package_sizes, json_file, indent=2) + + +def ReadPackageSizesJson(json_path): + """Reads package_sizes from a given JSON file. + + Opens json file of blob info written by WritePackageSizesJson, + and converts back into package sizes used in this script. + """ + with open(json_path, 'rt') as json_file: + formatted_package_info = json.load(json_file) + + package_sizes = {} + for package, size_info in formatted_package_info.items(): + package_sizes[package] = PackageSizes( + compressed=size_info['compressed'], + uncompressed=size_info['uncompressed']) + return package_sizes + + def GetCompressedSize(file_path): """Measures file size after blobfs compression.""" @@ -492,8 +528,7 @@ ) parser.add_argument( '--sizes-path', - default=os.path.join('fuchsia', 'release', 'size_tests', - 'fyi_sizes.json'), + default=os.path.join('tools', 'fuchsia', 'size_tests', 'fyi_sizes.json'), help='path to package size limits json file. The path is relative to ' 'the workspace src directory') parser.add_argument('--verbose', @@ -562,8 +597,10 @@ test_completed, test_status, timestamp) with open(os.path.join(results_directory, 'perf_results.json'), 'w') as f: json.dump(sizes_histogram, f) - WritePackageBlobsJson(os.path.join(results_directory, PACKAGES_SIZE_FILE), - package_blobs) + WritePackageBlobsJson( + os.path.join(results_directory, PACKAGES_BLOBS_FILE), package_blobs) + WritePackageSizesJson( + os.path.join(results_directory, PACKAGES_SIZES_FILE), package_sizes) if args.isolated_script_test_output: WriteTestResults(args.isolated_script_test_output, test_completed,
diff --git a/build/fuchsia/binary_sizes_test.py b/build/fuchsia/binary_sizes_test.py index d1073543..11fb67f 100755 --- a/build/fuchsia/binary_sizes_test.py +++ b/build/fuchsia/binary_sizes_test.py
@@ -3,6 +3,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import json import os import shutil import subprocess @@ -61,6 +62,7 @@ def tearDownClass(cls): shutil.rmtree(cls.tmpdir) + def testReadAndWritePackageBlobs(self): # TODO(1309977): Disabled on Windows because Windows doesn't allow opening a # NamedTemporaryFile by name. @@ -82,6 +84,52 @@ finally: os.remove(tmp_package_file.name) + def testReadAndWritePackageSizes(self): + # TODO(1309977): Disabled on Windows because Windows doesn't allow opening a + # NamedTemporaryFile by name. + if os.name == 'nt': + return + with tempfile.NamedTemporaryFile(mode='w') as tmp_file: + tmp_file.write(_EXAMPLE_BLOBS) + tmp_file.flush() + blobs = binary_sizes.ReadPackageBlobsJson(tmp_file.name) + + sizes = binary_sizes.GetPackageSizes(blobs) + + new_sizes = {} + with tempfile.NamedTemporaryFile(mode='w') as tmp_file: + binary_sizes.WritePackageSizesJson(tmp_file.name, sizes) + new_sizes = binary_sizes.ReadPackageSizesJson(tmp_file.name) + self.assertEqual(new_sizes, sizes) + self.assertIn('web_engine', new_sizes) + + def testGetPackageSizesUsesBlobMerklesForCount(self): + # TODO(1309977): Disabled on Windows because Windows doesn't allow opening a + # NamedTemporaryFile by name. + if os.name == 'nt': + return + blobs = json.loads(_EXAMPLE_BLOBS) + + # Make a duplicate of the last blob. + last_blob = dict(blobs['web_engine'][-1]) + blobs['cast_runner'] = [] + last_blob['path'] = 'foo' # Give a non-sense name, but keep merkle. + + # If the merkle is the same, the blob_count increases by 1. + # This effectively reduces the size of the blobs size by half. + # In both packages, despite it appearing in both and under different + # names. + blobs['cast_runner'].append(last_blob) + + with tempfile.NamedTemporaryFile(mode='w') as tmp_file: + tmp_file.write(json.dumps(blobs)) + tmp_file.flush() + blobs = binary_sizes.ReadPackageBlobsJson(tmp_file.name) + + sizes = binary_sizes.GetPackageSizes(blobs) + + self.assertEqual(sizes['cast_runner'].compressed, last_blob['size'] / 2) + if __name__ == '__main__': unittest.main()
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index e2c60c8e..26c3923 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -8.20220607.1.1 +8.20220607.2.1
diff --git a/build/toolchain/win/ml.py b/build/toolchain/win/ml.py new file mode 100755 index 0000000..8da910b --- /dev/null +++ b/build/toolchain/win/ml.py
@@ -0,0 +1,286 @@ +#!/usr/bin/env python +# Copyright 2018 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +"""Wraps ml.exe or ml64.exe and postprocesses the output to be deterministic. +Sets timestamp in .obj file to 0, hence incompatible with link.exe /incremental. + +Use by prefixing the ml(64).exe invocation with this script: + python ml.py ml.exe [args...]""" + +import array +import collections +import struct +import subprocess +import sys + + +class Struct(object): + """A thin wrapper around the struct module that returns a namedtuple""" + + def __init__(self, name, *args): + """Pass the name of the return type, and then an interleaved list of + format strings as used by the struct module and of field names.""" + self.fmt = '<' + ''.join(args[0::2]) + self.type = collections.namedtuple(name, args[1::2]) + + def pack_into(self, buffer, offset, data): + return struct.pack_into(self.fmt, buffer, offset, *data) + + def unpack_from(self, buffer, offset=0): + return self.type(*struct.unpack_from(self.fmt, buffer, offset)) + + def size(self): + return struct.calcsize(self.fmt) + + +def Subtract(nt, **kwargs): + """Subtract(nt, f=2) returns a new namedtuple with 2 subtracted from nt.f""" + return nt._replace(**{k: getattr(nt, k) - v for k, v in kwargs.items()}) + + +def MakeDeterministic(objdata): + # Takes data produced by ml(64).exe (without any special flags) and + # 1. Sets the timestamp to 0 + # 2. Strips the .debug$S section (which contains an unwanted absolute path) + + # This makes several assumptions about ml's output: + # - Section data is in the same order as the corresponding section headers: + # section headers preceding the .debug$S section header have their data + # preceding the .debug$S section data; likewise for section headers + # following the .debug$S section. + # - The .debug$S section contains only the absolute path to the obj file and + # nothing else, in particular there's only a single entry in the symbol + # table referring to the .debug$S section. + # - There are no COFF line number entries. + # - There's no IMAGE_SYM_CLASS_CLR_TOKEN symbol. + # These seem to hold in practice; if they stop holding this script needs to + # become smarter. + + objdata = array.array('b', objdata) # Writable, e.g. via struct.pack_into. + + # Read coff header. + COFFHEADER = Struct('COFFHEADER', 'H', 'Machine', 'H', 'NumberOfSections', + 'I', 'TimeDateStamp', 'I', 'PointerToSymbolTable', 'I', + 'NumberOfSymbols', 'H', 'SizeOfOptionalHeader', 'H', + 'Characteristics') + coff_header = COFFHEADER.unpack_from(objdata) + assert coff_header.SizeOfOptionalHeader == 0 # Only set for binaries. + + # Read section headers following coff header. + SECTIONHEADER = Struct('SECTIONHEADER', '8s', 'Name', 'I', 'VirtualSize', 'I', + 'VirtualAddress', 'I', 'SizeOfRawData', 'I', + 'PointerToRawData', 'I', 'PointerToRelocations', 'I', + 'PointerToLineNumbers', 'H', 'NumberOfRelocations', + 'H', 'NumberOfLineNumbers', 'I', 'Characteristics') + section_headers = [] + debug_section_index = -1 + for i in range(0, coff_header.NumberOfSections): + section_header = SECTIONHEADER.unpack_from(objdata, + offset=COFFHEADER.size() + + i * SECTIONHEADER.size()) + assert not section_header[0].startswith(b'/') # Support short names only. + section_headers.append(section_header) + + if section_header.Name == b'.debug$S': + assert debug_section_index == -1 + debug_section_index = i + assert debug_section_index != -1 + + data_start = COFFHEADER.size() + len(section_headers) * SECTIONHEADER.size() + + # Verify the .debug$S section looks like we expect. + assert section_headers[debug_section_index].Name == b'.debug$S' + assert section_headers[debug_section_index].VirtualSize == 0 + assert section_headers[debug_section_index].VirtualAddress == 0 + debug_size = section_headers[debug_section_index].SizeOfRawData + debug_offset = section_headers[debug_section_index].PointerToRawData + assert section_headers[debug_section_index].PointerToRelocations == 0 + assert section_headers[debug_section_index].PointerToLineNumbers == 0 + assert section_headers[debug_section_index].NumberOfRelocations == 0 + assert section_headers[debug_section_index].NumberOfLineNumbers == 0 + + # Make sure sections in front of .debug$S have their data preceding it. + for header in section_headers[:debug_section_index]: + assert header.PointerToRawData < debug_offset + assert header.PointerToRelocations < debug_offset + assert header.PointerToLineNumbers < debug_offset + + # Make sure sections after of .debug$S have their data following it. + for header in section_headers[debug_section_index + 1:]: + # Make sure the .debug$S data is at the very end of section data: + assert header.PointerToRawData > debug_offset + assert header.PointerToRelocations == 0 + assert header.PointerToLineNumbers == 0 + + # Make sure the first non-empty section's data starts right after the section + # headers. + for section_header in section_headers: + if section_header.PointerToRawData == 0: + assert section_header.PointerToRelocations == 0 + assert section_header.PointerToLineNumbers == 0 + continue + assert section_header.PointerToRawData == data_start + break + + # Make sure the symbol table (and hence, string table) appear after the last + # section: + assert ( + coff_header.PointerToSymbolTable >= + section_headers[-1].PointerToRawData + section_headers[-1].SizeOfRawData) + + # The symbol table contains a symbol for the no-longer-present .debug$S + # section. If we leave it there, lld-link will complain: + # + # lld-link: error: .debug$S should not refer to non-existent section 5 + # + # so we need to remove that symbol table entry as well. This shifts symbol + # entries around and we need to update symbol table indices in: + # - relocations + # - line number records (never present) + # - one aux symbol entry (IMAGE_SYM_CLASS_CLR_TOKEN; not present in ml output) + SYM = Struct( + 'SYM', + '8s', + 'Name', + 'I', + 'Value', + 'h', + 'SectionNumber', # Note: Signed! + 'H', + 'Type', + 'B', + 'StorageClass', + 'B', + 'NumberOfAuxSymbols') + i = 0 + debug_sym = -1 + while i < coff_header.NumberOfSymbols: + sym_offset = coff_header.PointerToSymbolTable + i * SYM.size() + sym = SYM.unpack_from(objdata, sym_offset) + + # 107 is IMAGE_SYM_CLASS_CLR_TOKEN, which has aux entry "CLR Token + # Definition", which contains a symbol index. Check it's never present. + assert sym.StorageClass != 107 + + # Note: sym.SectionNumber is 1-based, debug_section_index is 0-based. + if sym.SectionNumber - 1 == debug_section_index: + assert debug_sym == -1, 'more than one .debug$S symbol found' + debug_sym = i + # Make sure the .debug$S symbol looks like we expect. + # In particular, it should have exactly one aux symbol. + assert sym.Name == b'.debug$S' + assert sym.Value == 0 + assert sym.Type == 0 + assert sym.StorageClass == 3 + assert sym.NumberOfAuxSymbols == 1 + elif sym.SectionNumber > debug_section_index: + sym = Subtract(sym, SectionNumber=1) + SYM.pack_into(objdata, sym_offset, sym) + i += 1 + sym.NumberOfAuxSymbols + assert debug_sym != -1, '.debug$S symbol not found' + + # Note: Usually the .debug$S section is the last, but for files saying + # `includelib foo.lib`, like safe_terminate_process.asm in 32-bit builds, + # this isn't true: .drectve is after .debug$S. + + # Update symbol table indices in relocations. + # There are a few processor types that have one or two relocation types + # where SymbolTableIndex has a different meaning, but not for x86. + REL = Struct('REL', 'I', 'VirtualAddress', 'I', 'SymbolTableIndex', 'H', + 'Type') + for header in section_headers[0:debug_section_index]: + for j in range(0, header.NumberOfRelocations): + rel_offset = header.PointerToRelocations + j * REL.size() + rel = REL.unpack_from(objdata, rel_offset) + assert rel.SymbolTableIndex != debug_sym + if rel.SymbolTableIndex > debug_sym: + rel = Subtract(rel, SymbolTableIndex=2) + REL.pack_into(objdata, rel_offset, rel) + + # Update symbol table indices in line numbers -- just check they don't exist. + for header in section_headers: + assert header.NumberOfLineNumbers == 0 + + # Now that all indices are updated, remove the symbol table entry referring to + # .debug$S and its aux entry. + del objdata[coff_header.PointerToSymbolTable + + debug_sym * SYM.size():coff_header.PointerToSymbolTable + + (debug_sym + 2) * SYM.size()] + + # Now we know that it's safe to write out the input data, with just the + # timestamp overwritten to 0, the last section header cut out (and the + # offsets of all other section headers decremented by the size of that + # one section header), and the last section's data cut out. The symbol + # table offset needs to be reduced by one section header and the size of + # the missing section. + # (The COFF spec only requires on-disk sections to be aligned in image files, + # for obj files it's not required. If that wasn't the case, deleting slices + # if data would not generally be safe.) + + # Update section offsets and remove .debug$S section data. + for i in range(0, debug_section_index): + header = section_headers[i] + if header.SizeOfRawData: + header = Subtract(header, PointerToRawData=SECTIONHEADER.size()) + if header.NumberOfRelocations: + header = Subtract(header, PointerToRelocations=SECTIONHEADER.size()) + if header.NumberOfLineNumbers: + header = Subtract(header, PointerToLineNumbers=SECTIONHEADER.size()) + SECTIONHEADER.pack_into(objdata, + COFFHEADER.size() + i * SECTIONHEADER.size(), + header) + for i in range(debug_section_index + 1, len(section_headers)): + header = section_headers[i] + shift = SECTIONHEADER.size() + debug_size + if header.SizeOfRawData: + header = Subtract(header, PointerToRawData=shift) + if header.NumberOfRelocations: + header = Subtract(header, PointerToRelocations=shift) + if header.NumberOfLineNumbers: + header = Subtract(header, PointerToLineNumbers=shift) + SECTIONHEADER.pack_into(objdata, + COFFHEADER.size() + i * SECTIONHEADER.size(), + header) + + del objdata[debug_offset:debug_offset + debug_size] + + # Finally, remove .debug$S section header and update coff header. + coff_header = coff_header._replace(TimeDateStamp=0) + coff_header = Subtract(coff_header, + NumberOfSections=1, + PointerToSymbolTable=SECTIONHEADER.size() + debug_size, + NumberOfSymbols=2) + COFFHEADER.pack_into(objdata, 0, coff_header) + + del objdata[COFFHEADER.size() + + debug_section_index * SECTIONHEADER.size():COFFHEADER.size() + + (debug_section_index + 1) * SECTIONHEADER.size()] + + # All done! + if sys.version_info.major == 2: + return objdata.tostring() + else: + return objdata.tobytes() + + +def main(): + ml_result = subprocess.call(sys.argv[1:]) + if ml_result != 0: + return ml_result + + objfile = None + for i in range(1, len(sys.argv)): + if sys.argv[i].startswith('/Fo'): + objfile = sys.argv[i][len('/Fo'):] + assert objfile, 'failed to find ml output' + + with open(objfile, 'rb') as f: + objdata = f.read() + objdata = MakeDeterministic(objdata) + with open(objfile, 'wb') as f: + f.write(objdata) + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/build/toolchain/win/toolchain.gni b/build/toolchain/win/toolchain.gni index 9cdcc6bf..021e0519 100644 --- a/build/toolchain/win/toolchain.gni +++ b/build/toolchain/win/toolchain.gni
@@ -254,12 +254,20 @@ ml = "armasm64.exe" } } else { - prefix = rebase_path("$clang_base_path/bin", root_build_dir) - ml = "$prefix/llvm-ml.exe" - if (toolchain_args.current_cpu == "x64") { - ml += " --m64" + if (toolchain_is_clang) { + prefix = rebase_path("$clang_base_path/bin", root_build_dir) + ml = "$prefix/llvm-ml.exe" + if (toolchain_args.current_cpu == "x64") { + ml += " -m64" + } else { + ml += " -m32" + } } else { - ml += " --m32" + if (toolchain_args.current_cpu == "x64") { + ml = "ml64.exe" + } else { + ml = "ml.exe" + } } } @@ -271,6 +279,13 @@ if (toolchain_args.current_cpu != "arm64") { ml += " /c" } + if (use_lld && !toolchain_is_clang) { + # Wrap ml(64).exe with a script that makes its output deterministic. + # It's lld only because the script zaps obj Timestamp which + # link.exe /incremental looks at. + ml_py = rebase_path("//build/toolchain/win/ml.py", root_build_dir) + ml = "$python_path $ml_py $ml" + } } if (toolchain_args.current_cpu != "arm64" || toolchain_is_clang) { command = "$python_path $_tool_wrapper_path asm-wrapper $env $ml {{defines}} {{include_dirs}} {{asmflags}} {{source}}"
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java index 57b15569..36a8688 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java
@@ -259,9 +259,7 @@ } if (mMode == TabListMode.GRID && selectionDelegateProvider == null) { - // TODO(crbug.com/964406): unregister the listener when we don't need it. mGlobalLayoutListener = this::updateThumbnailAndSpanCount; - mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener); } } @@ -393,11 +391,17 @@ } void prepareTabSwitcherView() { + if (mGlobalLayoutListener != null) { + mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener); + } mRecyclerView.prepareTabSwitcherView(); mMediator.prepareTabSwitcherView(); } void postHiding() { + if (mGlobalLayoutListener != null) { + mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener); + } mRecyclerView.postHiding(); mMediator.postHiding(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java index 718596dc..144d9531 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java
@@ -299,11 +299,6 @@ } @Override - public boolean isIntentToInstantApp(Intent intent) { - return InstantAppsHandler.isIntentToInstantApp(intent); - } - - @Override public boolean isIntentToAutofillAssistant(Intent intent) { return AutofillAssistantFacade.isAutofillAssistantByIntentTriggeringEnabled(intent); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java index 0c3b786..df7d295 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java
@@ -60,12 +60,6 @@ private static final String BROWSER_LAUNCH_REASON = "com.google.android.gms.instantapps.BROWSER_LAUNCH_REASON"; - private static final String SUPERVISOR_PKG = "com.google.android.instantapps.supervisor"; - - private static final String[] SUPERVISOR_START_ACTIONS = { - "com.google.android.instantapps.START", "com.google.android.instantapps.nmr1.INSTALL", - "com.google.android.instantapps.nmr1.VIEW"}; - // Only two possible call sources for fallback intents, set boundary at n+1. private static final int SOURCE_BOUNDARY = 3; @@ -80,23 +74,6 @@ } /** - * Checks whether {@param intent} is for an Instant App. Considers both package and actions that - * would resolve to Supervisor. - * @return Whether the given intent is going to open an Instant App. - */ - public static boolean isIntentToInstantApp(Intent intent) { - if (SUPERVISOR_PKG.equals(intent.getPackage())) return true; - - String intentAction = intent.getAction(); - for (String action : SUPERVISOR_START_ACTIONS) { - if (action.equals(intentAction)) { - return true; - } - } - return false; - } - - /** * Record how long the handleIntent() method took. * @param startTime The timestamp for handleIntent start time. */
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImplTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImplTest.java index 4227e04e..2b2e4dad2 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImplTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImplTest.java
@@ -165,52 +165,6 @@ @Test @SmallTest - public void testIsIntentToInstantApp() { - // Check that the delegate correctly distinguishes instant app intents from others. - String vanillaUrl = "http://www.example.com"; - Intent vanillaIntent = new Intent(Intent.ACTION_VIEW); - vanillaIntent.setData(Uri.parse(vanillaUrl)); - - String instantAppIntentUrl = "intent://buzzfeed.com/tasty#Intent;scheme=http;" - + "package=com.google.android.instantapps.supervisor;" - + "action=com.google.android.instantapps.START;" - + "S.com.google.android.instantapps.FALLBACK_PACKAGE=" - + "com.android.chrome;S.com.google.android.instantapps.INSTANT_APP_PACKAGE=" - + "com.yelp.android;S.android.intent.extra.REFERRER_NAME=" - + "https%3A%2F%2Fwww.google.com;end"; - Intent instantAppIntent; - try { - instantAppIntent = Intent.parseUri(instantAppIntentUrl, Intent.URI_INTENT_SCHEME); - } catch (Exception ex) { - Assert.assertTrue(false); - return; - } - - Assert.assertFalse(mExternalNavigationDelegateImpl.isIntentToInstantApp(vanillaIntent)); - Assert.assertTrue(mExternalNavigationDelegateImpl.isIntentToInstantApp(instantAppIntent)); - - // Check that Supervisor is detected by action even without package. - for (String action : SUPERVISOR_START_ACTIONS) { - String intentWithoutPackageUrl = "intent://buzzfeed.com/tasty#Intent;scheme=http;" - + "action=" + action + ";" - + "S.com.google.android.instantapps.FALLBACK_PACKAGE=" - + "com.android.chrome;S.com.google.android.instantapps.INSTANT_APP_PACKAGE=" - + "com.yelp.android;S.android.intent.extra.REFERRER_NAME=" - + "https%3A%2F%2Fwww.google.com;end"; - try { - instantAppIntent = - Intent.parseUri(intentWithoutPackageUrl, Intent.URI_INTENT_SCHEME); - } catch (Exception ex) { - Assert.assertTrue(false); - return; - } - Assert.assertTrue( - mExternalNavigationDelegateImpl.isIntentToInstantApp(instantAppIntent)); - } - } - - @Test - @SmallTest public void testMaybeAdjustInstantAppExtras() { String url = "http://www.example.com"; Intent intent = new Intent(Intent.ACTION_VIEW);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManagerUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManagerUnitTest.java index d41f512..0bf46c7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManagerUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManagerUnitTest.java
@@ -12,6 +12,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import android.content.Context; +import android.support.test.InstrumentationRegistry; import android.util.SparseArray; import android.view.View; @@ -59,6 +61,7 @@ ListObserver<Void> mListObserver; private ModelList mSuggestionModels; + private Context mContext; private DropdownItemViewInfoListManager mManager; @Before @@ -70,7 +73,9 @@ mSuggestionModels = new ModelList(); mSuggestionModels.addObserver(mListObserver); - mManager = new DropdownItemViewInfoListManager(mSuggestionModels); + + mContext = InstrumentationRegistry.getContext(); + mManager = new DropdownItemViewInfoListManager(mSuggestionModels, mContext); } /**
diff --git a/chrome/app/chrome_command_ids.h b/chrome/app/chrome_command_ids.h index 0764b3fbc..47efe5f 100644 --- a/chrome/app/chrome_command_ids.h +++ b/chrome/app/chrome_command_ids.h
@@ -462,6 +462,10 @@ #define IDC_DEBUG_PRINT_VIEW_TREE_DETAILS 52512 // Please leave a gap here for new debug commands. +// Autofill context menu commands +#define IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_FIRST 53000 +#define IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_LAST 53250 + // NOTE: The last valid command value is 57343 (0xDFFF) // See http://msdn.microsoft.com/en-us/library/t2zechd4(VS.71).aspx
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index a458747..9c978575 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -1962,6 +1962,9 @@ <message name="IDS_SETTINGS_MANAGE_CERTIFICATES_DESCRIPTION" desc="Secondary, continued explanation of how to manage SSL certificates and settings in Privacy options"> Manage HTTPS/SSL certificates and settings </message> + <message name="IDS_SETTINGS_MANAGE" desc="Text displayed on a button, which when clicked opens the Extensions subpage for managing an extension"> + Manage + </message> <message name="IDS_SETTINGS_SECURE_DNS" desc="Text for secure DNS toggle in Privacy options"> Use secure DNS </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_MANAGE.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_MANAGE.png.sha1 new file mode 100644 index 0000000..3022f7a --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_MANAGE.png.sha1
@@ -0,0 +1 @@ +c56284f1ee244e37a4b5e0419aa4cd0e74f56822 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 247e816..b35b79f 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2497,8 +2497,6 @@ "android/background_task_scheduler/chrome_background_task_factory.h", "android/background_task_scheduler/proxy_native_task.cc", "android/background_task_scheduler/proxy_native_task.h", - "android/bookmarks/bookmark_bridge.cc", - "android/bookmarks/bookmark_bridge.h", "android/bookmarks/partner_bookmarks_reader.cc", "android/bookmarks/partner_bookmarks_reader.h", "android/bookmarks/partner_bookmarks_shim.cc", @@ -2893,6 +2891,8 @@ "banners/android/chrome_app_banner_manager_android.cc", "banners/android/chrome_app_banner_manager_android.h", "bluetooth/android/bluetooth_bridge.cc", + "bookmarks/android/bookmark_bridge.cc", + "bookmarks/android/bookmark_bridge.h", "browser_process_platform_part_android.cc", "browser_process_platform_part_android.h", "chrome_browser_field_trials_mobile.cc", @@ -3518,6 +3518,8 @@ "apps/intent_helper/page_transition_util.h", "autocomplete/tab_matcher_desktop.cc", "autocomplete/tab_matcher_desktop.h", + "autofill/autofill_context_menu_manager.cc", + "autofill/autofill_context_menu_manager.h", "autofill_assistant/password_change/apc_client.cc", "autofill_assistant/password_change/apc_client.h", "autofill_assistant/password_change/apc_client_impl.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 7990603..813bf216 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -7989,6 +7989,12 @@ #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS_ASH) + {"partial-split", flag_descriptions::kPartialSplit, + flag_descriptions::kPartialSplitDescription, kOsCrOS, + FEATURE_VALUE_TYPE(ash::features::kPartialSplit)}, +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + +#if BUILDFLAG(IS_CHROMEOS_ASH) {"performant-split-view-resizing", flag_descriptions::kPerformantSplitViewResizing, flag_descriptions::kPerformantSplitViewResizingDescription, kOsCrOS,
diff --git a/chrome/browser/accessibility/live_caption_unavailability_notifier.cc b/chrome/browser/accessibility/live_caption_unavailability_notifier.cc index 6ff4f3b..a0e813a 100644 --- a/chrome/browser/accessibility/live_caption_unavailability_notifier.cc +++ b/chrome/browser/accessibility/live_caption_unavailability_notifier.cc
@@ -12,8 +12,7 @@ #include "chrome/browser/accessibility/caption_bubble_context_browser.h" #include "chrome/browser/accessibility/live_caption_controller_factory.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser_navigator.h" -#include "chrome/browser/ui/browser_navigator_params.h" +#include "chrome/browser/ui/chrome_pages.h" #include "components/live_caption/live_caption_controller.h" #include "components/live_caption/pref_names.h" #include "components/live_caption/views/caption_bubble.h" @@ -165,12 +164,10 @@ void LiveCaptionUnavailabilityNotifier:: OnMediaFoundationRendererErrorClicked() { - NavigateParams params( - Profile::FromBrowserContext(render_frame_host()->GetBrowserContext()), - GURL("chrome://settings/content/protectedContent"), - ui::PAGE_TRANSITION_LINK); - params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; - Navigate(¶ms); + Profile* profile = + Profile::FromBrowserContext(render_frame_host()->GetBrowserContext()); + chrome::ShowSiteSettings( + profile, render_frame_host()->GetLastCommittedOrigin().GetURL()); } void LiveCaptionUnavailabilityNotifier::
diff --git a/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.cc b/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.cc index fb8cb50..d053c73 100644 --- a/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.cc +++ b/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.cc
@@ -43,7 +43,7 @@ void ArcContentFileSystemAsyncFileUtil::CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { NOTIMPLEMENTED(); base::ThreadTaskRunnerHandle::Get()->PostTask(
diff --git a/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.h b/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.h index 680fed35..a879e45 100644 --- a/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.h +++ b/chrome/browser/ash/arc/fileapi/arc_content_file_system_async_file_util.h
@@ -26,7 +26,7 @@ void CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists( std::unique_ptr<storage::FileSystemOperationContext> context,
diff --git a/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.cc b/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.cc index 6e377f97..df640cdf 100644 --- a/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.cc +++ b/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.cc
@@ -295,7 +295,7 @@ void ArcDocumentsProviderAsyncFileUtil::CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(nya): Implement this function if it is ever called.
diff --git a/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.h b/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.h index b7bde1d..4ae5c5d 100644 --- a/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.h +++ b/chrome/browser/ash/arc/fileapi/arc_documents_provider_async_file_util.h
@@ -36,7 +36,7 @@ void CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists( std::unique_ptr<storage::FileSystemOperationContext> context,
diff --git a/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.cc b/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.cc index 9ea07a7..e5286dd 100644 --- a/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.cc +++ b/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ash/arc/input_overlay/ui/input_menu_view.h" +#include "ash/components/arc/compat_mode/style/arc_color_provider.h" #include "ash/login/ui/views_utils.h" #include "ash/public/cpp/new_window_delegate.h" #include "ash/style/ash_color_provider.h" @@ -20,6 +21,7 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_types.h" +#include "ui/chromeos/styles/cros_styles.h" #include "ui/gfx/font.h" #include "ui/gfx/font_list.h" #include "ui/gfx/paint_vector_icon.h" @@ -53,12 +55,23 @@ constexpr int kCloseButtonSide = 12; constexpr int kCornerRadius = 16; constexpr int kSideInset = 20; +constexpr int kToggleInset = 16; +constexpr int kCloseInset = 8; // String styles/sizes. constexpr char kGoogleSansFont[] = "Google Sans"; constexpr int kTitleFontSize = 20; constexpr int kBodyFontSize = 13; +// About Alpha style. +constexpr int kAlphaFontSize = 11; +constexpr int kAlphaCornerRadius = 4; +constexpr int kAlphaHeight = 16; +constexpr int kAlphaSidePadding = 4; +constexpr int kAlphaLeftMargin = 12; +constexpr SkColor kAlphaBgColor = SkColorSetA(gfx::kGoogleBlue300, 0x4D); +constexpr SkColor kAlphaTextColor = gfx::kGoogleBlue200; + constexpr char kFeedbackUrl[] = "https://docs.google.com/forms/d/e/" "1FAIpQLSfL3ttPmopJj65P4EKr--SA18Sc9bbQVMnd0oueMhJu_42TbA/" @@ -163,7 +176,7 @@ auto header_view = std::make_unique<views::View>(); header_view->SetLayoutManager(std::make_unique<views::FlexLayout>()) ->SetOrientation(views::LayoutOrientation::kHorizontal) - .SetCrossAxisAlignment(views::LayoutAlignment::kStretch); + .SetCrossAxisAlignment(views::LayoutAlignment::kCenter); auto* menu_title = ash::login_views_utils::CreateBubbleLabel( l10n_util::GetStringUTF16(IDS_INPUT_OVERLAY_GAME_CONTROLS_ALPHA), @@ -174,6 +187,20 @@ /*line_height=*/kHeaderMinHeight); header_view->AddChildView(menu_title); + auto* alpha_label = ash::login_views_utils::CreateBubbleLabel( + l10n_util::GetStringUTF16(IDS_INPUT_OVERLAY_RELEASE_ALPHA), + /*view_defining_max_width=*/nullptr, kAlphaTextColor, + gfx::FontList({ash::login_views_utils::kGoogleSansFont}, + gfx::Font::FontStyle::NORMAL, kAlphaFontSize, + gfx::Font::Weight::MEDIUM)); + alpha_label->SetHorizontalAlignment(gfx::ALIGN_CENTER); + alpha_label->SetPreferredSize(gfx::Size( + alpha_label->GetPreferredSize().width() + 2 * kAlphaSidePadding, + kAlphaHeight)); + alpha_label->SetBackground( + views::CreateRoundedRectBackground(kAlphaBgColor, kAlphaCornerRadius)); + header_view->AddChildView(std::move(alpha_label)); + game_control_toggle_ = header_view->AddChildView(std::make_unique<views::ToggleButton>( base::BindRepeating(&InputMenuView::OnToggleGameControlPressed, @@ -198,11 +225,15 @@ close_button->SetAccessibleName( l10n_util::GetStringUTF16(IDS_INPUT_OVERLAY_ACCESSIBILITY_ALPHA)); close_button_ = header_view->AddChildView(std::move(close_button)); - menu_title->SetBorder(views::CreateEmptyBorder(CalculateInsets( - header_view.get(), /*left=*/20, /*right=*/8, /*other_spacing=*/16))); + menu_title->SetBorder( + views::CreateEmptyBorder(gfx::Insets::TLBR(0, kSideInset, 0, 0))); game_control_toggle_->SetBorder( - views::CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 0, 16))); + views::CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 0, kToggleInset))); SetCustomToggleColor(game_control_toggle_); + alpha_label->SetProperty( + views::kMarginsKey, + CalculateInsets(header_view.get(), kAlphaLeftMargin, /*right=*/0, + /*other_spacing=*/kCloseInset)); AddChildView(std::move(header_view)); AddChildView(BuildSeparator());
diff --git a/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.h b/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.h index afe748d8..60e7c7d 100644 --- a/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.h +++ b/chrome/browser/ash/arc/input_overlay/ui/input_menu_view.h
@@ -24,7 +24,7 @@ // // The class reports back to DisplayOverlayController, who owns this. // +---------------------------------+ -// | Game controls [ o] [x] | +// | Game Control |Alpha| [ o] [x] | // | | // | Key mapping [Customize] | // | |
diff --git a/chrome/browser/ash/file_manager/extract_io_task.cc b/chrome/browser/ash/file_manager/extract_io_task.cc index 7d183813..025eab5d 100644 --- a/chrome/browser/ash/file_manager/extract_io_task.cc +++ b/chrome/browser/ash/file_manager/extract_io_task.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/ash/file_manager/filesystem_api_util.h" #include "chrome/browser/ash/file_manager/path_util.h" #include "chrome/browser/chromeos/fileapi/file_system_backend.h" +#include "chrome/browser/platform_util.h" #include "components/services/unzip/content/unzip_service.h" #include "components/services/unzip/public/mojom/unzipper.mojom.h" #include "third_party/cros_system_api/constants/cryptohome.h" @@ -70,8 +71,12 @@ progress_callback_.Run(progress_); } -void ExtractIOTask::FinishedExtraction(bool success) { +void ExtractIOTask::FinishedExtraction(base::FilePath directory, bool success) { progress_.state = success ? State::kSuccess : State::kError; + if (success) { + // Open a new window to show the extracted content. + platform_util::ShowItemInFolder(profile_, directory); + } DCHECK_GT(extractCount_, 0); if (--extractCount_ == 0) { RecordUmaExtractStatus(progress_.state == State::kSuccess @@ -104,7 +109,7 @@ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&SetDirectoryPermissions, destination_directory, success), base::BindOnce(&ExtractIOTask::FinishedExtraction, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetWeakPtr(), destination_directory)); } void ExtractIOTask::ExtractIntoNewDirectory(
diff --git a/chrome/browser/ash/file_manager/extract_io_task.h b/chrome/browser/ash/file_manager/extract_io_task.h index 347f67e6..56cca7cc 100644 --- a/chrome/browser/ash/file_manager/extract_io_task.h +++ b/chrome/browser/ash/file_manager/extract_io_task.h
@@ -58,7 +58,7 @@ private: void Complete(); - void FinishedExtraction(bool success); + void FinishedExtraction(base::FilePath directory, bool success); void ZipExtractCallback(base::FilePath destination_directory, bool success);
diff --git a/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.cc b/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.cc index d72e21a9..d72bd1d 100644 --- a/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.cc +++ b/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.cc
@@ -307,7 +307,7 @@ void ProviderAsyncFileUtil::CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if ((file_flags & base::File::FLAG_CREATE) ||
diff --git a/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.h b/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.h index 475f884..0c54e2b1 100644 --- a/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.h +++ b/chrome/browser/ash/file_system_provider/fileapi/provider_async_file_util.h
@@ -41,7 +41,7 @@ void CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists( std::unique_ptr<storage::FileSystemOperationContext> context,
diff --git a/chrome/browser/ash/login/quick_unlock/auth_token.cc b/chrome/browser/ash/login/quick_unlock/auth_token.cc index 420933aa..185f074 100644 --- a/chrome/browser/ash/login/quick_unlock/auth_token.cc +++ b/chrome/browser/ash/login/quick_unlock/auth_token.cc
@@ -31,6 +31,12 @@ return identifier_.ToString(); } +absl::optional<base::UnguessableToken> AuthToken::GetUnguessableToken() const { + if (!user_context_) + return absl::nullopt; + return identifier_; +} + absl::optional<base::TimeDelta> AuthToken::GetAge() const { if (!user_context_) return absl::nullopt;
diff --git a/chrome/browser/ash/login/quick_unlock/auth_token.h b/chrome/browser/ash/login/quick_unlock/auth_token.h index f139053..b270184 100644 --- a/chrome/browser/ash/login/quick_unlock/auth_token.h +++ b/chrome/browser/ash/login/quick_unlock/auth_token.h
@@ -38,6 +38,10 @@ // instance has not changed. Returns nullopt if Reset() was called. absl::optional<std::string> Identifier() const; + // Similar to the above, but returns the strongly typed + // `base::UnguessableToken` instead + absl::optional<base::UnguessableToken> GetUnguessableToken() const; + // Time since token was created or `absl::nullopt` if Reset() was called. absl::optional<base::TimeDelta> GetAge() const;
diff --git a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.cc b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.cc index d510cdc..5c2942a5 100644 --- a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.cc +++ b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.cc
@@ -4,8 +4,6 @@ #include "chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.h" -#include "base/check.h" - namespace ash { namespace smb_client { @@ -16,42 +14,24 @@ active_account_name_(credentials_manager->GetActiveAccount()), active_account_changed_callback_( std::move(active_account_changed_callback)) { - DCHECK(credentials_manager_); credentials_manager_->AddObserver(this); } SmbKerberosCredentialsUpdater::~SmbKerberosCredentialsUpdater() { - DCHECK(credentials_manager_); credentials_manager_->RemoveObserver(this); } -bool SmbKerberosCredentialsUpdater::IsKerberosEnabled() const { - DCHECK(credentials_manager_); - return credentials_manager_->IsKerberosEnabled(); -} - -void SmbKerberosCredentialsUpdater::OnKerberosEnabledStateChanged() { - DCHECK(credentials_manager_); - - // If Kerberos got disabled by policy, set `active_account_name_` to empty - // string, which means no account is available. - UpdateActiveAccount(credentials_manager_->IsKerberosEnabled() - ? credentials_manager_->GetActiveAccount() - : ""); -} - void SmbKerberosCredentialsUpdater::OnAccountsChanged() { - DCHECK(credentials_manager_); - UpdateActiveAccount(credentials_manager_->GetActiveAccount()); -} - -void SmbKerberosCredentialsUpdater::UpdateActiveAccount( - const std::string& account_name) { + const std::string account_name = credentials_manager_->GetActiveAccount(); if (active_account_name_ != account_name) { active_account_name_ = account_name; active_account_changed_callback_.Run(account_name); } } +bool SmbKerberosCredentialsUpdater::IsKerberosEnabled() const { + return credentials_manager_->IsKerberosEnabled(); +} + } // namespace smb_client } // namespace ash
diff --git a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.h b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.h index 1e0d122..dd01910 100644 --- a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.h +++ b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater.h
@@ -9,15 +9,13 @@ #include <string> #include "base/callback.h" -#include "base/memory/raw_ptr.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager.h" namespace ash { namespace smb_client { // Updates Kerberos credentials in SmbService after receiving a -// `OnKerberosEnabledStateChanged` or `OnAccountsChanged` notification from -// `KerberosCredentialsManager`. +// OnAccountsChanged notification from KerberosCredentialsManager. class SmbKerberosCredentialsUpdater : public KerberosCredentialsManager::Observer { public: @@ -27,12 +25,10 @@ SmbKerberosCredentialsUpdater( KerberosCredentialsManager* credentials_manager, ActiveAccountChangedCallback active_account_changed_callback); - ~SmbKerberosCredentialsUpdater() override; - - // Disallow copy and assignment. SmbKerberosCredentialsUpdater(const SmbKerberosCredentialsUpdater&) = delete; SmbKerberosCredentialsUpdater& operator=( const SmbKerberosCredentialsUpdater&) = delete; + ~SmbKerberosCredentialsUpdater() override; // Checks if Kerberos is enabled by asking KerberosCredentialsManager. bool IsKerberosEnabled() const; @@ -42,17 +38,11 @@ } private: - // Updates `active_account_name_`, if the given `account_name` has a different - // value. In that case, calls `active_account_changed_callback_` with the new - // value. - void UpdateActiveAccount(const std::string& account_name); - // KerberosCredentialsManager::Observer: - void OnKerberosEnabledStateChanged() override; void OnAccountsChanged() override; // Not owned. - raw_ptr<KerberosCredentialsManager> credentials_manager_; + KerberosCredentialsManager* credentials_manager_; std::string active_account_name_; const ActiveAccountChangedCallback active_account_changed_callback_; };
diff --git a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater_unittest.cc b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater_unittest.cc index a3244e1..aaf33c0 100644 --- a/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater_unittest.cc +++ b/chrome/browser/ash/smb_client/smb_kerberos_credentials_updater_unittest.cc
@@ -8,9 +8,6 @@ #include "base/run_loop.h" #include "base/test/bind.h" -#include "base/test/gmock_callback_support.h" -#include "base/test/mock_callback.h" -#include "base/values.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager.h" #include "chrome/browser/ash/login/users/mock_user_manager.h" #include "chrome/common/pref_names.h" @@ -24,16 +21,12 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using ::base::test::RunClosure; - namespace ash { -namespace smb_client { namespace { constexpr char kProfileEmail[] = "gaia_user@example.com"; constexpr char kPrincipal[] = "user@EXAMPLE.COM"; -constexpr char kOtherPrincipal[] = "icebear_cloud@EXAMPLE.COM"; constexpr char kPassword[] = "m1sst1ped>_<"; constexpr char kConfig[] = "[libdefaults]"; @@ -52,8 +45,8 @@ : scoped_user_manager_(CreateMockUserManager()), local_state_(TestingBrowserProcess::GetGlobal()) { // Enable Kerberos via policy. - SetPref(prefs::kKerberosEnabled, base::Value(true)); - + local_state_.Get()->SetManagedPref(prefs::kKerberosEnabled, + std::make_unique<base::Value>(true)); // Initialize User, Profile and KerberosCredentialsManager. KerberosClient::InitializeFake(); TestingProfile::Builder profile_builder; @@ -62,34 +55,24 @@ credentials_manager_ = std::make_unique<KerberosCredentialsManager>( local_state_.Get(), profile_.get()); } - ~SmbKerberosCredentialsUpdaterTest() override { // Remove KerberosCredentialsManager instance, before shutting down // KerberosClient. - credentials_updater_.reset(); credentials_manager_.reset(); KerberosClient::Shutdown(); } protected: - void AddAccountAndAuthenticate( - const std::string& principal_name, - KerberosCredentialsManager::ResultCallback callback) { + void AddAndAuthenticate(const std::string& principal_name) { + base::RunLoop run_loop; credentials_manager_->AddAccountAndAuthenticate( - principal_name, /*is_managed=*/false, kPassword, + principal_name, /*is_managed=*/true, kPassword, /*remember_password=*/true, kConfig, /*allow_existing=*/false, - std::move(callback)); - } - - void SetPref(const char* name, base::Value value) { - local_state_.Get()->SetManagedPref( - name, std::make_unique<base::Value>(std::move(value))); - } - - void CreateCredentialsUpdater( - SmbKerberosCredentialsUpdater::ActiveAccountChangedCallback callback) { - credentials_updater_ = std::make_unique<SmbKerberosCredentialsUpdater>( - credentials_manager_.get(), std::move(callback)); + base::BindLambdaForTesting([&run_loop](kerberos::ErrorType result) { + EXPECT_EQ(kerberos::ERROR_NONE, result); + run_loop.Quit(); + })); + run_loop.Run(); } content::BrowserTaskEnvironment task_environment_; @@ -97,111 +80,35 @@ ScopedTestingLocalState local_state_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<KerberosCredentialsManager> credentials_manager_; - std::unique_ptr<SmbKerberosCredentialsUpdater> credentials_updater_; }; -TEST_F(SmbKerberosCredentialsUpdaterTest, FirstAccountAdded) { - base::RunLoop run_loop; - base::MockRepeatingCallback<void(const std::string& account_identifier)> - account_changed_callback; - base::MockOnceCallback<void(kerberos::ErrorType)> result_callback; +TEST_F(SmbKerberosCredentialsUpdaterTest, TestActiveAccountChanged) { + // If active accounts changed callback is called, we will set this variable to + // true. + bool callback_called = false; + std::string callback_account; - CreateCredentialsUpdater(account_changed_callback.Get()); - EXPECT_CALL(account_changed_callback, Run(kPrincipal)).Times(1); - EXPECT_CALL(result_callback, Run(kerberos::ErrorType::ERROR_NONE)) - .WillOnce(RunClosure(run_loop.QuitClosure())); + smb_client::SmbKerberosCredentialsUpdater credentials_updater( + credentials_manager_.get(), + base::BindLambdaForTesting([&callback_called, &callback_account]( + const std::string& account_identifier) { + callback_called = true; + callback_account = account_identifier; + })); - AddAccountAndAuthenticate(kPrincipal, result_callback.Get()); - run_loop.Run(); + EXPECT_FALSE(callback_called); - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); + AddAndAuthenticate(kPrincipal); - // Set the active user to the same one. + EXPECT_TRUE(callback_called); + EXPECT_EQ(callback_account, kPrincipal); + + callback_called = false; + + // Try to notify the change now without changing/adding a user. credentials_manager_->SetActiveAccount(kPrincipal); - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); + EXPECT_FALSE(callback_called); } -TEST_F(SmbKerberosCredentialsUpdaterTest, SecondAccountAdded) { - base::RunLoop run_loop; - base::RunLoop other_run_loop; - base::MockRepeatingCallback<void(const std::string& account_identifier)> - account_changed_callback; - base::MockOnceCallback<void(kerberos::ErrorType)> result_callback; - base::MockOnceCallback<void(kerberos::ErrorType)> other_result_callback; - - CreateCredentialsUpdater(account_changed_callback.Get()); - EXPECT_CALL(account_changed_callback, Run(kPrincipal)).Times(2); - EXPECT_CALL(account_changed_callback, Run(kOtherPrincipal)).Times(1); - EXPECT_CALL(result_callback, Run(kerberos::ErrorType::ERROR_NONE)) - .WillOnce(RunClosure(run_loop.QuitClosure())); - EXPECT_CALL(other_result_callback, Run(kerberos::ErrorType::ERROR_NONE)) - .WillOnce(RunClosure(other_run_loop.QuitClosure())); - - AddAccountAndAuthenticate(kPrincipal, result_callback.Get()); - run_loop.Run(); - - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); - - AddAccountAndAuthenticate(kOtherPrincipal, other_result_callback.Get()); - other_run_loop.Run(); - - EXPECT_EQ(credentials_updater_->active_account_name(), kOtherPrincipal); - - // Change the active user back to the first one. - credentials_manager_->SetActiveAccount(kPrincipal); - - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); -} - -TEST_F(SmbKerberosCredentialsUpdaterTest, KerberosGetsDisabled) { - base::RunLoop run_loop; - base::MockRepeatingCallback<void(const std::string& account_identifier)> - account_changed_callback; - base::MockOnceCallback<void(kerberos::ErrorType)> result_callback; - - EXPECT_CALL(account_changed_callback, Run("")).Times(1); - EXPECT_CALL(result_callback, Run(kerberos::ErrorType::ERROR_NONE)) - .WillOnce(RunClosure(run_loop.QuitClosure())); - - // Starting with one account added. - AddAccountAndAuthenticate(kPrincipal, result_callback.Get()); - run_loop.Run(); - - CreateCredentialsUpdater(account_changed_callback.Get()); - - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); - - // Disable Kerberos via policy. - SetPref(prefs::kKerberosEnabled, base::Value(false)); - - EXPECT_TRUE(credentials_updater_->active_account_name().empty()); -} - -TEST_F(SmbKerberosCredentialsUpdaterTest, KerberosGetsEnabled) { - base::RunLoop run_loop; - base::MockRepeatingCallback<void(const std::string& account_identifier)> - account_changed_callback; - base::MockOnceCallback<void(kerberos::ErrorType)> result_callback; - - EXPECT_CALL(account_changed_callback, Run(kPrincipal)).Times(1); - EXPECT_CALL(result_callback, Run(kerberos::ErrorType::ERROR_NONE)) - .WillOnce(RunClosure(run_loop.QuitClosure())); - - // Starting with Kerberos disabled via policy. - SetPref(prefs::kKerberosEnabled, base::Value(false)); - - CreateCredentialsUpdater(account_changed_callback.Get()); - - EXPECT_TRUE(credentials_updater_->active_account_name().empty()); - - // Enable Kerberos via policy, then add an account. - SetPref(prefs::kKerberosEnabled, base::Value(true)); - AddAccountAndAuthenticate(kPrincipal, result_callback.Get()); - run_loop.Run(); - - EXPECT_EQ(credentials_updater_->active_account_name(), kPrincipal); -} - -} // namespace smb_client } // namespace ash
diff --git a/chrome/browser/ash/smb_client/smb_service.cc b/chrome/browser/ash/smb_client/smb_service.cc index ab4087a..2920d361 100644 --- a/chrome/browser/ash/smb_client/smb_service.cc +++ b/chrome/browser/ash/smb_client/smb_service.cc
@@ -128,7 +128,7 @@ KerberosCredentialsManager* credentials_manager = KerberosCredentialsManagerFactory::GetExisting(profile); - if (credentials_manager) { + if (credentials_manager && credentials_manager->IsKerberosEnabled()) { kerberos_credentials_updater_ = std::make_unique<SmbKerberosCredentialsUpdater>( credentials_manager,
diff --git a/chrome/browser/ash/smb_client/smb_service.h b/chrome/browser/ash/smb_client/smb_service.h index 7b86e0c..ee34c87 100644 --- a/chrome/browser/ash/smb_client/smb_service.h +++ b/chrome/browser/ash/smb_client/smb_service.h
@@ -107,7 +107,8 @@ // Updates credentials for Kerberos service. void UpdateKerberosCredentials(const std::string& account_identifier); - // Returns true if the Kerberos feature is enabled. + // Returns true if Kerberos was enabled via policy at service creation time + // and is still enabled now. bool IsKerberosEnabledViaPolicy() const; // Sets the mounter creation callback, which is passed to
diff --git a/chrome/browser/ash/smb_client/smb_service_unittest.cc b/chrome/browser/ash/smb_client/smb_service_unittest.cc index 7768818..90ac0f4c4 100644 --- a/chrome/browser/ash/smb_client/smb_service_unittest.cc +++ b/chrome/browser/ash/smb_client/smb_service_unittest.cc
@@ -372,7 +372,7 @@ EXPECT_EQ(options.username, kTestUser); EXPECT_TRUE(options.workgroup.empty()); EXPECT_EQ(options.password, kTestPassword); - EXPECT_TRUE(options.allow_ntlm); + EXPECT_EQ(options.allow_ntlm, true); EXPECT_FALSE(options.kerberos_options); smbfs_host_delegate = delegate; return std::move(mock_mounter); @@ -531,7 +531,7 @@ // Workgroup/domain is converted to upper-case. EXPECT_EQ(options.workgroup, base::ToUpperASCII(kTestADDomain)); EXPECT_TRUE(options.password.empty()); - EXPECT_TRUE(options.allow_ntlm); + EXPECT_EQ(options.allow_ntlm, true); EXPECT_EQ( options.kerberos_options->source, smbfs::SmbFsMounter::KerberosOptions::Source::kActiveDirectory); @@ -656,7 +656,7 @@ EXPECT_EQ(options.username, kTestUser); EXPECT_EQ(options.workgroup, kTestDomain); EXPECT_TRUE(options.password.empty()); - EXPECT_TRUE(options.allow_ntlm); + EXPECT_EQ(options.allow_ntlm, true); EXPECT_FALSE(options.kerberos_options); EXPECT_TRUE(options.save_restore_password); EXPECT_FALSE(options.account_hash.empty());
diff --git a/chrome/browser/autofill/autofill_context_menu_manager.cc b/chrome/browser/autofill/autofill_context_menu_manager.cc new file mode 100644 index 0000000..54fecf7c --- /dev/null +++ b/chrome/browser/autofill/autofill_context_menu_manager.cc
@@ -0,0 +1,56 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/autofill/autofill_context_menu_manager.h" + +#include <string> + +#include "chrome/app/chrome_command_ids.h" + +namespace autofill { + +namespace { + +// The range of command IDs reserved for autofill's custom menus. +static constexpr int kAutofillContextCustomFirst = + IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_FIRST; +static constexpr int kAutofillContextCustomLast = + IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_LAST; + +} // namespace + +// static +bool AutofillContextMenuManager::IsAutofillCustomCommandId( + CommandId command_id) { + return command_id.value() >= kAutofillContextCustomFirst && + command_id.value() <= kAutofillContextCustomLast; +} + +void AutofillContextMenuManager::AppendTopLevelItems() { + // TODO(crbug.com/1325811): Implement +} + +bool AutofillContextMenuManager::IsCommandIdChecked( + CommandId command_id) const { + return false; +} + +bool AutofillContextMenuManager::IsCommandIdVisible( + CommandId command_id) const { + return true; +} + +bool AutofillContextMenuManager::IsCommandIdEnabled( + CommandId command_id) const { + return true; +} + +void AutofillContextMenuManager::ExecuteCommand( + CommandId command_id, + content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host) { + // TODO(crbug.com/1325811): Implement. +} + +} // namespace autofill
diff --git a/chrome/browser/autofill/autofill_context_menu_manager.h b/chrome/browser/autofill/autofill_context_menu_manager.h new file mode 100644 index 0000000..afc1ecf --- /dev/null +++ b/chrome/browser/autofill/autofill_context_menu_manager.h
@@ -0,0 +1,52 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_AUTOFILL_AUTOFILL_CONTEXT_MENU_MANAGER_H_ +#define CHROME_BROWSER_AUTOFILL_AUTOFILL_CONTEXT_MENU_MANAGER_H_ + +#include "base/types/strong_alias.h" + +namespace content { +class RenderFrameHost; +class WebContents; +} // namespace content + +namespace autofill { + +// `AutofillContextMenuManager` is responsible for adding/executing Autofill +// related context menu items. `RenderViewContextMenu` is intended to own and +// control the lifetime of `AutofillContextMenuManager`. +class AutofillContextMenuManager { + public: + // Represents command id used to denote a row in the context menu. The + // command ids are created when the items are added to the context menu during + // it's initialization. For Autofill, it ranges from + // `IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_FIRST` to + // `IDC_CONTENT_CONTEXT_AUTOFILL_CUSTOM_LAST`. + using CommandId = base::StrongAlias<class CommandIdTag, int>; + + // Returns true if the given id is one generated for autofill context menu. + static bool IsAutofillCustomCommandId(CommandId command_id); + + AutofillContextMenuManager() = default; + AutofillContextMenuManager(const AutofillContextMenuManager&) = delete; + AutofillContextMenuManager& operator=(const AutofillContextMenuManager&) = + delete; + + // Adds items such as "Addresses"/"Credit Cards"/"Passwords" to the top level + // of the context menu. + void AppendTopLevelItems(); + + // |AutofillContextMenuManager| specific, called from |RenderViewContextMenu|. + bool IsCommandIdChecked(CommandId command_id) const; + bool IsCommandIdVisible(CommandId command_id) const; + bool IsCommandIdEnabled(CommandId command_id) const; + void ExecuteCommand(CommandId command_id, + content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host); +}; + +} // namespace autofill + +#endif // CHROME_BROWSER_AUTOFILL_AUTOFILL_CONTEXT_MENU_MANAGER_H_
diff --git a/chrome/browser/android/bookmarks/bookmark_bridge.cc b/chrome/browser/bookmarks/android/bookmark_bridge.cc similarity index 93% rename from chrome/browser/android/bookmarks/bookmark_bridge.cc rename to chrome/browser/bookmarks/android/bookmark_bridge.cc index d0a025b..6832e77 100644 --- a/chrome/browser/android/bookmarks/bookmark_bridge.cc +++ b/chrome/browser/bookmarks/android/bookmark_bridge.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/android/bookmarks/bookmark_bridge.h" +#include "chrome/browser/bookmarks/android/bookmark_bridge.h" #include <stddef.h> #include <stdint.h> @@ -57,19 +57,19 @@ #include "content/public/browser/web_contents.h" using base::android::AttachCurrentThread; -using base::android::ConvertUTF8ToJavaString; using base::android::ConvertUTF16ToJavaString; +using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::JavaRef; -using base::android::ScopedJavaLocalRef; using base::android::ScopedJavaGlobalRef; +using base::android::ScopedJavaLocalRef; using base::android::ToJavaIntArray; -using bookmarks::android::JavaBookmarkIdCreateBookmarkId; -using bookmarks::android::JavaBookmarkIdGetId; -using bookmarks::android::JavaBookmarkIdGetType; using bookmarks::BookmarkModel; using bookmarks::BookmarkNode; using bookmarks::BookmarkType; +using bookmarks::android::JavaBookmarkIdCreateBookmarkId; +using bookmarks::android::JavaBookmarkIdGetId; +using bookmarks::android::JavaBookmarkIdGetType; using content::BrowserThread; namespace { @@ -78,8 +78,7 @@ public: explicit BookmarkTitleComparer(BookmarkBridge* bookmark_bridge, const icu::Collator* collator) - : bookmark_bridge_(bookmark_bridge), - collator_(collator) {} + : bookmark_bridge_(bookmark_bridge), collator_(collator) {} bool operator()(const BookmarkNode* lhs, const BookmarkNode* rhs) { if (collator_) { @@ -235,7 +234,7 @@ JNIEnv* env, const JavaParamRef<jobject>& obj) { if (partner_bookmarks_shim_->IsLoaded()) - return; + return; partner_bookmarks_shim_->SetPartnerBookmarksRoot( PartnerBookmarksReader::CreatePartnerBookmarksRootForTesting()); PartnerBookmarksShim::DisablePartnerBookmarksEditing(); @@ -276,9 +275,8 @@ return node ? CreateJavaBookmark(node) : ScopedJavaLocalRef<jobject>(); } -bool BookmarkBridge::IsDoingExtensiveChanges( - JNIEnv* env, - const JavaParamRef<jobject>& obj) { +bool BookmarkBridge::IsDoingExtensiveChanges(JNIEnv* env, + const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); return bookmark_model_->IsDoingExtensiveChanges(); } @@ -309,8 +307,8 @@ !managed_bookmark_service_->managed_node()->children().empty()) { top_level_folders.push_back(managed_bookmark_service_->managed_node()); } - if (partner_bookmarks_shim_->HasPartnerBookmarks() - && IsReachable(partner_bookmarks_shim_->GetPartnerBookmarksRoot())) { + if (partner_bookmarks_shim_->HasPartnerBookmarks() && + IsReachable(partner_bookmarks_shim_->GetPartnerBookmarksRoot())) { top_level_folders.push_back( partner_bookmarks_shim_->GetPartnerBookmarksRoot()); } @@ -344,11 +342,10 @@ } for (std::vector<const BookmarkNode*>::const_iterator it = - top_level_folders.begin(); it != top_level_folders.end(); ++it) { - Java_BookmarkBridge_addToBookmarkIdList(env, - j_result_obj, - (*it)->id(), - GetBookmarkType(*it)); + top_level_folders.begin(); + it != top_level_folders.end(); ++it) { + Java_BookmarkBridge_addToBookmarkIdList(env, j_result_obj, (*it)->id(), + GetBookmarkType(*it)); } } @@ -412,9 +409,8 @@ const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const BookmarkNode* root_node = bookmark_model_->root_node(); - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, root_node->id(), GetBookmarkType(root_node)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, root_node->id(), GetBookmarkType(root_node)); return folder_id_obj; } @@ -423,9 +419,8 @@ const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const BookmarkNode* mobile_node = bookmark_model_->mobile_node(); - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, mobile_node->id(), GetBookmarkType(mobile_node)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, mobile_node->id(), GetBookmarkType(mobile_node)); return folder_id_obj; } @@ -434,9 +429,8 @@ const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const BookmarkNode* other_node = bookmark_model_->other_node(); - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, other_node->id(), GetBookmarkType(other_node)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, other_node->id(), GetBookmarkType(other_node)); return folder_id_obj; } @@ -445,9 +439,8 @@ const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const BookmarkNode* desktop_node = bookmark_model_->bookmark_bar_node(); - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, desktop_node->id(), GetBookmarkType(desktop_node)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, desktop_node->id(), GetBookmarkType(desktop_node)); return folder_id_obj; } @@ -478,9 +471,9 @@ } jint BookmarkBridge::GetChildCount(JNIEnv* env, - const JavaParamRef<jobject>& obj, - jlong id, - jint type) { + const JavaParamRef<jobject>& obj, + jlong id, + jint type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); const BookmarkNode* node = GetNodeByID(id, type); @@ -488,10 +481,10 @@ } void BookmarkBridge::GetChildIDs(JNIEnv* env, - const JavaParamRef<jobject>& obj, - jlong id, - jint type, - const JavaParamRef<jobject>& j_result_obj) { + const JavaParamRef<jobject>& obj, + jlong id, + jint type, + const JavaParamRef<jobject>& j_result_obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); @@ -512,8 +505,7 @@ partner_bookmarks_shim_->HasPartnerBookmarks() && IsReachable(partner_bookmarks_shim_->GetPartnerBookmarksRoot())) { Java_BookmarkBridge_addToBookmarkIdList( - env, - j_result_obj, + env, j_result_obj, partner_bookmarks_shim_->GetPartnerBookmarksRoot()->id(), BookmarkType::BOOKMARK_TYPE_PARTNER); } @@ -532,8 +524,8 @@ DCHECK(parent); const BookmarkNode* child = parent->children()[static_cast<size_t>(index)].get(); - return JavaBookmarkIdCreateBookmarkId( - env, child->id(), GetBookmarkType(child)); + return JavaBookmarkIdCreateBookmarkId(env, child->id(), + GetBookmarkType(child)); } jint BookmarkBridge::GetTotalBookmarkCount( @@ -578,10 +570,10 @@ } void BookmarkBridge::SetBookmarkTitle(JNIEnv* env, - const JavaParamRef<jobject>& obj, - jlong id, - jint type, - const JavaParamRef<jstring>& j_title) { + const JavaParamRef<jobject>& obj, + jlong id, + jint type, + const JavaParamRef<jstring>& j_title) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); @@ -665,9 +657,9 @@ } bool BookmarkBridge::DoesBookmarkExist(JNIEnv* env, - const JavaParamRef<jobject>& obj, - jlong id, - jint type) { + const JavaParamRef<jobject>& obj, + jlong id, + jint type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); @@ -702,9 +694,8 @@ return; // Recreate the java bookmarkId object due to fallback. - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, folder->id(), GetBookmarkType(folder)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, folder->id(), GetBookmarkType(folder)); // Get the folder contents. for (const auto& node : folder->children()) { @@ -715,8 +706,7 @@ if (folder == bookmark_model_->mobile_node() && partner_bookmarks_shim_->HasPartnerBookmarks()) { ExtractBookmarkNodeInformation( - partner_bookmarks_shim_->GetPartnerBookmarksRoot(), - j_result_obj); + partner_bookmarks_shim_->GetPartnerBookmarksRoot(), j_result_obj); } if (j_callback_obj) { @@ -726,9 +716,9 @@ } jboolean BookmarkBridge::IsFolderVisible(JNIEnv* env, - const JavaParamRef<jobject>& obj, - jlong id, - jint type) { + const JavaParamRef<jobject>& obj, + jlong id, + jint type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (type == BookmarkType::BOOKMARK_TYPE_NORMAL) { const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( @@ -758,9 +748,8 @@ return; // Recreate the java bookmarkId object due to fallback. - ScopedJavaLocalRef<jobject> folder_id_obj = - JavaBookmarkIdCreateBookmarkId( - env, folder->id(), GetBookmarkType(folder)); + ScopedJavaLocalRef<jobject> folder_id_obj = JavaBookmarkIdCreateBookmarkId( + env, folder->id(), GetBookmarkType(folder)); // Get the folder hierarchy. const BookmarkNode* node = folder; @@ -857,9 +846,8 @@ parent, static_cast<size_t>(index), base::android::ConvertJavaStringToUTF16(env, j_title)); DCHECK(new_node); - ScopedJavaLocalRef<jobject> new_java_obj = - JavaBookmarkIdCreateBookmarkId( - env, new_node->id(), GetBookmarkType(new_node)); + ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId( + env, new_node->id(), GetBookmarkType(new_node)); return new_java_obj; } @@ -897,9 +885,8 @@ } } -void BookmarkBridge::RemoveAllUserBookmarks( - JNIEnv* env, - const JavaParamRef<jobject>& obj) { +void BookmarkBridge::RemoveAllUserBookmarks(JNIEnv* env, + const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); bookmark_model_->RemoveAllUserBookmarks(); @@ -945,9 +932,8 @@ base::android::ConvertJavaStringToUTF16(env, j_title), *url::GURLAndroid::ToNativeGURL(env, j_url)); DCHECK(new_node); - ScopedJavaLocalRef<jobject> new_java_obj = - JavaBookmarkIdCreateBookmarkId( - env, new_node->id(), GetBookmarkType(new_node)); + ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId( + env, new_node->id(), GetBookmarkType(new_node)); return new_java_obj; } @@ -1028,7 +1014,7 @@ } void BookmarkBridge::StartGroupingUndos(JNIEnv* env, - const JavaParamRef<jobject>& obj) { + const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); DCHECK(!grouped_bookmark_actions_.get()); // shouldn't have started already @@ -1037,7 +1023,7 @@ } void BookmarkBridge::EndGroupingUndos(JNIEnv* env, - const JavaParamRef<jobject>& obj) { + const JavaParamRef<jobject>& obj) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(IsLoaded()); DCHECK(grouped_bookmark_actions_.get()); // should only call after start @@ -1109,7 +1095,7 @@ } const BookmarkNode* BookmarkBridge::GetFolderWithFallback(long folder_id, - int type) { + int type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const BookmarkNode* folder = GetNodeByID(folder_id, type); if (!folder || folder->type() == BookmarkNode::URL || @@ -1138,7 +1124,7 @@ bool BookmarkBridge::IsEditable(const BookmarkNode* node) const { if (!node || (node->type() != BookmarkNode::FOLDER && - node->type() != BookmarkNode::URL)) { + node->type() != BookmarkNode::URL)) { return false; } if (!IsEditBookmarksEnabled() || bookmark_model_->is_permanent_node(node)) @@ -1192,8 +1178,7 @@ reading_list_manager_->IsLoaded()); } -bool BookmarkBridge::IsFolderAvailable( - const BookmarkNode* folder) const { +bool BookmarkBridge::IsFolderAvailable(const BookmarkNode* folder) const { // The managed bookmarks folder is not shown if there are no bookmarks // configured via policy. if (folder == managed_bookmark_service_->managed_node() && @@ -1234,7 +1219,7 @@ } void BookmarkBridge::BookmarkModelLoaded(BookmarkModel* model, - bool ids_reassigned) { + bool ids_reassigned) { NotifyIfDoneLoading(); } @@ -1307,7 +1292,7 @@ } void BookmarkBridge::BookmarkNodeChanged(BookmarkModel* model, - const BookmarkNode* node) { + const BookmarkNode* node) { if (!IsLoaded()) return; @@ -1319,7 +1304,7 @@ } void BookmarkBridge::BookmarkNodeChildrenReordered(BookmarkModel* model, - const BookmarkNode* node) { + const BookmarkNode* node) { if (!IsLoaded()) return;
diff --git a/chrome/browser/android/bookmarks/bookmark_bridge.h b/chrome/browser/bookmarks/android/bookmark_bridge.h similarity index 97% rename from chrome/browser/android/bookmarks/bookmark_bridge.h rename to chrome/browser/bookmarks/android/bookmark_bridge.h index 863deb36..7be901f 100644 --- a/chrome/browser/android/bookmarks/bookmark_bridge.h +++ b/chrome/browser/bookmarks/android/bookmark_bridge.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_ANDROID_BOOKMARKS_BOOKMARK_BRIDGE_H_ -#define CHROME_BROWSER_ANDROID_BOOKMARKS_BOOKMARK_BRIDGE_H_ +#ifndef CHROME_BROWSER_BOOKMARKS_ANDROID_BOOKMARK_BRIDGE_H_ +#define CHROME_BROWSER_BOOKMARKS_ANDROID_BOOKMARK_BRIDGE_H_ #include <memory> #include <set> @@ -31,7 +31,7 @@ class BookmarkModel; class ManagedBookmarkService; class ScopedGroupBookmarkActions; -} +} // namespace bookmarks class OptimizationGuideKeyedService; class Profile; @@ -238,9 +238,8 @@ const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_bookmark_id_obj); - void RemoveAllUserBookmarks( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); + void RemoveAllUserBookmarks(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); void MoveBookmark( JNIEnv* env, @@ -406,4 +405,4 @@ base::WeakPtrFactory<BookmarkBridge> weak_ptr_factory_; }; -#endif // CHROME_BROWSER_ANDROID_BOOKMARKS_BOOKMARK_BRIDGE_H_ +#endif // CHROME_BROWSER_BOOKMARKS_ANDROID_BOOKMARK_BRIDGE_H_
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index 6843430..6549be7 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -42,6 +42,7 @@ #include "ash/public/cpp/window_properties.h" #include "ash/rotator/screen_rotation_animator.h" #include "ash/shell.h" +#include "ash/style/ash_color_provider.h" #include "ash/wm/wm_event.h" #include "base/base64.h" #include "base/bind.h" @@ -5699,6 +5700,31 @@ } /////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateForceAutoThemeModeFunction +////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateForceAutoThemeModeFunction:: + AutotestPrivateForceAutoThemeModeFunction() = default; + +AutotestPrivateForceAutoThemeModeFunction:: + ~AutotestPrivateForceAutoThemeModeFunction() = default; + +ExtensionFunction::ResponseAction +AutotestPrivateForceAutoThemeModeFunction::Run() { + DVLOG(1) << "AutotestPrivateForceAutoThemeModeFunction"; + + std::unique_ptr<api::autotest_private::ForceAutoThemeMode::Params> params( + api::autotest_private::ForceAutoThemeMode::Params::Create(args())); + EXTENSION_FUNCTION_VALIDATE(params); + + ash::AshColorProvider* color_provider = ash::AshColorProvider::Get(); + DCHECK(color_provider); + + color_provider->SetDarkModeEnabledForTest(params->dark_mode_enabled); + return RespondNow(NoArguments()); +} + +/////////////////////////////////////////////////////////////////////////////// // AutotestPrivateAPI ///////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h index f4ff9cb..a48338c 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -1560,6 +1560,17 @@ ResponseAction Run() override; }; +class AutotestPrivateForceAutoThemeModeFunction : public ExtensionFunction { + public: + AutotestPrivateForceAutoThemeModeFunction(); + DECLARE_EXTENSION_FUNCTION("autotestPrivate.forceAutoThemeMode", + AUTOTESTPRIVATE_FORCEAUTOTHEMEMODE) + + private: + ~AutotestPrivateForceAutoThemeModeFunction() override; + ResponseAction Run() override; +}; + template <> KeyedService* BrowserContextKeyedAPIFactory<AutotestPrivateAPI>::BuildServiceInstanceFor(
diff --git a/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc b/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc index 0264870..029a8baf 100644 --- a/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc +++ b/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc
@@ -2805,7 +2805,8 @@ ExtensionActionRunner* runner = ExtensionActionRunner::GetForWebContents(web_contents()); ASSERT_TRUE(runner); - EXPECT_EQ(expected_blocked_actions, runner->GetBlockedActions(extension)); + EXPECT_EQ(expected_blocked_actions, + runner->GetBlockedActions(extension->id())); }; {
diff --git a/chrome/browser/extensions/api/printing/print_job_submitter.cc b/chrome/browser/extensions/api/printing/print_job_submitter.cc index 0400f99..3a05db9 100644 --- a/chrome/browser/extensions/api/printing/print_job_submitter.cc +++ b/chrome/browser/extensions/api/printing/print_job_submitter.cc
@@ -19,7 +19,7 @@ #include "chrome/browser/extensions/api/printing/printing_api_utils.h" #include "chrome/browser/printing/printing_service.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/browser/ui/extensions/extensions_dialogs.h" #include "chrome/browser/ui/native_window_tracker.h" #include "chrome/common/pref_names.h" #include "chrome/services/printing/public/mojom/pdf_flattener.mojom.h" @@ -263,7 +263,7 @@ if (native_window_tracker_ && native_window_tracker_->WasNativeWindowClosed()) native_window_ = gfx::kNullNativeWindow; - chrome::ShowPrintJobConfirmationDialog( + extensions::ShowPrintJobConfirmationDialog( native_window_, extension_->id(), base::UTF8ToUTF16(extension_->name()), extension_icon.AsImageSkia(), settings_->title(), printer_name_, base::BindOnce(&PrintJobSubmitter::OnPrintJobConfirmationDialogClosed,
diff --git a/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chrome/browser/extensions/api/web_request/web_request_apitest.cc index 22053cc4b..82e2696 100644 --- a/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_apitest.cc
@@ -1091,7 +1091,8 @@ PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath); PerformXhrInFrame(child_frame.get(), kChildHost, port, kXhrPath); EXPECT_EQ(0, GetWebRequestCountFromBackgroundPage(extension, profile())); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, + runner->GetBlockedActions(extension->id())); // Grant activeTab permission. runner->accept_bubble_for_testing(true); @@ -1117,7 +1118,7 @@ HasSeenWebRequestInBackgroundPage(extension, profile(), "c.com")); // The withheld sub-frame requests should not show up as a blocked action. - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); int request_count = GetWebRequestCountFromBackgroundPage(extension, profile()); @@ -1135,7 +1136,7 @@ GetWebRequestCountFromBackgroundPage(extension, profile())); // But since there's no way for the user to currently grant access to child // frames, this shouldn't show up as a blocked action. - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); // Revoke the extension's tab permissions. ActiveTabPermissionGranter* granter = @@ -1155,7 +1156,8 @@ EXPECT_EQ(request_count, GetWebRequestCountFromBackgroundPage(extension, profile())); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, + runner->GetBlockedActions(extension->id())); } // Test that extensions with granted runtime host permissions to a tab can @@ -1189,7 +1191,8 @@ ExtensionActionRunner::GetForWebContents(web_contents); ASSERT_TRUE(runner); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, + runner->GetBlockedActions(extension->id())); // Grant runtime host permission to the page. The page should refresh. Even // though the request is for b.com (and the extension only has access to @@ -1200,7 +1203,7 @@ runner->RunAction(extension, true /* grant tab permissions */); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); EXPECT_TRUE( HasSeenWebRequestInBackgroundPage(extension, profile(), kCrossSiteHost)); @@ -1259,7 +1262,7 @@ // Even though the extension has access to b.com, it shouldn't show that it // wants to run, because example.com is not a requested host. - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); EXPECT_FALSE( HasSeenWebRequestInBackgroundPage(extension, profile(), "b.com")); @@ -1268,7 +1271,8 @@ ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "b.com", "/extensions/cross_site_script.html"))); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, + runner->GetBlockedActions(extension->id())); } // Verify that requests to clientsX.google.com are protected properly. @@ -2252,9 +2256,8 @@ // Tests that the webRequest events aren't dispatched when the URL of the // request is protected by policy. -// Disabled because it is flaky. See https://crbug.com/835155 IN_PROC_BROWSER_TEST_F(ExtensionApiTestWithManagementPolicy, - DISABLED_UrlProtectedByPolicy) { + UrlProtectedByPolicy) { // Host protected by policy. const std::string protected_domain = "example.com"; @@ -2353,12 +2356,12 @@ // still be blocked due to ExtensionSettings policy on example.com. // Only records ACCESS_WITHHELD, not ACCESS_DENIED, this is why it matches // BLOCKED_ACTION_NONE. - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); runner->accept_bubble_for_testing(true); runner->RunAction(extension, true); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id())); int xhr_count = GetWebRequestCountFromBackgroundPage(extension, profile()); // ... which means that we should have a non-zero xhr count if the policy // didn't block the events.
diff --git a/chrome/browser/extensions/content_script_apitest.cc b/chrome/browser/extensions/content_script_apitest.cc index 645f706..083dcec8e 100644 --- a/chrome/browser/extensions/content_script_apitest.cc +++ b/chrome/browser/extensions/content_script_apitest.cc
@@ -54,6 +54,7 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/privacy_budget/identifiable_surface.h" #include "ui/base/page_transition_types.h" #include "url/gurl.h" @@ -1616,6 +1617,11 @@ // Tests that content scripts can run on filesystem: URLs. IN_PROC_BROWSER_TEST_F(ContentScriptRelatedFrameTest, MatchAboutBlank_FilesystemFrame) { + // TODO(https://crbug.com/1332598): Remove this test when removing filesystem: + // navigation for good. + if (!base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation)) + GTEST_SKIP(); + content::WebContents* tab = NavigateTab(allowed_url_with_iframe()); GURL filesystem_url = CreateFilesystemURL(tab->GetPrimaryMainFrame()); NavigateIframe(tab->GetPrimaryMainFrame(), "frames[0]", filesystem_url); @@ -1738,6 +1744,10 @@ // Inject a content script on an iframe to a filesystem: URL on an allowed site. IN_PROC_BROWSER_TEST_F(ContentScriptMatchOriginAsFallbackTest, FilesystemURLInjection_SimpleIframe_Allowed) { + // TODO(https://crbug.com/1332598): Remove this test when removing filesystem: + // navigation for good. + if (!base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation)) + GTEST_SKIP(); content::WebContents* tab = NavigateTab(allowed_url_with_iframe()); GURL filesystem_url = CreateFilesystemURL(tab->GetPrimaryMainFrame()); NavigateIframe(tab->GetPrimaryMainFrame(), "frames[0]", filesystem_url); @@ -1752,6 +1762,10 @@ // protected site. IN_PROC_BROWSER_TEST_F(ContentScriptMatchOriginAsFallbackTest, FilesystemURLInjection_SimpleIframe_Disallowed) { + // TODO(https://crbug.com/1332598): Remove this test when removing filesystem: + // navigation for good. + if (!base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation)) + GTEST_SKIP(); content::WebContents* tab = NavigateTab(disallowed_url_with_iframe()); GURL filesystem_url = CreateFilesystemURL(tab->GetPrimaryMainFrame()); NavigateIframe(tab->GetPrimaryMainFrame(), "frames[0]", filesystem_url);
diff --git a/chrome/browser/extensions/extension_action_runner.cc b/chrome/browser/extensions/extension_action_runner.cc index 988e0a89..ec73d02 100644 --- a/chrome/browser/extensions/extension_action_runner.cc +++ b/chrome/browser/extensions/extension_action_runner.cc
@@ -47,12 +47,8 @@ namespace extensions { -namespace { - -// The blocked actions that require a page refresh to run. -const int kRefreshRequiredActionsMask = +const int ExtensionActionRunner::kRefreshRequiredActionsMask = BLOCKED_ACTION_WEB_REQUEST | BLOCKED_ACTION_SCRIPT_AT_START; -} ExtensionActionRunner::PendingScript::PendingScript( mojom::RunLocation run_location, @@ -90,8 +86,8 @@ const Extension* extension, bool grant_tab_permissions) { if (grant_tab_permissions) { - int blocked = GetBlockedActions(extension); - if (blocked & kRefreshRequiredActionsMask) { + int blocked_actions = GetBlockedActions(extension->id()); + if (blocked_actions & kRefreshRequiredActionsMask) { const GURL& url = web_contents()->GetLastCommittedURL(); // An extension that wants to run but it is currently blocked must have // "on click" access. @@ -119,7 +115,7 @@ // If the extension had blocked actions, granting active tab will have // run the extension. Don't execute further since clicking should run // blocked actions *or* the normal extension action, not both. - if (blocked != BLOCKED_ACTION_NONE) + if (blocked_actions) return ExtensionAction::ACTION_NONE; } @@ -154,8 +150,7 @@ return; } - int blocked_actions = GetBlockedActions(extension); - + int blocked_actions = GetBlockedActions(extension->id()); // Refresh the page if there are pending actions which mandate a refresh. if (blocked_actions & kRefreshRequiredActionsMask) { // TODO(devlin): The bubble text should make it clear that permissions are @@ -194,11 +189,11 @@ test_observer_->OnBlockedActionAdded(); } -int ExtensionActionRunner::GetBlockedActions(const Extension* extension) { +int ExtensionActionRunner::GetBlockedActions(const ExtensionId& extension_id) { int blocked_actions = BLOCKED_ACTION_NONE; - if (web_request_blocked_.count(extension->id()) != 0) + if (web_request_blocked_.count(extension_id) != 0) blocked_actions |= BLOCKED_ACTION_WEB_REQUEST; - auto iter = pending_scripts_.find(extension->id()); + auto iter = pending_scripts_.find(extension_id); if (iter != pending_scripts_.end()) { for (const auto& script : iter->second) { switch (script->run_location) { @@ -221,7 +216,7 @@ } bool ExtensionActionRunner::WantsToRun(const Extension* extension) { - return GetBlockedActions(extension) != BLOCKED_ACTION_NONE; + return GetBlockedActions(extension->id()) != BLOCKED_ACTION_NONE; } void ExtensionActionRunner::RunForTesting(const Extension* extension) {
diff --git a/chrome/browser/extensions/extension_action_runner.h b/chrome/browser/extensions/extension_action_runner.h index a87f3d58..e64e74f 100644 --- a/chrome/browser/extensions/extension_action_runner.h +++ b/chrome/browser/extensions/extension_action_runner.h
@@ -22,6 +22,7 @@ #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" +#include "extensions/common/extension_id.h" #include "extensions/common/mojom/frame.mojom.h" #include "extensions/common/mojom/injection_type.mojom-shared.h" #include "extensions/common/mojom/run_location.mojom-shared.h" @@ -84,7 +85,7 @@ // Returns a bitmask of BlockedActionType for the actions that have been // blocked for the given extension. - int GetBlockedActions(const Extension* extension); + int GetBlockedActions(const ExtensionId& extension_id); // Returns true if the given |extension| has any blocked actions. bool WantsToRun(const Extension* extension); @@ -134,6 +135,9 @@ } #endif // defined(UNIT_TEST) + // The blocked actions that require a page refresh to run. + static const int kRefreshRequiredActionsMask; + private: FRIEND_TEST_ALL_PREFIXES(ExtensionActionRunnerFencedFrameBrowserTest, DoNotResetExtensionActionRunner);
diff --git a/chrome/browser/extensions/extension_action_runner_unittest.cc b/chrome/browser/extensions/extension_action_runner_unittest.cc index 7da6df0..fb6ec0445 100644 --- a/chrome/browser/extensions/extension_action_runner_unittest.cc +++ b/chrome/browser/extensions/extension_action_runner_unittest.cc
@@ -433,20 +433,20 @@ NavigateAndCommit(GURL("https://www.foo.com")); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension->id())); RequestInjection(extension, mojom::RunLocation::kDocumentEnd); EXPECT_EQ(BLOCKED_ACTION_SCRIPT_OTHER, - runner()->GetBlockedActions(extension)); + runner()->GetBlockedActions(extension->id())); RequestInjection(extension, mojom::RunLocation::kDocumentIdle); EXPECT_EQ(BLOCKED_ACTION_SCRIPT_OTHER, - runner()->GetBlockedActions(extension)); + runner()->GetBlockedActions(extension->id())); RequestInjection(extension, mojom::RunLocation::kDocumentStart); EXPECT_EQ(BLOCKED_ACTION_SCRIPT_AT_START | BLOCKED_ACTION_SCRIPT_OTHER, - runner()->GetBlockedActions(extension)); + runner()->GetBlockedActions(extension->id())); runner()->RunForTesting(extension); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension->id())); } TEST_F(ExtensionActionRunnerUnitTest, TestWebRequestBlocked) { @@ -455,20 +455,21 @@ NavigateAndCommit(GURL("https://www.foo.com")); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension->id())); EXPECT_FALSE(runner()->WantsToRun(extension)); runner()->OnWebRequestBlocked(extension); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner()->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, + runner()->GetBlockedActions(extension->id())); EXPECT_TRUE(runner()->WantsToRun(extension)); RequestInjection(extension); EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST | BLOCKED_ACTION_SCRIPT_OTHER, - runner()->GetBlockedActions(extension)); + runner()->GetBlockedActions(extension->id())); EXPECT_TRUE(runner()->WantsToRun(extension)); NavigateAndCommit(GURL("https://www.bar.com")); - EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension)); + EXPECT_EQ(BLOCKED_ACTION_NONE, runner()->GetBlockedActions(extension->id())); EXPECT_FALSE(runner()->WantsToRun(extension)); }
diff --git a/chrome/browser/extensions/external_provider_impl.cc b/chrome/browser/extensions/external_provider_impl.cc index 550b891..c8696b69 100644 --- a/chrome/browser/extensions/external_provider_impl.cc +++ b/chrome/browser/extensions/external_provider_impl.cc
@@ -160,7 +160,8 @@ // Check if the service is still alive. It is possible that it went // away while |loader_| was working on the FILE thread. - if (!service_) return; + if (!service_) + return; InstallStageTracker* install_stage_tracker = InstallStageTracker::Get(profile_); @@ -170,8 +171,7 @@ InstallStageTracker::InstallCreationStage::SEEN_BY_EXTERNAL_PROVIDER); } - prefs_ = std::make_unique<base::Value::DictStorage>( - std::move(*prefs).TakeDictDeprecated()); + prefs_ = std::make_unique<base::Value::Dict>(std::move(prefs->GetDict())); ready_ = true; // Queries for extensions are allowed from this point. NotifyServiceOnExternalExtensionsFound(); @@ -217,7 +217,7 @@ std::set<std::string> removed_extensions; // Find extensions that were removed by this ExternalProvider. - for (auto& pref : *prefs_) { + for (auto pref : *prefs_) { const std::string& extension_id = pref.first; // Don't bother about invalid ids. if (!crx_file::id_util::IdIsValid(extension_id)) @@ -226,8 +226,7 @@ removed_extensions.insert(extension_id); } - prefs_ = std::make_unique<base::Value::DictStorage>( - std::move(*prefs).TakeDictDeprecated()); + prefs_ = std::make_unique<base::Value::Dict>(std::move(prefs->GetDict())); std::vector<ExternalInstallInfoUpdateUrl> external_update_url_extensions; std::vector<ExternalInstallInfoFile> external_file_extensions; @@ -251,7 +250,7 @@ InstallStageTracker::Get(profile_); // Discover all the extensions this provider has. - for (auto& pref : *prefs_) { + for (auto pref : *prefs_) { const std::string& extension_id = pref.first; const base::DictionaryValue* extension_dict = nullptr; @@ -524,7 +523,7 @@ it != unsupported_extensions.end(); ++it) { // Remove extension for the list of know external extensions. The extension // will be uninstalled later because provider doesn't provide it anymore. - prefs_->erase(prefs_->find(*it)); + prefs_->Remove(*it); } } @@ -541,7 +540,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(prefs_.get()); CHECK(ready_); - return prefs_->find(id) != prefs_->end(); + return prefs_->contains(id); } bool ExternalProviderImpl::GetExtensionDetails( @@ -551,19 +550,18 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(prefs_.get()); CHECK(ready_); - auto it = prefs_->find(id); - if (it == prefs_->end() || !it->second.is_dict()) + base::Value::Dict* dict = prefs_->FindDict(id); + if (!dict) return false; ManifestLocation loc = ManifestLocation::kInvalidLocation; - if (it->second.FindKey(kExternalUpdateUrl)) { + if (dict->contains(kExternalUpdateUrl)) { loc = download_location_; - } else if (it->second.FindKey(kExternalCrx)) { + } else if (dict->contains(kExternalCrx)) { loc = crx_location_; - const std::string* external_version = - it->second.FindStringKey(kExternalVersion); + const std::string* external_version = dict->FindString(kExternalVersion); if (!external_version) return false;
diff --git a/chrome/browser/extensions/external_provider_impl.h b/chrome/browser/extensions/external_provider_impl.h index d80e7d5..b28395f 100644 --- a/chrome/browser/extensions/external_provider_impl.h +++ b/chrome/browser/extensions/external_provider_impl.h
@@ -133,7 +133,7 @@ raw_ptr<VisitorInterface> service_; // weak // Dictionary of the external extensions that are provided by this provider. - std::unique_ptr<base::Value::DictStorage> prefs_; + std::unique_ptr<base::Value::Dict> prefs_; // Indicates that the extensions provided by this provider are loaded // entirely.
diff --git a/chrome/browser/extensions/process_manager_browsertest.cc b/chrome/browser/extensions/process_manager_browsertest.cc index a0bdb4f2..a14ad9e 100644 --- a/chrome/browser/extensions/process_manager_browsertest.cc +++ b/chrome/browser/extensions/process_manager_browsertest.cc
@@ -55,6 +55,7 @@ #include "extensions/test/test_extension_dir.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "third_party/blink/public/common/features.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_switches.h" @@ -876,7 +877,13 @@ // Navigate the popup to each nested URL with extension origin. GURL nested_urls[] = {blob_url, filesystem_url}; - for (size_t i = 0; i < std::size(nested_urls); i++) { + // TODO(https://crbug.com/1332598): Remove filesystem: test branch entirely + // when filesystem: navigation is removed for good. + size_t nested_url_count = + base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation) + ? 2 + : 1; + for (size_t i = 0; i < nested_url_count; i++) { EXPECT_TRUE(ExecuteScript( popup, "location.href = '" + nested_urls[i].spec() + "';")); @@ -909,7 +916,7 @@ // Navigate second subframe to each nested URL from the main frame (i.e., // from non-extension process). These should be canceled. - for (size_t i = 0; i < std::size(nested_urls); i++) { + for (size_t i = 0; i < nested_url_count; i++) { EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", nested_urls[i])); content::RenderFrameHost* second_frame = ChildFrameAt(main_frame, 1); @@ -1048,7 +1055,13 @@ // Navigate second subframe to each nested URL from the main frame (i.e., // from non-extension process). These should be canceled. GURL nested_urls[] = {blob_url, filesystem_url}; - for (size_t i = 0; i < std::size(nested_urls); i++) { + // TODO(https://crbug.com/1332598): Remove filesystem: test branch entirely + // when filesystem: navigation is removed for good. + size_t nested_url_count = + base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation) + ? 2 + : 1; + for (size_t i = 0; i < nested_url_count; i++) { EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", nested_urls[i])); content::RenderFrameHost* second_frame = ChildFrameAt(main_frame, 1); @@ -1095,7 +1108,13 @@ // From the main frame, navigate its subframe to each nested URL. This // should be allowed and should stay in the extension process. GURL nested_urls[] = {blob_url, filesystem_url}; - for (size_t i = 0; i < std::size(nested_urls); i++) { + // TODO(https://crbug.com/1332598): Remove filesystem: test branch entirely + // when filesystem: navigation is removed for good. + size_t nested_url_count = + base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation) + ? 2 + : 1; + for (size_t i = 0; i < nested_url_count; i++) { EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", nested_urls[i])); content::RenderFrameHost* child = ChildFrameAt(main_frame, 0); EXPECT_EQ(nested_urls[i], child->GetLastCommittedURL()); @@ -1135,7 +1154,7 @@ EXPECT_NE(popup, tab); content::WebContentsConsoleObserver console_observer(popup); - console_observer.SetPattern("Not allowed to navigate top frame to*"); + console_observer.SetPattern("Not allowed to navigate to*"); EXPECT_TRUE(ExecuteScript( popup, "location.href = '" + nested_urls[1].spec() + "';")); console_observer.Wait();
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroController.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroController.java index cfef640..8a28c31 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroController.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroController.java
@@ -82,6 +82,8 @@ "intro-appearance-threshold-minutes"; // Time between appearances for the same WebFeedId. private static final long WEB_FEED_ID_APPEARANCE_THRESHOLD_MILLIS = TimeUnit.DAYS.toMillis(1); + // Maximum number of times a WebFeedId is promoted. + private static final long WEB_FEED_ID_MAX_APPEARANCES = 3; /** Clock to use so we can mock time in tests. */ public interface Clock { @@ -182,6 +184,10 @@ mSharedPreferencesManager.writeLong( getWebFeedIntroWebFeedIdShownTimeMsKey(recommendedInfo.webFeedId), currentTimeMillis); + + String showCountKey = getWebFeedIntroWebFeedIdShownCountKey(recommendedInfo.webFeedId); + long readCountBefore = mSharedPreferencesManager.readLong(showCountKey); + mSharedPreferencesManager.writeLong(showCountKey, readCountBefore + 1); } Log.i(TAG, "Allowed intro: all requirements met"); } @@ -305,13 +311,18 @@ long timeSinceLastShownForWebFeed = currentTimeMillis - mSharedPreferencesManager.readLong( getWebFeedIntroWebFeedIdShownTimeMsKey(recommendedInfo.webFeedId)); - if ((timeSinceLastShown < mAppearanceThresholdMillis) - || (timeSinceLastShownForWebFeed < WEB_FEED_ID_APPEARANCE_THRESHOLD_MILLIS)) { + long previousShowCount = mSharedPreferencesManager.readLong( + getWebFeedIntroWebFeedIdShownCountKey(recommendedInfo.webFeedId)); + if (timeSinceLastShown < mAppearanceThresholdMillis + || timeSinceLastShownForWebFeed < WEB_FEED_ID_APPEARANCE_THRESHOLD_MILLIS + || previousShowCount >= WEB_FEED_ID_MAX_APPEARANCES) { Log.i(TAG, "No intro: enoughTimeSinceLastShown=%s, " - + "enoughTimeSinceLastShownForWebFeed=%s", + + "enoughTimeSinceLastShownForWebFeed=%s" + + "tooManyShows=%s", timeSinceLastShown > mAppearanceThresholdMillis, - timeSinceLastShownForWebFeed > WEB_FEED_ID_APPEARANCE_THRESHOLD_MILLIS); + timeSinceLastShownForWebFeed > WEB_FEED_ID_APPEARANCE_THRESHOLD_MILLIS, + previousShowCount >= WEB_FEED_ID_MAX_APPEARANCES); return false; } @@ -323,10 +334,19 @@ Base64.encodeToString(webFeedId, Base64.DEFAULT)); } + private static String getWebFeedIntroWebFeedIdShownCountKey(byte[] webFeedId) { + return ChromePreferenceKeys.WEB_FEED_INTRO_WEB_FEED_ID_SHOWN_COUNT_PREFIX.createKey( + Base64.encodeToString(webFeedId, Base64.DEFAULT)); + } + @VisibleForTesting boolean getIntroShownForTesting() { return mIntroShownForTesting; } + @VisibleForTesting + void clearIntroShownForTesting() { + mIntroShownForTesting = false; + } @VisibleForTesting EmptyTabObserver getEmptyTabObserverForTesting() {
diff --git a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroControllerTest.java b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroControllerTest.java index 13a791f6..9728b24 100644 --- a/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroControllerTest.java +++ b/chrome/browser/feed/android/java/src/org/chromium/chrome/browser/feed/webfeed/WebFeedFollowIntroControllerTest.java
@@ -216,6 +216,56 @@ @Test @SmallTest + public void sameWebFeedIsNotShownMoreThan3Times() { + mBaseTestValues.addFieldTrialParamOverride( + ChromeFeatureList.WEB_FEED, "intro_style", "IPH"); + mBaseTestValues.addFeatureFlagOverride(ChromeFeatureList.SNOOZABLE_IPH, false); + mBaseTestValues.addFeatureFlagOverride(ChromeFeatureList.ENABLE_AUTOMATIC_SNOOZE, false); + mBaseTestValues.addFeatureFlagOverride(ChromeFeatureList.ENABLE_IPH, true); + mBaseTestValues.addFeatureFlagOverride( + ChromeFeatureList.ANDROID_SCROLL_OPTIMIZATIONS, false); + FeatureList.setTestValues(mBaseTestValues); + resetWebFeedFollowIntroController(); + + mWebFeedFollowIntroController.clearIntroShownForTesting(); + setWebFeedIntroLastShownTimeMsPref(0); + setWebFeedIntroWebFeedIdShownTimeMsPref(0); + setVisitCounts(3, 3); + invokePageLoad(WebFeedSubscriptionStatus.NOT_SUBSCRIBED, /*isRecommended=*/true); + advanceClockByMs(SAFE_INTRO_WAIT_TIME_MILLIS); + assertTrue("Intro should be shown first time", + mWebFeedFollowIntroController.getIntroShownForTesting()); + + mWebFeedFollowIntroController.clearIntroShownForTesting(); + setWebFeedIntroLastShownTimeMsPref(0); + setWebFeedIntroWebFeedIdShownTimeMsPref(0); + setVisitCounts(3, 3); + invokePageLoad(WebFeedSubscriptionStatus.NOT_SUBSCRIBED, /*isRecommended=*/true); + advanceClockByMs(SAFE_INTRO_WAIT_TIME_MILLIS); + assertTrue("Intro should be shown second time", + mWebFeedFollowIntroController.getIntroShownForTesting()); + + mWebFeedFollowIntroController.clearIntroShownForTesting(); + setWebFeedIntroLastShownTimeMsPref(0); + setWebFeedIntroWebFeedIdShownTimeMsPref(0); + setVisitCounts(3, 3); + invokePageLoad(WebFeedSubscriptionStatus.NOT_SUBSCRIBED, /*isRecommended=*/true); + advanceClockByMs(SAFE_INTRO_WAIT_TIME_MILLIS); + assertTrue("Intro should be shown third time", + mWebFeedFollowIntroController.getIntroShownForTesting()); + + mWebFeedFollowIntroController.clearIntroShownForTesting(); + setWebFeedIntroLastShownTimeMsPref(0); + setWebFeedIntroWebFeedIdShownTimeMsPref(0); + setVisitCounts(3, 3); + invokePageLoad(WebFeedSubscriptionStatus.NOT_SUBSCRIBED, /*isRecommended=*/true); + advanceClockByMs(SAFE_INTRO_WAIT_TIME_MILLIS); + assertFalse("Intro should NOT be shown fourth time", + mWebFeedFollowIntroController.getIntroShownForTesting()); + } + + @Test + @SmallTest public void noIntroStyleSet_doesNotShowIntro() { FeatureList.setTestValues(new FeatureList.TestValues()); resetWebFeedFollowIntroController();
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index b27a0d03..e3fafa2 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -4848,6 +4848,11 @@ "expiry_milestone": 104 }, { + "name": "partial-split", + "owners": [ "sophiewen", "chromeos-wmp-eng@google.com" ], + "expiry_milestone": 110 + }, + { "name": "partitioned-cookies", "owners": [ "dylancutler" ], "expiry_milestone": 110
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 8d917292..15fe0491 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -5325,6 +5325,10 @@ "Enables the ChromeOS HID Detection Revamp, which updates OOBE HID " "detection screen UI and related infrastructure."; +const char kPartialSplit[] = "Partial Split"; +const char kPartialSplitDescription[] = + "Enables the option to snap windows by thirds for split view."; + const char kPcieBillboardNotificationName[] = "Pcie billboard notification"; const char kPcieBillboardNotificationDescription[] = "Enable Pcie peripheral billboard notification.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index e4bbf55c..d5f6a57 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -3044,6 +3044,9 @@ extern const char kOobeHidDetectionRevampName[]; extern const char kOobeHidDetectionRevampDescription[]; +extern const char kPartialSplit[]; +extern const char kPartialSplitDescription[]; + extern const char kPcieBillboardNotificationName[]; extern const char kPcieBillboardNotificationDescription[];
diff --git a/chrome/browser/media/encrypted_media_supported_types_browsertest.cc b/chrome/browser/media/encrypted_media_supported_types_browsertest.cc index ccc127e1..d96d9c8 100644 --- a/chrome/browser/media/encrypted_media_supported_types_browsertest.cc +++ b/chrome/browser/media/encrypted_media_supported_types_browsertest.cc
@@ -140,6 +140,10 @@ // TODO(crbug.com/1243903): WhatsNewUI might be causing timeouts. disabled_features_.push_back(features::kChromeWhatsNewUI); +#if BUILDFLAG(ENABLE_PLATFORM_HEVC) + enabled_features_.push_back(media::kPlatformHEVCDecoderSupport); +#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) + audio_webm_codecs_.push_back("vorbis"); video_webm_codecs_.push_back("vp8"); @@ -428,6 +432,32 @@ robustness, encryption_scheme); } + void CheckPlatformHevcSupport(const std::string& key_system) { + auto hevc_supported = IsSupportedByKeySystem(key_system, kVideoMP4MimeType, + video_mp4_hevc_codecs()); +#if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) +#if BUILDFLAG(IS_WIN) + // On Windows platforms, HEVC support is detected through the GPU + // capabilities which won't indicate support when running the tests. + // TODO(crbug/1327470): Fix this so that we can inject HEVC support on + // Windows. + EXPECT_UNSUPPORTED(hevc_supported); +#elif BUILDFLAG(IS_MAC) + // On Mac platforms, HEVC support should be available if OS >= Big Sur 11.0 + // and kPlatformHEVCDecoderSupport is enabled. + if (__builtin_available(macOS 11.0, *)) { + EXPECT_ECK_PROPRIETARY(hevc_supported); + } else { + EXPECT_UNSUPPORTED(hevc_supported); + } +#else + EXPECT_ECK_PROPRIETARY(hevc_supported); +#endif // BUILDFLAG(IS_WIN) +#else + EXPECT_UNSUPPORTED(hevc_supported); +#endif // BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) + } + protected: // Features to enable or disable for the test. Must be updated in the test // constructor (before SetUpDefaultCommandLine()) to take effect. @@ -468,9 +498,6 @@ #if BUILDFLAG(ENABLE_LIBRARY_CDMS) EncryptedMediaSupportedTypesExternalClearKeyTest() { enabled_features_.push_back(media::kExternalClearKeyForTesting); -#if BUILDFLAG(ENABLE_PLATFORM_HEVC) - enabled_features_.push_back(media::kPlatformHEVCDecoderSupport); -#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -703,8 +730,9 @@ // Valid video types. EXPECT_PROPRIETARY( IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, video_mp4_codecs())); - EXPECT_UNSUPPORTED(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, - video_mp4_hevc_codecs())); + + CheckPlatformHevcSupport(kClearKey); + EXPECT_SUCCESS(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, vp9_profile0_codecs())); EXPECT_SUCCESS(IsSupportedByKeySystem(kClearKey, kVideoMP4MimeType, @@ -821,29 +849,7 @@ EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( kExternalClearKey, kVideoMP4MimeType, video_mp4_codecs())); - auto hevc_supported = IsSupportedByKeySystem( - kExternalClearKey, kVideoMP4MimeType, video_mp4_hevc_codecs()); -#if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) -#if BUILDFLAG(IS_WIN) - // On Windows platforms, HEVC support is detected through the GPU capabilities - // which won't indicate support when running the tests. - // TODO(crbug/1327470): Fix this so that we can inject HEVC support on - // Windows. - EXPECT_UNSUPPORTED(hevc_supported); -#elif BUILDFLAG(IS_MAC) - // On Mac platforms, HEVC support should be available if OS >= Big Sur 11.0 - // and kPlatformHEVCDecoderSupport is enabled. - if (__builtin_available(macOS 11.0, *)) { - EXPECT_ECK_PROPRIETARY(hevc_supported); - } else { - EXPECT_UNSUPPORTED(hevc_supported); - } -#else - EXPECT_ECK_PROPRIETARY(hevc_supported); -#endif // BUILDFLAG(IS_WIN) -#else - EXPECT_UNSUPPORTED(hevc_supported); -#endif // BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) + CheckPlatformHevcSupport(kExternalClearKey); EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( kExternalClearKey, kAudioMP4MimeType, audio_mp4_codecs())); @@ -955,29 +961,7 @@ EXPECT_ECK_PROPRIETARY(IsSupportedByKeySystem( kExternalClearKey, kVideoMP4MimeType, video_mp4_codecs())); - auto hevc_supported = IsSupportedByKeySystem( - kExternalClearKey, kVideoMP4MimeType, video_mp4_hevc_codecs()); -#if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) -#if BUILDFLAG(IS_WIN) - // On Windows platforms, HEVC support is detected through the GPU capabilities - // which won't indicate support when running the tests. - // TODO(crbug/1327470): Fix this so that we can inject HEVC support on - // Windows. - EXPECT_UNSUPPORTED(hevc_supported); -#elif BUILDFLAG(IS_MAC) - // On Mac platforms, HEVC support should be available if OS >= Big Sur 11.0 - // and kPlatformHEVCDecoderSupport is enabled. - if (__builtin_available(macOS 11.0, *)) { - EXPECT_ECK_PROPRIETARY(hevc_supported); - } else { - EXPECT_UNSUPPORTED(hevc_supported); - } -#else - EXPECT_ECK_PROPRIETARY(hevc_supported); -#endif // BUILDFLAG(IS_WIN) -#else - EXPECT_UNSUPPORTED(hevc_supported); -#endif // BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) + CheckPlatformHevcSupport(kExternalClearKey); EXPECT_ECK(IsSupportedByKeySystem(kExternalClearKey, kVideoMP4MimeType, vp9_profile0_codecs()));
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc index 0ba5e53e..d04a3af 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.cc
@@ -168,55 +168,105 @@ } std::vector<MediaRoute::Id> removed_routes; - std::set_difference(old_routes_.begin(), old_routes_.end(), + std::set_difference(previous_routes_.begin(), previous_routes_.end(), new_routes.begin(), new_routes.end(), std::inserter(removed_routes, removed_routes.end())); - old_routes_ = new_routes; + + std::vector<MediaRoute::Id> added_routes; + std::set_difference(new_routes.begin(), new_routes.end(), + previous_routes_.begin(), previous_routes_.end(), + std::inserter(added_routes, added_routes.end())); + + previous_routes_ = new_routes; + + if (!added_routes.empty()) { + // There should only be 1 element in the |added_routes| set. + DCHECK(added_routes.size() < 2) << "This value should only be 1, since " + "only one route can be added at a time."; + auto first = added_routes.begin(); + added_route_id_ = *first; + + base::PostTaskAndReplyWithResult( + access_code_sink_service_->GetCastMediaSinkServiceImpl() + ->task_runner() + .get(), + FROM_HERE, + base::BindOnce( + &CastMediaSinkServiceImpl::GetSinkById, + base::Unretained( + access_code_sink_service_->GetCastMediaSinkServiceImpl()), + MediaRoute::GetSinkIdFromMediaRouteId(added_route_id_)), + base::BindOnce( + &AccessCodeCastSinkService::HandleMediaRouteAddedByAccessCode, + access_code_sink_service_->GetWeakPtr())); + } // No routes were removed. if (removed_routes.empty()) return; // There should only be 1 element in the |removed_routes| set. - DCHECK(removed_routes.size() < 2); + DCHECK(removed_routes.size() < 2) + << "This value should only be 1, since only one route can be removed at " + "a time."; auto first = removed_routes.begin(); removed_route_id_ = *first; base::PostTaskAndReplyWithResult( - access_code_sink_service_->cast_media_sink_service_impl_->task_runner() + access_code_sink_service_->GetCastMediaSinkServiceImpl() + ->task_runner() .get(), FROM_HERE, base::BindOnce( &CastMediaSinkServiceImpl::GetSinkById, base::Unretained( - access_code_sink_service_->cast_media_sink_service_impl_), + access_code_sink_service_->GetCastMediaSinkServiceImpl()), MediaRoute::GetSinkIdFromMediaRouteId(removed_route_id_)), base::BindOnce( - &AccessCodeCastSinkService::HandleMediaRouteDiscoveredByAccessCode, + &AccessCodeCastSinkService::HandleMediaRouteRemovedByAccessCode, access_code_sink_service_->GetWeakPtr())); } -void AccessCodeCastSinkService::HandleMediaRouteDiscoveredByAccessCode( +bool AccessCodeCastSinkService::IsSinkValidAccessCodeSink( const MediaSinkInternal* sink) { // The route Id did not correspond to a sink for some reason. Return to // avoid nullptr issues. if (!sink) - return; - + return false; if (!sink->is_cast_sink()) { - return; + return false; } - // Check to see if route was created by an access code sink. CastDiscoveryType type = sink->cast_data().discovery_type; if (type != CastDiscoveryType::kAccessCodeManualEntry && - type != CastDiscoveryType::kAccessCodeRememberedDevice) { - return; + type != CastDiscoveryType::kAccessCodeRememberedDevice) { + return false; } + return true; +} +void AccessCodeCastSinkService::HandleMediaRouteAddedByAccessCode( + const MediaSinkInternal* sink) { + if (!IsSinkValidAccessCodeSink(sink)) + return; + + // The timer object exists but Start() has not been called on it yet. + if (current_session_expiration_timers_.count(sink->id())) { + // Normally there is a delay in starting an expiration timer to ensure that + // we don't expire and remove the sink before the route has actually been + // made. Since we can confirm that the route was generated, we can start the + // expiration timer right now instead of waiting for the delay. + StartExpirationTimerWithDelay(sink, base::TimeDelta::FiniteMin()); + } +} + +void AccessCodeCastSinkService::HandleMediaRouteRemovedByAccessCode( + const MediaSinkInternal* sink) { + if (!IsSinkValidAccessCodeSink(sink)) + return; media_router_->GetLogger()->LogInfo( - mojom::LogCategory::kDiscovery, kLoggerComponent, - "An Access Code Cast route has ended.", sink->id(), "", ""); + mojom::LogCategory::kDiscovery, kLoggerComponent, + "An Access Code Cast route has ended.", sink->id(), "", ""); // There are two possible cases here. The common case is that a route for // the specified sink has been terminated by local or remote user @@ -235,15 +285,15 @@ std::move(it->second).Run(AddSinkResultCode::OK, sink->id()); pending_callbacks_.erase(sink->id()); } else { - // Need to pause just a little bit before attempting to remove the sink. - // Sometimes sinks terminate their routes and immediately start another - // (tab content transitions for example), so wait just a little while - // before checking to see if removing the route makes sense. - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&AccessCodeCastSinkService::OnAccessCodeRouteRemoved, - weak_ptr_factory_.GetWeakPtr(), sink), - kExpirationDelay); + // Need to pause just a little bit before attempting to remove the sink. + // Sometimes sinks terminate their routes and immediately start another + // (tab content transitions for example), so wait just a little while + // before checking to see if removing the route makes sense. + task_runner_->PostDelayedTask( + FROM_HERE, + base::BindOnce(&AccessCodeCastSinkService::OnAccessCodeRouteRemoved, + weak_ptr_factory_.GetWeakPtr(), sink), + kExpirationDelay); } } @@ -256,19 +306,19 @@ // another (preseentation). There was a pause before this method was called, // so check again to see if there's an active route for this sink. Only expire // the sink if a new route wasn't established during the pause. - auto route_id = GetActiveRouteId(sink->id()); + auto route = GetActiveRoute(sink->id()); // Only remove the sink if there is still no active routes for this sink. if (base::FeatureList::IsEnabled(features::kAccessCodeCastRememberDevices)) { // If a sink is pending expiration that means we can // remove it from the media router. - if (!route_id.has_value() && pending_expirations_.count(sink->id())) { + if (!route.has_value() && pending_expirations_.count(sink->id())) { RemoveSinkIdFromAllEntries(sink->id()); RemoveMediaSinkFromRouter(sink); pending_expirations_.erase(sink->id()); } } else { - if (!route_id.has_value()) { + if (!route.has_value()) { RemoveMediaSinkFromRouter(sink); } } @@ -348,15 +398,15 @@ // terminate the route before alerting the dialog to discovery success. // This is because any attempt to start a route on a sink that already has // one won't be successful. - auto route_id = GetActiveRouteId(sink.id()); - if (route_id.has_value()) { + auto route = GetActiveRoute(sink.id()); + if (route.has_value()) { media_router_->GetLogger()->LogInfo(mojom::LogCategory::kDiscovery, kLoggerComponent, "There was an existing route when " "discovery occurred, attempting to " "terminate it.", sink.id(), "", ""); - media_router_->TerminateRoute(route_id.value()); + media_router_->TerminateRoute(route.value().media_route_id()); pending_callbacks_.emplace(sink.id(), std::move(add_sink_callback)); } else { std::move(add_sink_callback).Run(AddSinkResultCode::OK, sink.id()); @@ -417,8 +467,8 @@ CreateCastSocketOpenParams(sink))); } -absl::optional<const MediaRoute::Id> -AccessCodeCastSinkService::GetActiveRouteId(const MediaSink::Id& sink_id) { +absl::optional<const MediaRoute> AccessCodeCastSinkService::GetActiveRoute( + const MediaSink::Id& sink_id) { auto routes = media_router_->GetCurrentRoutes(); auto route_it = std::find_if(routes.begin(), routes.end(), [&sink_id](const MediaRoute& route) { @@ -426,7 +476,7 @@ }); if (route_it == routes.end()) return absl::nullopt; - return route_it->media_route_id(); + return *route_it; } cast_channel::CastSocketOpenParams @@ -540,6 +590,15 @@ return; } + // Make sure we include a delay in the case of instant expiration to ensure + // the sink is not removed before the route is created. + StartExpirationTimerWithDelay( + sink, AccessCodeCastSinkService::kExpirationTimerDelay); +} + +void AccessCodeCastSinkService::StartExpirationTimerWithDelay( + const MediaSinkInternal* sink, + base::TimeDelta delay) { // Either retrieve collection or create it if it doesn't exist before an // operation can occur. auto existing_timer = current_session_expiration_timers_.find(sink->id()); @@ -547,17 +606,13 @@ // We must first stop the timer before resetting it. existing_timer->second->Stop(); } + auto expiration_timer = std::make_unique<base::OneShotTimer>(); - // Make sure we include a delay in the case of instant expiration to ensure - // the sink is not removed before the route is created. expiration_timer->Start( - FROM_HERE, - CalculateDurationTillExpiration(sink->id()) + - AccessCodeCastSinkService::kExpirationTimerDelay, + FROM_HERE, CalculateDurationTillExpiration(sink->id()) + delay, base::BindOnce(&AccessCodeCastSinkService::OnExpiration, weak_ptr_factory_.GetWeakPtr(), *sink)); - current_session_expiration_timers_[sink->id()] = std::move(expiration_timer); } @@ -662,10 +717,10 @@ "references.", sink.id(), "", ""); - auto route_id = GetActiveRouteId(sink.id()); + auto route = GetActiveRoute(sink.id()); // The given sink still has an active route, don't remove it yet and wait for // the route to end before we expire it. - if (route_id.has_value()) { + if (route.has_value()) { media_router_->GetLogger()->LogInfo( mojom::LogCategory::kDiscovery, kLoggerComponent, "The sink id: " + sink.id() + @@ -692,10 +747,10 @@ if (!sink) { return; } - DCHECK(!GetActiveRouteId(sink->id()).has_value()) + DCHECK(!GetActiveRoute(sink->id()).has_value()) << "This sink " + sink->id() + " still has an active route, we should not be removing it!"; - if (GetActiveRouteId(sink->id()).has_value()) + if (GetActiveRoute(sink->id()).has_value()) return; media_router_->GetLogger()->LogInfo( mojom::LogCategory::kDiscovery, kLoggerComponent, @@ -761,7 +816,7 @@ // If there is an active route for this sink -- don't attempt to remove it. // In this case we let the Media Router handle removals from the media // router when a network is changed with an active route. - if (GetActiveRouteId(sink_id).has_value()) { + if (GetActiveRoute(sink_id).has_value()) { continue; }
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h index 11cc5ff..77a2b3d 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service.h
@@ -101,18 +101,22 @@ TestChangeNetworkWithRouteActive); FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, TestChangeNetworkWithRouteActiveExpiration); + FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, + TestExpirationTimerWithNoDelayStartedOnRouteAdded); // media_router::MediaRoutesObserver: void OnRoutesUpdated(const std::vector<MediaRoute>& routes) override; // Set of route ids that is updated whenever OnRoutesUpdated is called. - std::vector<MediaRoute::Id> old_routes_; + std::vector<MediaRoute::Id> previous_routes_; MediaRoute::Id removed_route_id_; + MediaRoute::Id added_route_id_; const raw_ptr<AccessCodeCastSinkService> access_code_sink_service_; base::WeakPtrFactory<AccessCodeMediaRoutesObserver> weak_ptr_factory_{this}; }; + // TODO(b/234892353): Remove friend class AccessCodeCastSinkServiceFactory friend class AccessCodeCastSinkServiceFactory; friend class AccessCodeCastSinkServiceTest; friend class AccessCodeCastHandlerTest; @@ -168,6 +172,8 @@ TestChangeNetworkWithRouteActive); FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, TestChangeNetworkWithRouteActiveExpiration); + FRIEND_TEST_ALL_PREFIXES(AccessCodeCastSinkServiceTest, + TestExpirationTimerWithNoDelayStartedOnRouteAdded); // Constructor used for testing. AccessCodeCastSinkService( @@ -189,7 +195,16 @@ MediaSink::Id sink_id, bool channel_opened); - void HandleMediaRouteDiscoveredByAccessCode(const MediaSinkInternal* sink); + bool IsSinkValidAccessCodeSink(const MediaSinkInternal* sink); + + // Handles removal from media router via expiration if a route with an access + // code cast sink has ended. + void HandleMediaRouteRemovedByAccessCode(const MediaSinkInternal* sink); + + // Handles starting of expiration timers if a access code cast route has been + // added via access code casting. + void HandleMediaRouteAddedByAccessCode(const MediaSinkInternal* sink); + void OnAccessCodeRouteRemoved(const MediaSinkInternal* sink); void OpenChannelIfNecessary(const MediaSinkInternal& sink, AddSinkResultCallback add_sink_callback, @@ -201,8 +216,7 @@ // Returns a MediaRoute if the given |sink_id| corresponds to a route // currently active in the media router. - absl::optional<const MediaRoute::Id> GetActiveRouteId( - const MediaSink::Id& sink_id); + absl::optional<const MediaRoute> GetActiveRoute(const MediaSink::Id& sink_id); void InitAllStoredDevices(); void InitExpirationTimers(const std::vector<MediaSinkInternal> cast_sinks); @@ -249,6 +263,12 @@ cast_channel::CastSocketOpenParams CreateCastSocketOpenParams( const MediaSinkInternal& sink); + // This function checks if a timer already exists for the given sink and + // resets it given the new delay. Otherwise it will simply start the timer + // with the given delay. + void StartExpirationTimerWithDelay(const MediaSinkInternal* sink, + base::TimeDelta delay); + // KeyedService. void Shutdown() override; @@ -257,6 +277,11 @@ task_runner_ = task_runner; } + const raw_ptr<media_router::CastMediaSinkServiceImpl> + GetCastMediaSinkServiceImpl() { + return cast_media_sink_service_impl_; + } + // Owns us via the KeyedService mechanism. const raw_ptr<Profile> profile_;
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_factory.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_factory.cc index 31c84fd..2108d05 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_factory.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_factory.cc
@@ -21,8 +21,21 @@ } // GetServiceForBrowserContext returns a KeyedService hence the static_cast<> // to return a pointer to AccessCodeCastSinkService. - return static_cast<AccessCodeCastSinkService*>( - GetInstance()->GetServiceForBrowserContext(profile, false)); + AccessCodeCastSinkService* service = static_cast<AccessCodeCastSinkService*>( + GetInstance()->GetServiceForBrowserContext(profile, /* create */ false)); + if (!service) { + // This can happen in certain cases (notably when a profile has been newly + // created and a null ACCSS was associated with this profile before the + // policies were downloaded. If we passed the above enabled check, then we + // shouldn't have a null ACCSS pointer. So if we do, disassociate the null + // and recreate (b/233285243). + GetInstance()->Disassociate(profile); + service = static_cast<AccessCodeCastSinkService*>( + GetInstance()->GetServiceForBrowserContext(profile, /* create */ true)); + } + DCHECK(service) + << "No AccessCodeCastSinkService found for pref enabled user!"; + return service; } // static
diff --git a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc index 8c01a798..48dc397 100644 --- a/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc +++ b/chrome/browser/media/router/discovery/access_code/access_code_cast_sink_service_unittest.cc
@@ -270,7 +270,7 @@ // Expect cast sink is NOT removed from the media router since it // is not an access code sink. - access_code_cast_sink_service_->HandleMediaRouteDiscoveredByAccessCode( + access_code_cast_sink_service_->HandleMediaRouteRemovedByAccessCode( &cast_sink1); EXPECT_CALL(*mock_cast_media_sink_service_impl(), DisconnectAndRemoveSink(cast_sink1)) @@ -288,7 +288,7 @@ media_route_access.media_route_id()); mock_time_task_runner()->FastForwardUntilNoTasksRemain(); - access_code_cast_sink_service_->HandleMediaRouteDiscoveredByAccessCode( + access_code_cast_sink_service_->HandleMediaRouteRemovedByAccessCode( &access_code_sink2); // Expect that there is a pending attempt to examine the sink to see if it // should be expired. @@ -347,7 +347,7 @@ // Expect cast sink is NOT removed from the media router since it // is not an access code sink. - access_code_cast_sink_service_->HandleMediaRouteDiscoveredByAccessCode( + access_code_cast_sink_service_->HandleMediaRouteRemovedByAccessCode( &cast_sink1); EXPECT_CALL(*mock_cast_media_sink_service_impl(), DisconnectAndRemoveSink(cast_sink1)) @@ -365,7 +365,7 @@ media_route_access.media_route_id()); mock_time_task_runner()->FastForwardUntilNoTasksRemain(); - access_code_cast_sink_service_->HandleMediaRouteDiscoveredByAccessCode( + access_code_cast_sink_service_->HandleMediaRouteRemovedByAccessCode( &access_code_sink2); // Expect that there is a pending attempt to examine the sink to see if it // should be expired. @@ -425,7 +425,7 @@ access_code_cast_sink_service_->media_routes_observer_->removed_route_id_, media_route_cast.media_route_id()); - access_code_cast_sink_service_->HandleMediaRouteDiscoveredByAccessCode( + access_code_cast_sink_service_->HandleMediaRouteRemovedByAccessCode( &cast_sink1); mock_time_task_runner()->FastForwardUntilNoTasksRemain(); } @@ -932,6 +932,55 @@ mock_time_task_runner()->FastForwardUntilNoTasksRemain(); } +TEST_F(AccessCodeCastSinkServiceTest, + TestExpirationTimerWithNoDelayStartedOnRouteAdded) { + // Test to see that an expiration timer will be started (and it will overwrite + // previous starts) IFF a route was successfully added for that sink. + // Otherwise the previous expiration timer with that given delay will hold. + MediaSinkInternal cast_sink1 = CreateCastSink(1); + cast_sink1.cast_data().discovery_type = + CastDiscoveryType::kAccessCodeManualEntry; + SetDeviceDurationPrefForTest(base::Seconds(1)); + mock_cast_media_sink_service_impl()->AddSinkForTest(cast_sink1); + + access_code_cast_sink_service_->StoreSinkAndSetExpirationTimer( + cast_sink1.id()); + FastForwardUiAndIoTasks(); + content::RunAllTasksUntilIdle(); + FastForwardUiAndIoTasks(); + + // Expect the session timer is running. + EXPECT_TRUE(access_code_cast_sink_service_ + ->current_session_expiration_timers_[cast_sink1.id()] + ->IsRunning()); + + // Because we have a delay on timers started before a route is added, going + // forward less than that delay should not expire the sink yet. + task_environment_.FastForwardBy( + AccessCodeCastSinkService::kExpirationTimerDelay - base::Seconds(5)); + + // Add a cast sink discovered by access code to the list of routes. + MediaRoute media_route_access = CreateRouteForTesting(cast_sink1); + std::vector<MediaRoute> route_list = {media_route_access}; + + // Expect that the added_route_id_ member variable includes the newly added + // route. + access_code_cast_sink_service_->media_routes_observer_->OnRoutesUpdated( + route_list); + EXPECT_FALSE(access_code_cast_sink_service_->media_routes_observer_ + ->added_route_id_.empty()); + FastForwardUiAndIoTasks(); + content::RunAllTasksUntilIdle(); + FastForwardUiAndIoTasks(); + + // The timer should now be reset to include no delay since the route was + // successfully added. We now expire it. + task_environment_.FastForwardBy(base::Seconds(2)); + EXPECT_FALSE(access_code_cast_sink_service_ + ->current_session_expiration_timers_[cast_sink1.id()] + ->IsRunning()); +} + TEST_F(AccessCodeCastSinkServiceTest, TestResetExpirationTimersNetworkChange) { // Test to check all expiration timers are restarted after network is changed. SetDeviceDurationPrefForTest(base::Seconds(10000));
diff --git a/chrome/browser/media/webrtc/region_capture_browsertest.cc b/chrome/browser/media/webrtc/region_capture_browsertest.cc index 0e54671..a51adc8 100644 --- a/chrome/browser/media/webrtc/region_capture_browsertest.cc +++ b/chrome/browser/media/webrtc/region_capture_browsertest.cc
@@ -3,13 +3,11 @@ // found in the LICENSE file. #include <memory> -#include <set> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/guid.h" #include "base/memory/raw_ptr.h" #include "base/path_service.h" #include "base/strings/strcat.h" @@ -47,9 +45,15 @@ using testing::Values; using testing::WithParamInterface; -MATCHER(IsValidCropTarget, "") { +// Comparisons with CropTargets are limited. We can only know that a one was +// returned by the test. However, we keep this matcher around in anticipation +// of CropTargets being made either comparable or stringifiable. Then we +// can do more interesting comparisons, like ensuring uniqueness or checking +// that repeatedly calling CropTarget.fromElement() on the same Element yields +// either the same CropTarget, or an equivalent one. +MATCHER_P(IsExpectedCropTarget, expected_crop_target_index, "") { static_assert(std::is_same<decltype(arg), const std::string&>::value, ""); - return base::GUID::ParseLowercase(arg).is_valid(); + return arg == expected_crop_target_index; } const char kMainPageTitle[] = "Region Capture Test - Page 1 (Main)"; @@ -63,6 +67,7 @@ kMainPageEmbeddedDocument, kOtherPageTopLevelDocument, kOtherPageEmbeddedDocument, + kMailmanServer, kServerCount // Must be last. }; @@ -78,6 +83,8 @@ kEmbeddedFrame, }; +enum class Track { kOriginal, kClone }; + // Conveniently pack together all relevant information about a tab and // conveniently expose test controls on it. struct TabInfo { @@ -90,6 +97,15 @@ EXPECT_EQ(script_result, "embedding-done"); } + void SetUpMailman(const GURL& url) { + std::string script_result; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + web_contents->GetMainFrame(), + base::StringPrintf("setUpMailman('%s');", url.spec().c_str()), + &script_result)); + EXPECT_EQ(script_result, "mailman-ready"); + } + void StartCapture() { // Bring the tab into focus. This avoids getDisplayMedia rejection. browser->tab_strip_model()->ActivateTabAt(tab_strip_index); @@ -98,7 +114,7 @@ EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents->GetPrimaryMainFrame(), "startCapture();", &script_result)); - EXPECT_EQ(script_result, "capture-success"); + EXPECT_EQ(script_result, "top-level-capture-success"); } void StartCaptureFromEmbeddedFrame() { @@ -116,7 +132,7 @@ const std::string& element_id = "div") { DCHECK_NE(frame, Frame::kNone); const std::string frame_js = - (frame == Frame::kTopLevelDocument) ? "top" : "embedded"; + (frame == Frame::kTopLevelDocument) ? "top-level" : "embedded"; std::string script_result = "error-not-modified"; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents->GetPrimaryMainFrame(), @@ -126,18 +142,47 @@ return script_result; } - std::string CropTo(const std::string& crop_id) { + // Takes as input either the CropTarget[*], or "undefined" if the test + // wants track.cropTo(undefined) to be invoked. + // [*] Actually, because `CropTarget`s are not stringifiable, an index + // of the CropTarget is used, and translated by JS code back into + // the CropTarget it had stored. + std::string CropTo(const std::string& crop_target, + Track track = Track::kOriginal) { std::string script_result = "error-not-modified"; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents->GetPrimaryMainFrame(), - base::StrCat({"cropTo(\"", crop_id, "\");"}), &script_result)); + base::StringPrintf("cropToByIndex('%s', '%s');", crop_target.c_str(), + track == Track::kOriginal ? "original" : "clone"), + &script_result)); return script_result; } + bool CloneTrack() { + std::string script_result = "error-not-modified"; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + web_contents->GetMainFrame(), "clone();", &script_result)); + DCHECK(script_result == "clone-track-success" || + script_result == "clone-track-failure"); + return script_result == "clone-track-success"; + } + + bool Deallocate(Track track) { + std::string script_result = "error-not-modified"; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + web_contents->GetMainFrame(), + base::StringPrintf("deallocate('%s');", + track == Track::kOriginal ? "original" : "clone"), + &script_result)); + DCHECK(script_result == "deallocate-failure" || + script_result == "deallocate-success"); + return script_result == "deallocate-success"; + } + std::string CreateNewDivElement(Frame frame, const std::string& div_id) { DCHECK_NE(frame, Frame::kNone); const std::string frame_js = - (frame == Frame::kTopLevelDocument) ? "top" : "embedded"; + (frame == Frame::kTopLevelDocument) ? "top-level" : "embedded"; std::string script_result = "error-not-modified"; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents->GetPrimaryMainFrame(), @@ -206,7 +251,6 @@ WebContents* const web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - // web_contents_vector_.push_back(web_contents); permissions::PermissionRequestManager::FromWebContents(web_contents) ->set_auto_response_for_test( permissions::PermissionRequestManager::ACCEPT_ALL); @@ -215,6 +259,12 @@ browser()->tab_strip_model()->active_index()}; tab_info->StartEmbeddingFrame( embedded_iframe_server->GetURL(embedded_iframe_document)); + + // Start embedding a frame whose sole purpose is to be same-origin + // across all other documents and therefore allow communication + // between them all over a shared BroadcastChannel. + tab_info->SetUpMailman(servers_[kMailmanServer]->GetURL( + "/webrtc/region_capture_mailman.html")); } // Set up all (necessary) tabs, loads iframes, and start capturing the @@ -260,21 +310,14 @@ CropTargetFromElementReturnsValidIdInMainPage) { SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); EXPECT_THAT(tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument), - IsValidCropTarget()); + IsExpectedCropTarget("0")); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropTargetFromElementReturnsValidIdInCrossOriginIframe) { SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); EXPECT_THAT(tabs_[kMainTab].CropTargetFromElement(Frame::kEmbeddedFrame), - IsValidCropTarget()); -} - -IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, - CropTargetFromElementReturnsSameIdIfSameElement) { - SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); - EXPECT_EQ(tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument), - tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument)); + IsExpectedCropTarget("0")); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, @@ -282,10 +325,10 @@ SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - EXPECT_EQ(tab.CropTo(crop_id), "top-level-crop-success"); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + EXPECT_EQ(tab.CropTo(crop_target), "top-level-crop-success"); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, @@ -293,9 +336,10 @@ SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = tab.CropTargetFromElement(Frame::kEmbeddedFrame); - ASSERT_THAT(crop_id, IsValidCropTarget()); - EXPECT_EQ(tab.CropTo(crop_id), "top-level-crop-success"); + const std::string crop_target = + tab.CropTargetFromElement(Frame::kEmbeddedFrame); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + EXPECT_EQ(tab.CropTo(crop_target), "top-level-crop-success"); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, @@ -303,10 +347,10 @@ SetUpTest(Frame::kEmbeddedFrame, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - EXPECT_EQ(tab.CropTo(crop_id), "embedded-crop-success"); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + EXPECT_EQ(tab.CropTo(crop_target), "embedded-crop-success"); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, @@ -314,95 +358,52 @@ SetUpTest(Frame::kEmbeddedFrame, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = tab.CropTargetFromElement(Frame::kEmbeddedFrame); - ASSERT_THAT(crop_id, IsValidCropTarget()); - EXPECT_EQ(tab.CropTo(crop_id), "embedded-crop-success"); + const std::string crop_target = + tab.CropTargetFromElement(Frame::kEmbeddedFrame); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + EXPECT_EQ(tab.CropTo(crop_target), "embedded-crop-success"); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToAllowedToUncrop) { SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - ASSERT_EQ(tab.CropTo(crop_id), "top-level-crop-success"); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + ASSERT_EQ(tab.CropTo(crop_target), "top-level-crop-success"); - EXPECT_EQ(tab.CropTo(""), "top-level-crop-success"); + EXPECT_EQ(tab.CropTo("undefined"), "top-level-crop-success"); } -IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToRejectedIfUnknown) { - SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); - TabInfo& tab = tabs_[kMainTab]; - - const std::string crop_id = - tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - - DCHECK(!crop_id.empty()); // Test sanity. - const std::string::value_type wrong_char = (crop_id[0] == 'a' ? 'b' : 'a'); - const std::string wrong_crop_id = wrong_char + crop_id.substr(1); - EXPECT_EQ(tab.CropTo(wrong_crop_id), "top-level-crop-error"); -} - -IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToRejectedIfInvalid) { - SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); - TabInfo& tab = tabs_[kMainTab]; - - const std::string crop_id = - tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - - EXPECT_EQ(tab.CropTo("invalid-crop-target"), "top-level-crop-error"); -} - +// TODO(crbug.com/1333319): Align implementation and specification. +// This is discussed in: https://github.com/w3c/mediacapture-region/issues/60 IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, - CropToRejectedIfCropTargetFromElementWasNeverCalled) { + CropToForUncroppingAllowedOnUncroppedTracks) { SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); TabInfo& tab = tabs_[kMainTab]; - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - - const std::string kValidCropId = "01234567-0123-0123-0123-0123456789ab"; - ASSERT_THAT(kValidCropId, IsValidCropTarget()); // Test is sane. - - EXPECT_EQ(tab.CropTo(kValidCropId), "top-level-crop-error"); -} - -IN_PROC_BROWSER_TEST_F( - RegionCaptureBrowserTest, - CropToForUncroppingRejectedIfCropTargetFromElementWasCalledButTrackUncropped) { - SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); - TabInfo& tab = tabs_[kMainTab]; - - const std::string crop_id = - tab.CropTargetFromElement(Frame::kTopLevelDocument); - ASSERT_THAT(crop_id, IsValidCropTarget()); - // CropTo(crop_id) with a non-empty |crop_id| is intentionally not called. - // Instead, the test immediately calls CropTo("") on a still-uncropped track, - // attempting to stop cropping when no cropping was ever specified. - EXPECT_EQ(tab.CropTo(""), "top-level-crop-success"); + ASSERT_THAT(crop_target, IsExpectedCropTarget("0")); + // CropTo(cropTarget) is intentionally not called. + // Instead, the test immediately calls CropTo(undefined) on a still-uncropped + // track, attempting to stop cropping when no cropping was ever specified. + EXPECT_EQ(tab.CropTo("undefined"), "top-level-crop-success"); } IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, MaxCropIdsInTopLevelDocument) { SetUpTest(Frame::kNone, /*self_capture=*/false); TabInfo& tab = tabs_[kMainTab]; - // Create kMaxCropIdsPerWebContents new elements and assign each a - // crop-target. - std::set<std::string> crop_ids; for (size_t i = 0; i < kMaxCropIdsPerWebContents; ++i) { const std::string element_id = ("new_id_" + base::NumberToString(i)); ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id), "top-level-new-div-success"); - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument, element_id); - ASSERT_THAT(crop_id, IsValidCropTarget()); - crop_ids.insert(crop_id); + ASSERT_THAT(crop_target, IsExpectedCropTarget(base::NumberToString(i))); } - EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents); // Create one more element - this one won't get a crop-target. const std::string element_id = @@ -417,19 +418,14 @@ SetUpTest(Frame::kNone, /*self_capture=*/false); TabInfo& tab = tabs_[kMainTab]; - // Create kMaxCropIdsPerWebContents new elements and assign each a - // crop-target. - std::set<std::string> crop_ids; for (size_t i = 0; i < kMaxCropIdsPerWebContents; ++i) { const std::string element_id = ("new_id_" + base::NumberToString(i)); ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id), "embedded-new-div-success"); - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kEmbeddedFrame, element_id); - ASSERT_THAT(crop_id, IsValidCropTarget()); - crop_ids.insert(crop_id); + ASSERT_THAT(crop_target, IsExpectedCropTarget(base::NumberToString(i))); } - EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents); // Create one more element - this one won't get a crop-target. const std::string element_id = @@ -449,27 +445,24 @@ // Create (kMaxCropIdsPerWebContents - 1) new elements and assign each a // crop-target. - std::set<std::string> crop_ids; for (size_t i = 0; i < kMaxCropIdsPerWebContents - 1; ++i) { const std::string element_id = ("new_id_" + base::NumberToString(i)); ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id), "top-level-new-div-success"); - const std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kTopLevelDocument, element_id); - ASSERT_THAT(crop_id, IsValidCropTarget()); - crop_ids.insert(crop_id); + ASSERT_THAT(crop_target, IsExpectedCropTarget(base::NumberToString(i))); } - EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents - 1); // One more in the embedded frame is possible. std::string element_id = ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents - 1)); ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id), "embedded-new-div-success"); - std::string crop_id = + const std::string crop_target = tab.CropTargetFromElement(Frame::kEmbeddedFrame, element_id); - EXPECT_THAT(crop_id, IsValidCropTarget()); - EXPECT_TRUE(crop_ids.find(crop_id) == crop_ids.end()); + EXPECT_THAT(crop_target, IsExpectedCropTarget(base::NumberToString( + kMaxCropIdsPerWebContents - 1))); // Create one more element - this one won't get a crop-target. element_id = ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents)); @@ -486,6 +479,207 @@ "embedded-produce-crop-target-error"); } +// Tests related to behavior when cloning. +class RegionCaptureClonesBrowserTest : public RegionCaptureBrowserTest { + public: + static const std::string kCropTarget0; + static const std::string kCropTarget1; + + ~RegionCaptureClonesBrowserTest() override = default; + + void SetUpCommandLine(base::CommandLine* command_line) override { + command_line->AppendSwitchASCII("js-flags", "--expose-gc"); + RegionCaptureBrowserTest::SetUpCommandLine(command_line); + } + + // Has to be called from within the test's body. + void ManualSetUp() { + SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true); + EXPECT_THAT( + tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument, "div"), + IsExpectedCropTarget(kCropTarget0)); + EXPECT_THAT(tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument, + "embedded_frame"), + IsExpectedCropTarget(kCropTarget1)); + } + + bool CropTo(const std::string& crop_target, Track track) { + const std::string result = tabs_[kMainTab].CropTo(crop_target, track); + + // This test suite only ever starts the capture from the top-level frame. + DCHECK(result == "top-level-crop-success" || + result == "top-level-crop-error"); + + return result == "top-level-crop-success"; + } + + bool CloneTrack() { return tabs_[kMainTab].CloneTrack(); } + + bool Deallocate(Track track) { return tabs_[kMainTab].Deallocate(track); } +}; + +const std::string RegionCaptureClonesBrowserTest::kCropTarget0 = "0"; +const std::string RegionCaptureClonesBrowserTest::kCropTarget1 = "1"; + +// Sanity cloning 1/2. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanCloneUncroppedTracks) { + ManualSetUp(); + + EXPECT_TRUE(CloneTrack()); +} + +// Sanity cloning 2/2. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, CanCloneCroppedTracks) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + + EXPECT_TRUE(CloneTrack()); +} + +// Restrictions on cloned tracked 1/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, CannotCropClone) { + ManualSetUp(); + + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo(kCropTarget0, Track::kClone)); +} + +// Restrictions on cloned tracked 2/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, CannotRecropClone) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo(kCropTarget1, Track::kClone)); +} + +// Restrictions on cloned tracked 3/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, CannotUncropClone) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo("undefined", Track::kClone)); +} + +// Restrictions on original track that has a clone 1/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CannotCropTrackThatHasClone) { + ManualSetUp(); + + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo(kCropTarget0, Track::kOriginal)); +} + +// Restrictions on original track that has a clone 2/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CannotRecropTrackThatHasClone) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo(kCropTarget1, Track::kOriginal)); +} + +// Restrictions on original track that has a clone 3/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CannotUncropTrackThatHasClone) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + + EXPECT_FALSE(CropTo("undefined", Track::kOriginal)); +} + +// Original track becomes unblocked for cropping after clone is GCed 1/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanCropOriginalTrackAfterCloneIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo(kCropTarget0, Track::kOriginal)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kClone)); + + EXPECT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); +} + +// Original track becomes unblocked for cropping after clone is GCed 2/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanRecropOriginalTrackAfterCloneIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo(kCropTarget1, Track::kOriginal)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kClone)); + + EXPECT_TRUE(CropTo(kCropTarget1, Track::kOriginal)); +} + +// Original track becomes unblocked for cropping after clone is GCed 3/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanUncropOriginalTrackAfterCloneIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo("undefined", Track::kOriginal)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kClone)); + + EXPECT_TRUE(CropTo("undefined", Track::kOriginal)); +} + +// The following tests are disabled because of a loosely-related issue, +// where an original track is kept alive if a clone exists, but not vice versa. +// TODO(crbug.com/1333594): Uncomment after fixing the aforementioned issue. +#if 0 +// Cloned track becomes unblocked for cropping after original is GCed 1/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanCropCloneAfterOriginalTrackIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo(kCropTarget0, Track::kClone)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kOriginal)); + + EXPECT_TRUE(CropTo(kCropTarget0, Track::kClone)); +} + +// Cloned track becomes unblocked for cropping after original is GCed 2/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanRecropCloneAfterOriginalTrackIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo(kCropTarget1, Track::kClone)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kOriginal)); + + EXPECT_TRUE(CropTo(kCropTarget1, Track::kClone)); +} + +// Cloned track becomes unblocked for cropping after original is GCed 3/3. +IN_PROC_BROWSER_TEST_F(RegionCaptureClonesBrowserTest, + CanUncropCloneAfterOriginalTrackIsGarbageCollected) { + ManualSetUp(); + + ASSERT_TRUE(CropTo(kCropTarget0, Track::kOriginal)); + ASSERT_TRUE(CloneTrack()); + ASSERT_FALSE(CropTo("undefined", Track::kClone)); // Sanity. + ASSERT_TRUE(Deallocate(Track::kOriginal)); + + EXPECT_TRUE(CropTo("undefined", Track::kClone)); +} +#endif + // Suite of tests ensuring that only self-capture may crop, and that it may // only crop to targets in its own tab, but that any target in its own tab // is permitted. @@ -547,14 +741,18 @@ // To make things even clearer, ensure both the top-level and the embedded // frame have produced crop-targets. (This should not be necessary, but is // done as an extra buffer against false-positives.) - tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument); - tabs_[kMainTab].CropTargetFromElement(Frame::kEmbeddedFrame); - tabs_[kOtherTab].CropTargetFromElement(Frame::kTopLevelDocument); - tabs_[kOtherTab].CropTargetFromElement(Frame::kEmbeddedFrame); + ASSERT_THAT(tabs_[kMainTab].CropTargetFromElement(Frame::kTopLevelDocument), + IsExpectedCropTarget("0")); + ASSERT_THAT(tabs_[kMainTab].CropTargetFromElement(Frame::kEmbeddedFrame), + IsExpectedCropTarget("1")); + ASSERT_THAT(tabs_[kOtherTab].CropTargetFromElement(Frame::kTopLevelDocument), + IsExpectedCropTarget("2")); + ASSERT_THAT(tabs_[kOtherTab].CropTargetFromElement(Frame::kEmbeddedFrame), + IsExpectedCropTarget("3")); - const std::string crop_id = + const std::string crop_target = tabs_[target_element_tab_].CropTargetFromElement(target_frame_); - ASSERT_THAT(crop_id, IsValidCropTarget()); + ASSERT_THAT(crop_target, IsExpectedCropTarget("4")); // Cropping only permitted if both conditions hold. const bool expect_permitted = @@ -564,7 +762,7 @@ {capturing_entity_ == Frame::kTopLevelDocument ? "top-level" : "embedded", "-", expect_permitted ? "crop-success" : "crop-error"}); - EXPECT_EQ(tabs_[kMainTab].CropTo(crop_id), expected_result); + EXPECT_EQ(tabs_[kMainTab].CropTo(crop_target), expected_result); } #endif // !BUILDFLAG(IS_CHROMEOS_LACROS)
diff --git a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc index a107b0b..2955e5f 100644 --- a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc +++ b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.cc
@@ -308,7 +308,7 @@ void DeviceMediaAsyncFileUtil::CreateOrOpen( std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Returns an error if any unsupported flag is found.
diff --git a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.h b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.h index dd12fde..a8ce24b3 100644 --- a/chrome/browser/media_galleries/fileapi/device_media_async_file_util.h +++ b/chrome/browser/media_galleries/fileapi/device_media_async_file_util.h
@@ -49,7 +49,7 @@ void CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists( std::unique_ptr<storage::FileSystemOperationContext> context,
diff --git a/chrome/browser/media_galleries/fileapi/native_media_file_util.cc b/chrome/browser/media_galleries/fileapi/native_media_file_util.cc index c86a2c4..76349cbe 100644 --- a/chrome/browser/media_galleries/fileapi/native_media_file_util.cc +++ b/chrome/browser/media_galleries/fileapi/native_media_file_util.cc
@@ -209,7 +209,7 @@ // static void NativeMediaFileUtil::CreatedSnapshotFileForCreateOrOpen( base::SequencedTaskRunner* media_task_runner, - int file_flags, + uint32_t file_flags, storage::AsyncFileUtil::CreateOrOpenCallback callback, base::File::Error result, const base::File::Info& file_info, @@ -231,14 +231,15 @@ void NativeMediaFileUtil::CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Returns an error if any unsupported flag is found. if (file_flags & ~(base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_WRITE_ATTRIBUTES)) { - std::move(callback).Run(base::File(base::File::FILE_ERROR_SECURITY), base::OnceClosure()); + std::move(callback).Run(base::File(base::File::FILE_ERROR_SECURITY), + base::OnceClosure()); return; } scoped_refptr<base::SequencedTaskRunner> task_runner = context->task_runner();
diff --git a/chrome/browser/media_galleries/fileapi/native_media_file_util.h b/chrome/browser/media_galleries/fileapi/native_media_file_util.h index bc0912d9..514d088d 100644 --- a/chrome/browser/media_galleries/fileapi/native_media_file_util.h +++ b/chrome/browser/media_galleries/fileapi/native_media_file_util.h
@@ -44,7 +44,7 @@ // DeviceMediaAsyncFileUtil. static void CreatedSnapshotFileForCreateOrOpen( base::SequencedTaskRunner* media_task_runner, - int file_flags, + uint32_t file_flags, storage::AsyncFileUtil::CreateOrOpenCallback callback, base::File::Error result, const base::File::Info& file_info, @@ -55,7 +55,7 @@ void CreateOrOpen( std::unique_ptr<storage::FileSystemOperationContext> context, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists( std::unique_ptr<storage::FileSystemOperationContext> context,
diff --git a/chrome/browser/new_tab_page/new_tab_page_browsertest.cc b/chrome/browser/new_tab_page/new_tab_page_browsertest.cc index 37f00eff..0a35555 100644 --- a/chrome/browser/new_tab_page/new_tab_page_browsertest.cc +++ b/chrome/browser/new_tab_page/new_tab_page_browsertest.cc
@@ -33,7 +33,7 @@ #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || \ (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "base/command_line.h" -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" +#include "ui/views/test/view_skia_gold_pixel_diff.h" #endif class NewTabPageTest : public InProcessBrowserTest, @@ -170,10 +170,10 @@ "browser-ui-tests-verify-pixels")) { return true; } - BrowserSkiaGoldPixelDiff pixel_diff; + views::ViewSkiaGoldPixelDiff pixel_diff; pixel_diff.Init(screenshot_prefix); - return pixel_diff.CompareScreenshot(screenshot_name, - browser_view_->contents_web_view()); + return pixel_diff.CompareViewScreenshot(screenshot_name, + browser_view_->contents_web_view()); #else return true; #endif
diff --git a/chrome/browser/optimization_guide/optimization_guide_keyed_service.h b/chrome/browser/optimization_guide/optimization_guide_keyed_service.h index 78de30c..960df862 100644 --- a/chrome/browser/optimization_guide/optimization_guide_keyed_service.h +++ b/chrome/browser/optimization_guide/optimization_guide_keyed_service.h
@@ -18,7 +18,7 @@ #include "components/optimization_guide/proto/models.pb.h" #if BUILDFLAG(IS_ANDROID) -#include "chrome/browser/android/bookmarks/bookmark_bridge.h" +#include "chrome/browser/bookmarks/android/bookmark_bridge.h" #endif namespace content {
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 769ab63..c7b4ff7 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -457,7 +457,8 @@ TouchToFillWebAuthnCredential::Username(suggestion.label), TouchToFillWebAuthnCredential::DisplayName( suggestion.main_text.value), - TouchToFillWebAuthnCredential::BackendId(suggestion.backend_id)); + TouchToFillWebAuthnCredential::BackendId( + suggestion.template GetPayload<std::string>())); }); }
diff --git a/chrome/browser/password_manager/chrome_webauthn_credentials_delegate.cc b/chrome/browser/password_manager/chrome_webauthn_credentials_delegate.cc index cd563fd..ce22877 100644 --- a/chrome/browser/password_manager/chrome_webauthn_credentials_delegate.cc +++ b/chrome/browser/password_manager/chrome_webauthn_credentials_delegate.cc
@@ -116,9 +116,9 @@ // Android passes the credential ID instead of the user ID, because it // needs the credential ID to directly populate the allowCredentials // list when one is selected. - suggestion.backend_id = base::Base64Encode(credential.cred_id); + suggestion.payload = base::Base64Encode(credential.cred_id); #else - suggestion.backend_id = + suggestion.payload = std::string(credential.user.id.begin(), credential.user.id.end()); #endif suggestions.push_back(std::move(suggestion));
diff --git a/chrome/browser/permissions/permissions_security_model_interactive_uitest.cc b/chrome/browser/permissions/permissions_security_model_interactive_uitest.cc index 3fcc1d0..3b04177 100644 --- a/chrome/browser/permissions/permissions_security_model_interactive_uitest.cc +++ b/chrome/browser/permissions/permissions_security_model_interactive_uitest.cc
@@ -700,6 +700,11 @@ IN_PROC_BROWSER_TEST_F(PermissionsSecurityModelInteractiveUITest, EmbedIframeFileSystem) { + // TODO(https://crbug.com/1332598): Remove this test when removing filesystem: + // navigation for good. + if (!base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation)) + GTEST_SKIP(); + ASSERT_TRUE(embedded_test_server()->Start()); const GURL url(embedded_test_server()->GetURL("/empty.html")); content::RenderFrameHost* main_rfh =
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java index 87578f0..f5a54bcd 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java
@@ -884,6 +884,11 @@ */ public static final KeyPrefix WEB_FEED_INTRO_WEB_FEED_ID_SHOWN_TIME_MS_PREFIX = new KeyPrefix("Chrome.WebFeed.IntroWebFeedIdShownTimeMs.*"); + /** + * Key used to save the number of times the WebFeed intro for the WebFeed ID was shown. + */ + public static final KeyPrefix WEB_FEED_INTRO_WEB_FEED_ID_SHOWN_COUNT_PREFIX = + new KeyPrefix("Chrome.WebFeed.IntroWebFeedIdShownCount.*"); public static final String LOCK_ICON_IN_ADDRESS_BAR_ENABLED = "omnibox.lock_icon_in_address_bar_enabled"; @@ -1056,6 +1061,7 @@ VIDEO_TUTORIALS_SHARE_URL_SET, WEB_FEED_INTRO_LAST_SHOWN_TIME_MS, WEB_FEED_INTRO_WEB_FEED_ID_SHOWN_TIME_MS_PREFIX.pattern(), + WEB_FEED_INTRO_WEB_FEED_ID_SHOWN_COUNT_PREFIX.pattern(), WEB_SIGNIN_ACCOUNT_PICKER_ACTIVE_DISMISSAL_COUNT ); // clang-format on
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index cd952ea4..20ae83b 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -529,6 +529,12 @@ if (ContextMenuMatcher::IsExtensionsCustomCommandId(id)) return 1; + if (autofill::AutofillContextMenuManager::IsAutofillCustomCommandId( + autofill::AutofillContextMenuManager::CommandId(id))) { + // TODO(crbug.com/1325811): Track the autofill items. + return -1; + } + id = CollapseCommandsForUMA(id); const auto& map = GetIdcToUmaMap(type); auto it = map.find(id); @@ -917,6 +923,12 @@ menu_model_.AddSeparator(ui::NORMAL_SEPARATOR); } + if (content_type_->SupportsGroup( + ContextMenuContentType::ITEM_GROUP_AUTOFILL)) { + autofill_context_menu_manager_.AppendTopLevelItems(); + menu_model_.AddSeparator(ui::NORMAL_SEPARATOR); + } + bool media_image = content_type_->SupportsGroup( ContextMenuContentType::ITEM_GROUP_MEDIA_IMAGE); if (media_image) @@ -2198,6 +2210,13 @@ if (ContextMenuMatcher::IsExtensionsCustomCommandId(id)) return extension_items_.IsCommandIdEnabled(id); + // Autofill items. + if (autofill::AutofillContextMenuManager::IsAutofillCustomCommandId( + autofill::AutofillContextMenuManager::CommandId(id))) { + return autofill_context_menu_manager_.IsCommandIdEnabled( + autofill::AutofillContextMenuManager::CommandId(id)); + } + if (id >= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST && id <= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_LAST) { return true; @@ -2455,6 +2474,11 @@ bool RenderViewContextMenu::IsCommandIdVisible(int id) const { if (ContextMenuMatcher::IsExtensionsCustomCommandId(id)) return extension_items_.IsCommandIdVisible(id); + if (autofill::AutofillContextMenuManager::IsAutofillCustomCommandId( + autofill::AutofillContextMenuManager::CommandId(id))) { + return autofill_context_menu_manager_.IsCommandIdVisible( + autofill::AutofillContextMenuManager::CommandId(id)); + } return RenderViewContextMenuBase::IsCommandIdVisible(id); } @@ -2474,6 +2498,17 @@ return; } + if (autofill::AutofillContextMenuManager::IsAutofillCustomCommandId( + autofill::AutofillContextMenuManager::CommandId(id))) { + RenderFrameHost* render_frame_host = GetRenderFrameHost(); + if (render_frame_host) { + autofill_context_menu_manager_.ExecuteCommand( + autofill::AutofillContextMenuManager::CommandId(id), + source_web_contents_, render_frame_host); + } + return; + } + if (id >= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST && id <= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_LAST) { ExecProtocolHandler(event_flags,
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.h b/chrome/browser/renderer_context_menu/render_view_context_menu.h index 929956a..e95f4669 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.h +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.h
@@ -17,6 +17,7 @@ #include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/autofill/autofill_context_menu_manager.h" #include "components/custom_handlers/protocol_handler_registry.h" #include "components/renderer_context_menu/context_menu_content_type.h" #include "components/renderer_context_menu/render_view_context_menu_base.h" @@ -403,6 +404,9 @@ lens_region_search_controller_; #endif + // Responsible for handling autofill related context menu items. + autofill::AutofillContextMenuManager autofill_context_menu_manager_; + base::WeakPtrFactory<RenderViewContextMenu> weak_pointer_factory_{this}; };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn index 9b0df2d..ef5733b 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
@@ -56,7 +56,6 @@ "common/log_types.js", "common/msgs.js", "common/panel_bridge.js", - "common/panel_command.js", "common/panel_menu_data.js", "common/spannable.js", "common/tree_dumper.js", @@ -138,6 +137,7 @@ "common/key_sequence.js", "common/key_util.js", "common/keyboard_handler.js", + "common/panel_command.js", "common/tts_base.js", "learn_mode/learn_mode.js", "log_page/log.js",
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js index d46fab2..e4e9a861 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/background.js
@@ -24,6 +24,7 @@ import {ChromeVoxPrefs} from '/chromevox/background/prefs.js'; import {RangeAutomationHandler} from '/chromevox/background/range_automation_handler.js'; import {ExtensionBridge} from '/chromevox/common/extension_bridge.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; import {JaPhoneticMap} from '/chromevox/third_party/tamachiyomi/ja_phonetic_map.js'; import {InstanceChecker} from '/common/instance_checker.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_captions_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_captions_background.js index f08e22f2..ef4bde4 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_captions_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/braille/braille_captions_background.js
@@ -8,6 +8,7 @@ * other platforms. */ import {ChromeVoxPrefs} from '/chromevox/background/prefs.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; export class BrailleCaptionsBackground { /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js index 0f46fb4..2e14a71f 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/command_handler.js
@@ -22,6 +22,7 @@ import {CustomAutomationEvent} from '/chromevox/common/custom_automation_event.js'; import {GestureGranularity} from '/chromevox/common/gesture_command_data.js'; import {ChromeVoxKbHandler} from '/chromevox/common/keyboard_handler.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; import {EventGenerator} from '/common/event_generator.js'; const ActionType = chrome.automation.ActionType;
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js index dfd2481..bd60b05 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/loader.js
@@ -41,8 +41,6 @@ goog.require('OutputSelectionSpan'); goog.require('OutputSpeechProperties'); goog.require('PanelBridge'); -goog.require('PanelCommand'); -goog.require('PanelCommandType'); goog.require('PanelNodeMenuData'); goog.require('PanelTabMenuItemData'); goog.require('PhoneticData');
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js index eb37079..c2fa8297 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/tts_background.js
@@ -8,6 +8,7 @@ */ import {AbstractTts} from '/chromevox/common/abstract_tts.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; import {ChromeTtsBase} from '/chromevox/common/tts_base.js'; const Utterance = class {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js index c7cacfc..d8ccfe4c 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js
@@ -7,6 +7,7 @@ */ import {Output} from '/chromevox/background/output/output.js'; import {KeySequence} from '/chromevox/common/key_sequence.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; /** * The types of actions we want to monitor.
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/panel_command.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/panel_command.js index aa480a7d..5c9a62a 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/panel_command.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/panel_command.js
@@ -7,13 +7,10 @@ * to the ChromeVox Panel. */ -goog.provide('PanelCommand'); -goog.provide('PanelCommandType'); - /** * Create one command to pass to the ChromeVox Panel. */ -PanelCommand = class { +export class PanelCommand { /** * @param {PanelCommandType} type The type of command. * @param {string|{groups:Array}=} opt_data @@ -62,14 +59,14 @@ const panelWindow = this.getPanelWindow(); panelWindow.postMessage(JSON.stringify(this), window.location.origin); } -}; +} /** * Possible panel commands. * @enum {string} */ -PanelCommandType = { +export const PanelCommandType = { CLEAR_SPEECH: 'clear_speech', ADD_NORMAL_SPEECH: 'add_normal_speech', ADD_ANNOTATION_SPEECH: 'add_annotation_speech',
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js index c6b1dce..f77cb01 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options.js
@@ -8,6 +8,7 @@ import {AbstractTts} from '/chromevox/common/abstract_tts.js'; import {BrailleTable} from '/chromevox/common/braille/braille_table.js'; import {ExtensionBridge} from '/chromevox/common/extension_bridge.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; import {BluetoothBrailleDisplayUI} from '/chromevox/options/bluetooth_braille_display_ui.js'; /** @const {string} */
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_loader.js b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_loader.js index 4e83cdb4..b640f2a 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_loader.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_loader.js
@@ -13,7 +13,6 @@ goog.require('ExtraCellsSpan'); goog.require('LibLouis'); goog.require('Msgs'); -goog.require('PanelCommand'); goog.require('Spannable'); goog.require('SpeechLog'); goog.require('TtsInterface');
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js index 7480273..a4ea4dbf 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel.js
@@ -10,6 +10,7 @@ import {GestureCommandData} from '/chromevox/common/gesture_command_data.js'; import {KeyMap} from '/chromevox/common/key_map.js'; import {KeyUtil} from '/chromevox/common/key_util.js'; +import {PanelCommand, PanelCommandType} from '/chromevox/common/panel_command.js'; import {ISearchUI} from '/chromevox/panel/i_search_ui.js'; import {PanelInterface} from '/chromevox/panel/panel_interface.js'; import {PanelMenu, PanelNodeMenu, PanelSearchMenu} from '/chromevox/panel/panel_menu.js';
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js index 91854fdb..33411ee2 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_loader.js
@@ -31,8 +31,6 @@ goog.require('OutputRulesStr'); goog.require('OutputSelectionSpan'); goog.require('OutputSpeechProperties'); -goog.require('PanelCommand'); -goog.require('PanelCommandType'); goog.require('PanelNodeMenuData'); goog.require('PanelNodeMenuItemData'); goog.require('QueueMode');
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js index b12717d..f9662cc 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test.js
@@ -14,6 +14,9 @@ await super.setUpDeferred(); await importModule( 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); + await importModule( + ['PanelCommand', 'PanelCommandType'], + '/chromevox/common/panel_command.js'); } fireMockEvent(key) {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test_base.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test_base.js index 1db3358..ecb86ee 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test_base.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/panel_test_base.js
@@ -12,6 +12,9 @@ /** @override */ async setUpDeferred() { await super.setUpDeferred(); + await importModule( + ['PanelCommand', 'PanelCommandType'], + '/chromevox/common/panel_command.js'); await new PanelCommand(PanelCommandType.ENABLE_TEST_HOOKS).send(); }
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js index 3ac42f15..682cadd 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/panel/tutorial_test.js
@@ -17,6 +17,9 @@ 'ChromeVoxState', '/chromevox/background/chromevox_state.js'); await importModule( 'UserActionMonitor', '/chromevox/background/user_action_monitor.js'); + await importModule( + ['PanelCommand', 'PanelCommandType'], + '/chromevox/common/panel_command.js'); } assertActiveLessonIndex(expectedIndex) {
diff --git a/chrome/browser/resources/settings/controls/extension_controlled_indicator.html b/chrome/browser/resources/settings/controls/extension_controlled_indicator.html index 9dc58b4..347a28e66 100644 --- a/chrome/browser/resources/settings/controls/extension_controlled_indicator.html +++ b/chrome/browser/resources/settings/controls/extension_controlled_indicator.html
@@ -11,6 +11,18 @@ margin-inline-end: 16px; } + iron-icon[icon='cr:open-in-new'] { + fill: var(--text-color); + height: var(--cr-icon-size); + margin-inline-end: -10px; + margin-inline-start: 6px; + width: var(--cr-icon-size); + } + + #disable { + margin-inline-start: 8px; + } + /* Using ">" operator to ensure that this CSS rule will not accidentally * be applied to a search highlight span (which is inserted dynamically if * when search "hit" occurs within this element. */ @@ -20,7 +32,11 @@ } </style> <img role="presentation" src="chrome://extension-icon/[[extensionId]]/20/1"> -<span inner-h-t-m-l="[[getLabel_(extensionId, extensionName)]]"></span> +<span>[[getLabel_(extensionName)]]</span> +<cr-button id="manage" on-click="onManageClick_"> + $i18n{manage} + <iron-icon icon="cr:open-in-new"></iron-icon> +</cr-button> <template is="dom-if" if="[[extensionCanBeDisabled]]" restamp> - <cr-button on-click="onDisableTap_">$i18n{disable}</cr-button> + <cr-button id="disable" on-click="onDisableClick_">$i18n{disable}</cr-button> </template>
diff --git a/chrome/browser/resources/settings/controls/extension_controlled_indicator.ts b/chrome/browser/resources/settings/controls/extension_controlled_indicator.ts index c96eacce..f2d4f5ed 100644 --- a/chrome/browser/resources/settings/controls/extension_controlled_indicator.ts +++ b/chrome/browser/resources/settings/controls/extension_controlled_indicator.ts
@@ -7,17 +7,15 @@ import '../settings_shared_css.js'; import {assert} from '//resources/js/assert_ts.js'; -import {I18nMixin} from '//resources/js/i18n_mixin.js'; +import {loadTimeData} from '//resources/js/load_time_data.m.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ExtensionControlBrowserProxyImpl} from '../extension_control_browser_proxy.js'; +import {OpenWindowProxyImpl} from '../open_window_proxy.js'; import {getTemplate} from './extension_controlled_indicator.html.js'; -const ExtensionControlledIndicatorElementBase = I18nMixin(PolymerElement); - -export class ExtensionControlledIndicatorElement extends - ExtensionControlledIndicatorElementBase { +export class ExtensionControlledIndicatorElement extends PolymerElement { static get is() { return 'extension-controlled-indicator'; } @@ -39,19 +37,15 @@ extensionName: string; private getLabel_(): string { - if (this.extensionId === undefined || this.extensionName === undefined) { - return ''; - } - - const manageUrl = 'chrome://extensions/?id=' + this.extensionId; - return this.i18nAdvanced('controlledByExtension', { - substitutions: - ['<a href="' + manageUrl + '" target="_blank">' + this.extensionName + - '</a>'], - }); + return loadTimeData.getStringF('controlledByExtension', this.extensionName); } - private onDisableTap_() { + private onManageClick_() { + const manageUrl = 'chrome://extensions/?id=' + this.extensionId; + OpenWindowProxyImpl.getInstance().openURL(manageUrl); + } + + private onDisableClick_() { assert(this.extensionCanBeDisabled); ExtensionControlBrowserProxyImpl.getInstance().disableExtension( this.extensionId);
diff --git a/chrome/browser/segmentation_platform/segmentation_platform_config.cc b/chrome/browser/segmentation_platform/segmentation_platform_config.cc index 5296acc..230cd16 100644 --- a/chrome/browser/segmentation_platform/segmentation_platform_config.cc +++ b/chrome/browser/segmentation_platform/segmentation_platform_config.cc
@@ -231,7 +231,7 @@ std::unique_ptr<ModelProvider> GetFeedUserSegmentDefautlModel() { if (!base::GetFieldTrialParamByFeatureAsBool( features::kSegmentationPlatformFeedSegmentFeature, - kDefaultModelEnabledParam, false)) { + kDefaultModelEnabledParam, true)) { return nullptr; } return std::make_unique<FeedUserSegment>();
diff --git a/chrome/browser/sync_file_system/local/syncable_file_system_operation.cc b/chrome/browser/sync_file_system/local/syncable_file_system_operation.cc index 018fd81..4415536 100644 --- a/chrome/browser/sync_file_system/local/syncable_file_system_operation.cc +++ b/chrome/browser/sync_file_system/local/syncable_file_system_operation.cc
@@ -296,7 +296,7 @@ } void SyncableFileSystemOperation::OpenFile(const FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) { NOTREACHED(); }
diff --git a/chrome/browser/sync_file_system/local/syncable_file_system_operation.h b/chrome/browser/sync_file_system/local/syncable_file_system_operation.h index 93c1dcf..30c0eec 100644 --- a/chrome/browser/sync_file_system/local/syncable_file_system_operation.h +++ b/chrome/browser/sync_file_system/local/syncable_file_system_operation.h
@@ -94,7 +94,7 @@ const base::Time& last_modified_time, StatusCallback callback) override; void OpenFile(const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) override; void Cancel(StatusCallback cancel_callback) override; void CreateSnapshotFile(const storage::FileSystemURL& path,
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 130aaaa4..90d46129 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -3252,8 +3252,7 @@ "platform_keys_certificate_selector_chromeos.h", "tabs/existing_window_sub_menu_model_chromeos.cc", "tabs/existing_window_sub_menu_model_chromeos.h", - "views/extensions/print_job_confirmation_dialog_view.cc", - "views/extensions/print_job_confirmation_dialog_view.h", + "views/extensions/print_job_confirmation_dialog.cc", "views/frame/browser_frame_header_chromeos.cc", "views/frame/browser_frame_header_chromeos.h", "views/frame/browser_non_client_frame_view_chromeos.cc",
diff --git a/chrome/browser/ui/android/omnibox/java/res/values/dimens.xml b/chrome/browser/ui/android/omnibox/java/res/values/dimens.xml index 00ef090d..43761f2 100644 --- a/chrome/browser/ui/android/omnibox/java/res/values/dimens.xml +++ b/chrome/browser/ui/android/omnibox/java/res/values/dimens.xml
@@ -71,7 +71,6 @@ <dimen name="omnibox_suggestion_action_icon_width">48dp</dimen> <dimen name="omnibox_suggestion_refine_view_modern_end_padding">4dp</dimen> - <dimen name="omnibox_suggestion_carousel_horizontal_spacing">8dp</dimen> <!-- Adding search engine logo to the omnibox. --> <!-- Max size which will fit completely in the composed/rounded bg. -->
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java index 4aba9ff..0cc7f43d 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java
@@ -170,7 +170,8 @@ mDropdownViewInfoListBuilder = new DropdownItemViewInfoListBuilder( activityTabSupplier, bookmarkState, exploreIconProvider, omniboxPedalDelegate); mDropdownViewInfoListBuilder.setShareDelegateSupplier(shareDelegateSupplier); - mDropdownViewInfoListManager = new DropdownItemViewInfoListManager(mSuggestionModels); + mDropdownViewInfoListManager = + new DropdownItemViewInfoListManager(mSuggestionModels, context); } /**
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManager.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManager.java index 1e7bd8a..b36bdee 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManager.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/DropdownItemViewInfoListManager.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.omnibox.suggestions; +import android.content.Context; import android.util.SparseArray; import android.util.SparseBooleanArray; import android.view.View; @@ -12,6 +13,7 @@ import org.chromium.chrome.browser.ui.theme.BrandedColorScheme; import org.chromium.components.omnibox.AutocompleteResult; +import org.chromium.ui.base.DeviceFormFactor; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; @@ -22,14 +24,16 @@ /** Manages the list of DropdownItemViewInfo elements. */ class DropdownItemViewInfoListManager { + private final Context mContext; private final ModelList mManagedModel; private final SparseBooleanArray mGroupsCollapsedState; private int mLayoutDirection; private @BrandedColorScheme int mBrandedColorScheme; private List<DropdownItemViewInfo> mSourceViewInfoList; - DropdownItemViewInfoListManager(@NonNull ModelList managedModel) { + DropdownItemViewInfoListManager(@NonNull ModelList managedModel, @NonNull Context context) { assert managedModel != null : "Must specify a non-null model."; + mContext = context; mLayoutDirection = View.LAYOUT_DIRECTION_INHERIT; mBrandedColorScheme = BrandedColorScheme.LIGHT_BRANDED_THEME; mSourceViewInfoList = Collections.emptyList(); @@ -125,11 +129,15 @@ // Build a new list of suggestions. Honor the default collapsed state. final List<ListItem> suggestionsList = new ArrayList<>(); + int deviceType = DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext) + ? SuggestionCommonProperties.FormFactor.TABLET + : SuggestionCommonProperties.FormFactor.PHONE; for (int i = 0; i < mSourceViewInfoList.size(); i++) { final DropdownItemViewInfo item = mSourceViewInfoList.get(i); final PropertyModel model = item.model; model.set(SuggestionCommonProperties.LAYOUT_DIRECTION, mLayoutDirection); model.set(SuggestionCommonProperties.COLOR_SCHEME, mBrandedColorScheme); + model.set(SuggestionCommonProperties.DEVICE_FORM_FACTOR, deviceType); final boolean groupIsDefaultCollapsed = getGroupCollapsedState(item.groupId); if (!groupIsDefaultCollapsed || isGroupHeaderWithId(item, item.groupId)) {
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionCommonProperties.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionCommonProperties.java index 1cf01f1..de8d9a56 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionCommonProperties.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionCommonProperties.java
@@ -4,17 +4,34 @@ package org.chromium.chrome.browser.omnibox.suggestions; +import androidx.annotation.IntDef; + import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableIntPropertyKey; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + /** * The set of common properties associated with any omnibox suggestion. */ public class SuggestionCommonProperties { + /** Enum for identifying the device type */ + @IntDef({FormFactor.UNKOWN, FormFactor.PHONE, FormFactor.TABLET}) + @Retention(RetentionPolicy.SOURCE) + public @interface FormFactor { + int UNKOWN = 0; + int PHONE = 1; + int TABLET = 2; + } + /** Whether dark colors should be applied to text, icons. */ public static final WritableIntPropertyKey COLOR_SCHEME = new WritableIntPropertyKey(); /** The layout direction to be applied to the entire suggestion view. */ public static final WritableIntPropertyKey LAYOUT_DIRECTION = new WritableIntPropertyKey(); + /** The device type for calculating the tile margin in the suggestion view. */ + public static final WritableIntPropertyKey DEVICE_FORM_FACTOR = new WritableIntPropertyKey(); - public static final PropertyKey[] ALL_KEYS = new PropertyKey[] {COLOR_SCHEME, LAYOUT_DIRECTION}; + public static final PropertyKey[] ALL_KEYS = + new PropertyKey[] {COLOR_SCHEME, LAYOUT_DIRECTION, DEVICE_FORM_FACTOR}; }
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java index ba28f4f2..ac59d9d 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionView.java
@@ -27,6 +27,7 @@ private final HeaderView mHeader; private final RecyclerView mRecyclerView; private final BaseCarouselSuggestionSelectionManager mSelectionManager; + private int mItemSpacingPx; /** * Constructs a new carousel suggestion view. @@ -64,15 +65,12 @@ new BaseCarouselSuggestionSelectionManager(mRecyclerView.getLayoutManager()); mRecyclerView.addOnChildAttachStateChangeListener(mSelectionManager); - final int itemSpacing = context.getResources().getDimensionPixelOffset( - R.dimen.omnibox_suggestion_carousel_horizontal_spacing); - mRecyclerView.addItemDecoration(new ItemDecoration() { @Override public void getItemOffsets( Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { - outRect.left = itemSpacing; - outRect.right = itemSpacing; + outRect.left = mItemSpacingPx; + outRect.right = mItemSpacingPx; } }); @@ -123,4 +121,14 @@ public RecyclerView getRecyclerViewForTest() { return mRecyclerView; } + + /** + * Applies a new item spacing to the carousel. + * + * @param itemSpacingPx The requested item spacing, expressed in Pixels. + */ + public void setItemSpacingPx(int itemSpacingPx) { + mItemSpacingPx = itemSpacingPx; + mRecyclerView.requestLayout(); + } }
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java index 963c23c..8e3fba0f 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinder.java
@@ -4,9 +4,14 @@ package org.chromium.chrome.browser.omnibox.suggestions.carousel; +import android.content.res.Resources; import android.view.View; +import androidx.annotation.NonNull; + import org.chromium.chrome.browser.omnibox.R; +import org.chromium.chrome.browser.omnibox.suggestions.SuggestionCommonProperties; +import org.chromium.chrome.browser.omnibox.suggestions.SuggestionCommonProperties.FormFactor; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -43,6 +48,35 @@ headerView.setVisibility(View.GONE); view.setPaddingRelative(0, verticalPad, 0, verticalPad); } + } else if (key == SuggestionCommonProperties.DEVICE_FORM_FACTOR) { + view.setItemSpacingPx(getItemSpacingPx( + model.get(SuggestionCommonProperties.DEVICE_FORM_FACTOR), view.getResources())); + } + } + + /** + * Calculate the margin between tiles based on screen size. + * + * @param formFactor the form factor of the device, from which we differentiate between PHONE + * and TABLET. + * @param resources Android resources object, used to read the dimension. + * @return The requested item spacing, expressed in Pixels. + */ + static int getItemSpacingPx(@FormFactor int formFactor, @NonNull Resources resources) { + int tileViewPortraitEdgePadding = + resources.getDimensionPixelSize(R.dimen.tile_view_padding_edge_portrait); + switch (formFactor) { + case FormFactor.PHONE: + int screenWidth = resources.getDisplayMetrics().widthPixels; + int tileViewWidth = resources.getDimensionPixelOffset(R.dimen.tile_view_width); + return Integer.max(-resources.getDimensionPixelOffset(R.dimen.tile_view_padding), + (int) ((screenWidth - tileViewPortraitEdgePadding - tileViewWidth * 4.7) + / 4)); + case FormFactor.TABLET: + return tileViewPortraitEdgePadding; + default: + assert false : "Unknown device type"; + return 0; } } }
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java index 73315b2..24508ed3 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/carousel/BaseCarouselSuggestionViewBinderUnitTest.java
@@ -13,6 +13,7 @@ import static org.mockito.Mockito.when; import android.content.res.Resources; +import android.util.DisplayMetrics; import android.view.View; import android.widget.TextView; @@ -26,6 +27,8 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.R; +import org.chromium.chrome.browser.omnibox.suggestions.SuggestionCommonProperties; +import org.chromium.chrome.browser.omnibox.suggestions.SuggestionCommonProperties.FormFactor; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; @@ -144,4 +147,77 @@ eq(SUGGESTION_VERTICAL_PADDING)); verify(mView, times(2)).setPaddingRelative(anyInt(), anyInt(), anyInt(), anyInt()); } + + /** + * We expect value to be computed as the tile margin value computed is larger than + * tile_view_padding + */ + @Test + public void formFactor_itemSpacingPhone_computed() { + int displayWidth = 1000; + int tileViewPaddingEdgePortrait = 300; + int tileViewwidth = 100; + int tileViewPadding = 15; + when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) + .thenReturn(tileViewPaddingEdgePortrait); + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_width))) + .thenReturn(tileViewwidth); + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_padding))) + .thenReturn(tileViewPadding); + + DisplayMetrics displayMetrics = new DisplayMetrics(); + displayMetrics.widthPixels = displayWidth; + when(mResources.getDisplayMetrics()).thenReturn(displayMetrics); + + final int expectedSpacingPx = + (int) ((displayWidth - tileViewPaddingEdgePortrait - tileViewwidth * 4.7) / 4); + Assert.assertEquals(expectedSpacingPx, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.PHONE, mResources)); + } + + /** + * We expect value to be fixed as tile_view_padding is larger than the tile margin value + * computed + */ + @Test + public void formFactor_itemSpacingPhone_fixed() { + int displayWidth = 0; + int tileViewPaddingEdgePortrait = 0; + int tileViewwidth = 0; + int tileViewPadding = -15; + when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) + .thenReturn(tileViewPaddingEdgePortrait); + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_width))) + .thenReturn(tileViewwidth); + when(mResources.getDimensionPixelOffset(eq(R.dimen.tile_view_padding))) + .thenReturn(tileViewPadding); + + DisplayMetrics displayMetrics = new DisplayMetrics(); + displayMetrics.widthPixels = displayWidth; + when(mResources.getDisplayMetrics()).thenReturn(displayMetrics); + + final int expectedSpacingPx = -tileViewPadding; + Assert.assertEquals(expectedSpacingPx, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.PHONE, mResources)); + } + + @Test + public void formFactor_itemSpacingTablet() { + final int paddingPx = 100; + when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) + .thenReturn(paddingPx); + Assert.assertEquals(paddingPx, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.TABLET, mResources)); + } + + @Test + public void formFactor_itemSpacingEndToEnd() { + final int spacingPx = 100; + when(mResources.getDimensionPixelSize(eq(R.dimen.tile_view_padding_edge_portrait))) + .thenReturn(spacingPx); + Assert.assertEquals(spacingPx, + BaseCarouselSuggestionViewBinder.getItemSpacingPx(FormFactor.TABLET, mResources)); + mModel.set(SuggestionCommonProperties.DEVICE_FORM_FACTOR, FormFactor.TABLET); + verify(mView, times(1)).setItemSpacingPx(eq(spacingPx)); + } }
diff --git a/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.cc b/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.cc index 4514966..d7a85107 100644 --- a/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.cc +++ b/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.cc
@@ -6,6 +6,8 @@ #include <memory> +#include "base/bind.h" +#include "base/location.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/projector/projector_client_impl.h" #include "ui/base/metadata/metadata_impl_macros.h" @@ -23,6 +25,17 @@ views::WebContentsSetBackgroundColor::CreateForWebContentsWithColor( web_contents, SK_ColorTRANSPARENT); + // Loading the annotator app in `web_view_` can take a long time, so in order + // to avoid stalling the initialization of recording, we will do this + // asynchronously. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&RecordingOverlayViewImpl::InitializeAnnotator, + weak_ptr_factory_.GetWeakPtr())); +} + +RecordingOverlayViewImpl::~RecordingOverlayViewImpl() = default; + +void RecordingOverlayViewImpl::InitializeAnnotator() { ProjectorClientImpl::InitForProjectorAnnotator(web_view_); }
diff --git a/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.h b/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.h index f30a53a..40ab89ef 100644 --- a/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.h +++ b/chrome/browser/ui/ash/capture_mode/recording_overlay_view_impl.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_ASH_CAPTURE_MODE_RECORDING_OVERLAY_VIEW_IMPL_H_ #include "ash/public/cpp/capture_mode/recording_overlay_view.h" +#include "base/memory/weak_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" class Profile; @@ -24,12 +25,17 @@ explicit RecordingOverlayViewImpl(Profile* profile); RecordingOverlayViewImpl(const RecordingOverlayViewImpl&) = delete; RecordingOverlayViewImpl& operator=(const RecordingOverlayViewImpl&) = delete; - ~RecordingOverlayViewImpl() override = default; + ~RecordingOverlayViewImpl() override; views::WebView* GetWebViewForTest() { return web_view_; } private: + // Initializes `web_view_` to load the annotator app. + void InitializeAnnotator(); + views::WebView* web_view_; + + base::WeakPtrFactory<RecordingOverlayViewImpl> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_UI_ASH_CAPTURE_MODE_RECORDING_OVERLAY_VIEW_IMPL_H_
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc index 63d24ef..7d8bf0d 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc
@@ -357,7 +357,7 @@ } delegate_->DidAcceptSuggestion(suggestion.main_text.value, - suggestion.frontend_id, suggestion.backend_id, + suggestion.frontend_id, suggestion.payload, index); } @@ -486,10 +486,10 @@ view_->OnSelectedRowChanged(previous_selected_line, selected_line_); if (selected_line_) { - delegate_->DidSelectSuggestion( - suggestions_[*selected_line_].main_text.value, - suggestions_[*selected_line_].frontend_id, - suggestions_[*selected_line_].backend_id); + const Suggestion& suggestion = suggestions_[*selected_line_]; + delegate_->DidSelectSuggestion(suggestion.main_text.value, + suggestion.frontend_id, + suggestion.GetPayload<std::string>()); } else { delegate_->ClearPreviewedForm(); }
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc index 85004e5..63cc74f 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_unittest.cc
@@ -26,6 +26,7 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/ui/popup_item_ids.h" +#include "components/autofill/core/browser/ui/suggestion.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_contents.h" #include "testing/gmock/include/gmock/gmock.h" @@ -118,8 +119,9 @@ MOCK_METHOD0(ClearPreviewedForm, void()); MOCK_METHOD0(OnPopupSuppressed, void()); - MOCK_METHOD4(DidAcceptSuggestion, - void(const std::u16string&, int, const std::string&, int)); + MOCK_METHOD4( + DidAcceptSuggestion, + void(const std::u16string&, int, const Suggestion::Payload&, int)); }; class MockAutofillPopupView : public AutofillPopupView {
diff --git a/chrome/browser/ui/browser_dialogs.h b/chrome/browser/ui/browser_dialogs.h index fd71eb5a..df9f83d 100644 --- a/chrome/browser/ui/browser_dialogs.h +++ b/chrome/browser/ui/browser_dialogs.h
@@ -242,23 +242,6 @@ // user interaction. void SetAutoAcceptPWAInstallConfirmationForTesting(bool auto_accept); -#if BUILDFLAG(IS_CHROMEOS) - -// Shows the print job confirmation dialog bubble anchored to the toolbar icon -// for the extension. -// If there's no toolbar icon, shows a modal dialog using -// CreateBrowserModalDialogViews(). Note that this dialog is shown up even if we -// have no |parent| window. -void ShowPrintJobConfirmationDialog(gfx::NativeWindow parent, - const std::string& extension_id, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback); - -#endif // BUILDFLAG(IS_CHROMEOS) - #if BUILDFLAG(IS_MAC) // Bridging methods that show/hide the toolkit-views based Task Manager on Mac.
diff --git a/chrome/browser/ui/extensions/extension_action_view_controller.cc b/chrome/browser/ui/extensions/extension_action_view_controller.cc index c9cdf4a..ea65bd16 100644 --- a/chrome/browser/ui/extensions/extension_action_view_controller.cc +++ b/chrome/browser/ui/extensions/extension_action_view_controller.cc
@@ -31,6 +31,7 @@ #include "chrome/grit/generated_resources.h" #include "components/sessions/content/session_tab_helper.h" #include "content/public/browser/web_contents.h" +#include "extensions/browser/blocked_action_type.h" #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_action_manager.h" #include "extensions/browser/extension_registry.h" @@ -94,6 +95,23 @@ return false; } +// static +bool ExtensionActionViewController::AnyActionRequiresPageRefreshToRun( + const std::vector<ToolbarActionViewController*>& actions, + content::WebContents* web_contents) { + ExtensionActionRunner* action_runner = + ExtensionActionRunner::GetForWebContents(web_contents); + + return std::any_of( + actions.begin(), actions.end(), + [action_runner](ToolbarActionViewController* action) { + auto blocked_actions = + action_runner->GetBlockedActions(action->GetId()); + return blocked_actions & + ExtensionActionRunner::kRefreshRequiredActionsMask; + }); +} + ExtensionActionViewController::ExtensionActionViewController( scoped_refptr<const extensions::Extension> extension, Browser* browser,
diff --git a/chrome/browser/ui/extensions/extension_action_view_controller.h b/chrome/browser/ui/extensions/extension_action_view_controller.h index 7248884..1a83d837 100644 --- a/chrome/browser/ui/extensions/extension_action_view_controller.h +++ b/chrome/browser/ui/extensions/extension_action_view_controller.h
@@ -54,6 +54,12 @@ const std::vector<std::unique_ptr<ToolbarActionViewController>>& actions, content::WebContents* web_contents); + // Returns whether any of `actions` need a page refresh to execute its action + // in `web_contents`. + static bool AnyActionRequiresPageRefreshToRun( + const std::vector<ToolbarActionViewController*>& actions, + content::WebContents* web_contents); + ExtensionActionViewController(const ExtensionActionViewController&) = delete; ExtensionActionViewController& operator=( const ExtensionActionViewController&) = delete;
diff --git a/chrome/browser/ui/extensions/extensions_dialogs.h b/chrome/browser/ui/extensions/extensions_dialogs.h index ddf76cfa..2a91a15 100644 --- a/chrome/browser/ui/extensions/extensions_dialogs.h +++ b/chrome/browser/ui/extensions/extensions_dialogs.h
@@ -6,10 +6,17 @@ #define CHROME_BROWSER_UI_EXTENSIONS_EXTENSIONS_DIALOGS_H_ #include "base/callback_forward.h" +#include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "extensions/common/extension_id.h" +#include "ui/gfx/native_widget_types.h" class Browser; +namespace gfx { +class ImageSkia; +} // namespace gfx + namespace extensions { // Shows a dialog when an extension requires a refresh after gaining access to @@ -21,6 +28,23 @@ bool show_checkbox, base::OnceCallback<void(bool)> callback); +#if BUILDFLAG(IS_CHROMEOS) + +// Shows the print job confirmation dialog bubble anchored to the toolbar icon +// for the extension. +// If there's no toolbar icon, shows a modal dialog using +// CreateBrowserModalDialogViews(). Note that this dialog is shown even if there +// is no `parent` window. +void ShowPrintJobConfirmationDialog(gfx::NativeWindow parent, + const ExtensionId& extension_id, + const std::u16string& extension_name, + const gfx::ImageSkia& extension_icon, + const std::u16string& print_job_title, + const std::u16string& printer_name, + base::OnceCallback<void(bool)> callback); + +#endif // BUILDFLAG(IS_CHROMEOS) + } // namespace extensions #endif // CHROME_BROWSER_UI_EXTENSIONS_EXTENSIONS_DIALOGS_H_
diff --git a/chrome/browser/ui/quick_answers/BUILD.gn b/chrome/browser/ui/quick_answers/BUILD.gn index fd11ab9..49ffc8f 100644 --- a/chrome/browser/ui/quick_answers/BUILD.gn +++ b/chrome/browser/ui/quick_answers/BUILD.gn
@@ -8,8 +8,6 @@ source_set("quick_answers") { sources = [ - "quick_answers_access_token_fetcher.cc", - "quick_answers_access_token_fetcher.h", "quick_answers_controller_impl.cc", "quick_answers_controller_impl.h", "quick_answers_ui_controller.cc",
diff --git a/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.cc b/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.cc deleted file mode 100644 index 23b9093..0000000 --- a/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.cc +++ /dev/null
@@ -1,118 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.h" - -#include "base/logging.h" -#include "base/rand_util.h" -#include "base/time/time.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/signin/identity_manager_factory.h" -#include "components/account_id/account_id.h" -#include "components/signin/public/base/consent_level.h" -#include "components/signin/public/identity_manager/access_token_fetcher.h" -#include "components/signin/public/identity_manager/access_token_info.h" -#include "components/signin/public/identity_manager/identity_manager.h" -#include "components/signin/public/identity_manager/scope_set.h" - -namespace { - -constexpr char kCloudTranslationScope[] = - "https://www.googleapis.com/auth/cloud-translation"; - -constexpr base::TimeDelta kMinTokenRefreshDelay = base::Milliseconds(1000); -constexpr base::TimeDelta kMaxTokenRefreshDelay = base::Milliseconds(60 * 1000); - -} // namespace - -QuickAnswersAccessTokenFetcher::QuickAnswersAccessTokenFetcher() = default; - -QuickAnswersAccessTokenFetcher::~QuickAnswersAccessTokenFetcher() = default; - -void QuickAnswersAccessTokenFetcher::RequestAccessToken( - AccessTokenCallback callback) { - if (!access_token_.empty()) { - // Return the token if there is enough time to use the access token when - // requested. - if (expiration_time_ - base::Time::Now() > token_usage_time_buffer_) { - std::move(callback).Run(access_token_); - return; - } - - access_token_.clear(); - expiration_time_ = base::Time::Now(); - } - - callbacks_.emplace_back(std::move(callback)); - - // There is already pending request. - if (access_token_fetcher_) - return; - - RefreshAccessToken(); -} - -void QuickAnswersAccessTokenFetcher::RefreshAccessToken() { - auto* profile = ProfileManager::GetActiveUserProfile(); - DCHECK(profile); - - signin::IdentityManager* identity_manager = - IdentityManagerFactory::GetForProfile(profile); - DCHECK(identity_manager); - - CoreAccountInfo account_info = - identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin); - - const signin::ScopeSet scopes{kCloudTranslationScope}; - DCHECK(!access_token_fetcher_); - access_token_fetcher_ = identity_manager->CreateAccessTokenFetcherForAccount( - account_info.account_id, /*oauth_consumer_name=*/"cros_quick_answers", - scopes, - base::BindOnce(&QuickAnswersAccessTokenFetcher::OnAccessTokenRefreshed, - weak_factory_.GetWeakPtr()), - signin::AccessTokenFetcher::Mode::kImmediate); -} - -void QuickAnswersAccessTokenFetcher::OnAccessTokenRefreshed( - GoogleServiceAuthError error, - signin::AccessTokenInfo access_token_info) { - // It's safe to delete AccessTokenFetcher from inside its own callback. - access_token_fetcher_.reset(); - - if (error.state() != GoogleServiceAuthError::NONE) { - LOG(ERROR) << "Failed to retrieve token, error: " << error.ToString(); - RetryRefreshAccessToken(); - return; - } - - VLOG(1) << "Access token fetched."; - access_token_ = access_token_info.token; - expiration_time_ = access_token_info.expiration_time; - NotifyAccessTokenRefreshed(); -} - -void QuickAnswersAccessTokenFetcher::RetryRefreshAccessToken() { - base::TimeDelta backoff_delay = - std::min(kMinTokenRefreshDelay * - (1 << (token_refresh_error_backoff_factor_ - 1)), - kMaxTokenRefreshDelay) + - base::RandDouble() * kMinTokenRefreshDelay; - - if (backoff_delay < kMaxTokenRefreshDelay) - ++token_refresh_error_backoff_factor_; - - token_refresh_timer_.Start( - FROM_HERE, backoff_delay, - base::BindOnce(&QuickAnswersAccessTokenFetcher::RefreshAccessToken, - weak_factory_.GetWeakPtr())); -} - -void QuickAnswersAccessTokenFetcher::NotifyAccessTokenRefreshed() { - std::vector<AccessTokenCallback> callbacks; - callbacks.swap(callbacks_); - - for (auto& callback : callbacks) - std::move(callback).Run(access_token_); -}
diff --git a/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.h b/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.h deleted file mode 100644 index b7c9e29..0000000 --- a/chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_QUICK_ANSWERS_QUICK_ANSWERS_ACCESS_TOKEN_FETCHER_H_ -#define CHROME_BROWSER_UI_QUICK_ANSWERS_QUICK_ANSWERS_ACCESS_TOKEN_FETCHER_H_ - -#include <string> -#include <vector> - -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "base/timer/timer.h" - -class GoogleServiceAuthError; - -namespace signin { -class AccessTokenFetcher; -struct AccessTokenInfo; -} // namespace signin - -// A helper class which provide access token for quick answers. -class QuickAnswersAccessTokenFetcher { - public: - using AccessTokenCallback = - base::OnceCallback<void(const std::string& access_token)>; - - QuickAnswersAccessTokenFetcher(); - - QuickAnswersAccessTokenFetcher(const QuickAnswersAccessTokenFetcher&) = - delete; - QuickAnswersAccessTokenFetcher& operator=( - const QuickAnswersAccessTokenFetcher&) = delete; - - ~QuickAnswersAccessTokenFetcher(); - - void RequestAccessToken(AccessTokenCallback callback); - - private: - void RefreshAccessToken(); - void OnAccessTokenRefreshed(GoogleServiceAuthError error, - signin::AccessTokenInfo access_token_info); - void RetryRefreshAccessToken(); - void NotifyAccessTokenRefreshed(); - - std::string access_token_; - - std::unique_ptr<signin::AccessTokenFetcher> access_token_fetcher_; - - // The expiration time of the |access_token_|. - base::Time expiration_time_; - - // The buffer time to use the access token. - base::TimeDelta token_usage_time_buffer_ = base::Minutes(1); - - base::OneShotTimer token_refresh_timer_; - int token_refresh_error_backoff_factor_ = 1; - - std::vector<AccessTokenCallback> callbacks_; - - base::WeakPtrFactory<QuickAnswersAccessTokenFetcher> weak_factory_{this}; -}; - -#endif // CHROME_BROWSER_UI_QUICK_ANSWERS_QUICK_ANSWERS_ACCESS_TOKEN_FETCHER_H_
diff --git a/chrome/browser/ui/quick_answers/quick_answers_controller_impl.cc b/chrome/browser/ui/quick_answers/quick_answers_controller_impl.cc index 4e5889e..566601b 100644 --- a/chrome/browser/ui/quick_answers/quick_answers_controller_impl.cc +++ b/chrome/browser/ui/quick_answers/quick_answers_controller_impl.cc
@@ -69,9 +69,7 @@ QuickAnswersControllerImpl::QuickAnswersControllerImpl() : quick_answers_ui_controller_( - std::make_unique<QuickAnswersUiController>(this)), - quick_answers_access_token_fetcher_( - std::make_unique<QuickAnswersAccessTokenFetcher>()) { + std::make_unique<QuickAnswersUiController>(this)) { #if BUILDFLAG(IS_CHROMEOS_ASH) quick_answers_state_ = std::make_unique<QuickAnswersStateAsh>(); #elif BUILDFLAG(IS_CHROMEOS_LACROS) @@ -232,11 +230,6 @@ HandleQuickAnswerRequest(processed_request); } -void QuickAnswersControllerImpl::RequestAccessToken( - AccessTokenCallback callback) { - quick_answers_access_token_fetcher_->RequestAccessToken(std::move(callback)); -} - void QuickAnswersControllerImpl::OnRetryQuickAnswersRequest() { QuickAnswersRequest request = BuildRequest(); if (QuickAnswersState::Get()->ShouldUseQuickAnswersTextAnnotator()) {
diff --git a/chrome/browser/ui/quick_answers/quick_answers_controller_impl.h b/chrome/browser/ui/quick_answers/quick_answers_controller_impl.h index 4f32406..c42b114 100644 --- a/chrome/browser/ui/quick_answers/quick_answers_controller_impl.h +++ b/chrome/browser/ui/quick_answers/quick_answers_controller_impl.h
@@ -8,7 +8,6 @@ #include <memory> #include <string> -#include "chrome/browser/ui/quick_answers/quick_answers_access_token_fetcher.h" #include "chromeos/components/quick_answers/public/cpp/controller/quick_answers_controller.h" #include "chromeos/components/quick_answers/quick_answers_client.h" #include "chromeos/components/quick_answers/quick_answers_model.h" @@ -22,9 +21,6 @@ class QuickAnswersControllerImpl : public QuickAnswersController, public quick_answers::QuickAnswersDelegate { public: - using AccessTokenCallback = - base::OnceCallback<void(const std::string& access_token)>; - QuickAnswersControllerImpl(); QuickAnswersControllerImpl(const QuickAnswersControllerImpl&) = delete; QuickAnswersControllerImpl& operator=(const QuickAnswersControllerImpl&) = @@ -59,7 +55,6 @@ void OnNetworkError() override; void OnRequestPreprocessFinished( const quick_answers::QuickAnswersRequest& processed_request) override; - void RequestAccessToken(AccessTokenCallback callback) override; // Retry sending quick answers request to backend. void OnRetryQuickAnswersRequest(); @@ -105,9 +100,6 @@ std::unique_ptr<QuickAnswersUiController> quick_answers_ui_controller_; - std::unique_ptr<QuickAnswersAccessTokenFetcher> - quick_answers_access_token_fetcher_; - // The last received QuickAnswer from client. std::unique_ptr<quick_answers::QuickAnswer> quick_answer_;
diff --git a/chrome/browser/ui/test/test_browser_ui.cc b/chrome/browser/ui/test/test_browser_ui.cc index dde48777..e72607b 100644 --- a/chrome/browser/ui/test/test_browser_ui.cc +++ b/chrome/browser/ui/test/test_browser_ui.cc
@@ -17,9 +17,9 @@ // of lacros-chrome is complete. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || \ (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" #include "ui/base/test/skia_gold_matching_algorithm.h" #include "ui/compositor/test/draw_waiter_for_test.h" +#include "ui/views/test/view_skia_gold_pixel_diff.h" #include "ui/views/widget/widget.h" #endif @@ -99,10 +99,10 @@ auto* compositor = view->GetWidget()->GetCompositor(); ui::DrawWaiterForTest::WaitForCompositingEnded(compositor); - BrowserSkiaGoldPixelDiff pixel_diff; + views::ViewSkiaGoldPixelDiff pixel_diff; pixel_diff.Init(screenshot_prefix); - return pixel_diff.CompareScreenshot(screenshot_name, view, - GetPixelMatchAlgorithm()); + return pixel_diff.CompareViewScreenshot(screenshot_name, view, + GetPixelMatchAlgorithm()); } void TestBrowserUi::SetPixelMatchAlgorithm(
diff --git a/chrome/browser/ui/views/accessibility/caption_bubble_controller_views_browsertest.cc b/chrome/browser/ui/views/accessibility/caption_bubble_controller_views_browsertest.cc index 0277773e..8737a1ba 100644 --- a/chrome/browser/ui/views/accessibility/caption_bubble_controller_views_browsertest.cc +++ b/chrome/browser/ui/views/accessibility/caption_bubble_controller_views_browsertest.cc
@@ -132,6 +132,11 @@ return controller_ && controller_->IsWidgetVisibleForTesting(); } + bool HasMediaFoundationError() { + return controller_ && + controller_->caption_bubble_->HasMediaFoundationError(); + } + void DestroyController() { controller_.reset(nullptr); } void ClickButton(views::Button* button) { @@ -175,6 +180,19 @@ [](CaptionBubbleErrorType error_type, bool checked) {})); } + void OnMediaFoundationError() { + OnMediaFoundationError(GetCaptionBubbleContext()); + } + + void OnMediaFoundationError(CaptionBubbleContext* caption_bubble_context) { + GetController()->OnError( + caption_bubble_context, + CaptionBubbleErrorType::MEDIA_FOUNDATION_RENDERER_UNSUPPORTED, + base::RepeatingClosure(), + base::BindRepeating( + [](CaptionBubbleErrorType error_type, bool checked) {})); + } + void OnAudioStreamEnd() { GetController()->OnAudioStreamEnd(GetCaptionBubbleContext()); } @@ -1101,4 +1119,35 @@ // app but the tests aren't working. } +IN_PROC_BROWSER_TEST_F(CaptionBubbleControllerViewsTest, + ErrorHidesAfterInactivity) { + // Use a ScopedMockTimeMessageLoopTaskRunner to test the inactivity timer with + // a mock tick clock that replaces the default tick clock with mock time. + base::ScopedMockTimeMessageLoopTaskRunner test_task_runner; + SetTickClockForTesting(test_task_runner->GetMockTickClock()); + + OnError(); + EXPECT_TRUE(IsWidgetVisible()); + EXPECT_FALSE(HasMediaFoundationError()); + EXPECT_EQ("", GetLabelText()); + ASSERT_TRUE(GetBubble()->GetInactivityTimerForTesting()->IsRunning()); + + // Verify that the caption bubble hides due to inactivity. + test_task_runner->FastForwardBy(base::Seconds(15)); + EXPECT_FALSE(IsWidgetVisible()); + EXPECT_EQ("", GetLabelText()); + + OnMediaFoundationError(); + EXPECT_TRUE(IsWidgetVisible()); + EXPECT_TRUE(HasMediaFoundationError()); + EXPECT_EQ("", GetLabelText()); + ASSERT_TRUE(GetBubble()->GetInactivityTimerForTesting()->IsRunning()); + + // The Media Foundation renderer unsupported error should not hide to due + // inactivity. + test_task_runner->FastForwardBy(base::Seconds(15)); + EXPECT_TRUE(IsWidgetVisible()); + EXPECT_EQ("", GetLabelText()); +} + } // namespace captions
diff --git a/chrome/browser/ui/views/extensions/extensions_request_access_button.cc b/chrome/browser/ui/views/extensions/extensions_request_access_button.cc index 587e824b..f542b49 100644 --- a/chrome/browser/ui/views/extensions/extensions_request_access_button.cc +++ b/chrome/browser/ui/views/extensions/extensions_request_access_button.cc
@@ -3,11 +3,13 @@ // found in the LICENSE file. #include "chrome/browser/ui/views/extensions/extensions_request_access_button.h" + #include <memory> #include "base/bind.h" #include "base/check_op.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/extensions/extension_action_view_controller.h" #include "chrome/browser/ui/views/extensions/extensions_dialogs_utils.h" #include "chrome/browser/ui/views/extensions/extensions_request_access_button_hover_card.h" #include "chrome/browser/ui/views/extensions/extensions_request_access_dialog_view.h" @@ -46,7 +48,7 @@ return; ExtensionsRequestAccessButtonHoverCard::ShowBubble( - web_contents(), this, extensions_requesting_access_); + GetActiveWebContents(), this, extensions_requesting_access_); } std::u16string ExtensionsRequestAccessButton::GetTooltipText( @@ -59,10 +61,21 @@ ExtensionsToolbarContainer* const container = GetExtensionsToolbarContainer(browser_); DCHECK(container); - views::View* const anchor_view = container->GetExtensionsButton(); - ShowExtensionsRequestAccessDialogView(web_contents(), anchor_view, - extensions_requesting_access_); + content::WebContents* web_contents = GetActiveWebContents(); + views::View* const anchor_view = container->GetExtensionsButton(); + bool requires_refresh = + ExtensionActionViewController::AnyActionRequiresPageRefreshToRun( + extensions_requesting_access_, web_contents); + + if (requires_refresh) { + // TODO(crbug.com/1319555): Display blocked action dialog. Currently, the + // dialog only supports one extension, and here we can have multiple + // extensions. + } else { + ShowExtensionsRequestAccessDialogView(web_contents, anchor_view, + extensions_requesting_access_); + } } // Linux enter/leave events are sometimes flaky, so we don't want to "miss" @@ -81,6 +94,6 @@ ExtensionsRequestAccessButtonHoverCard::HideBubble(); } -content::WebContents* ExtensionsRequestAccessButton::web_contents() { +content::WebContents* ExtensionsRequestAccessButton::GetActiveWebContents() { return browser_->tab_strip_model()->GetActiveWebContents(); }
diff --git a/chrome/browser/ui/views/extensions/extensions_request_access_button.h b/chrome/browser/ui/views/extensions/extensions_request_access_button.h index a4d1a2c..5ec0349 100644 --- a/chrome/browser/ui/views/extensions/extensions_request_access_button.h +++ b/chrome/browser/ui/views/extensions/extensions_request_access_button.h
@@ -42,7 +42,7 @@ private: void OnButtonPressed(); - content::WebContents* web_contents(); + content::WebContents* GetActiveWebContents(); raw_ptr<Browser> browser_;
diff --git a/chrome/browser/ui/views/extensions/extensions_toolbar_controls_unittest.cc b/chrome/browser/ui/views/extensions/extensions_toolbar_controls_unittest.cc index f99bf22..5acab38 100644 --- a/chrome/browser/ui/views/extensions/extensions_toolbar_controls_unittest.cc +++ b/chrome/browser/ui/views/extensions/extensions_toolbar_controls_unittest.cc
@@ -289,3 +289,6 @@ // the current site to verify no extension should have access to the current // site. Uninstall extension in unit tests is flaky. } + +// TODO(crbug.com/3671898): Add a test that checks the correct dialog is open +// when clicking on request access button.
diff --git a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc new file mode 100644 index 0000000..b1c95924 --- /dev/null +++ b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog.cc
@@ -0,0 +1,79 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/bind.h" +#include "base/callback_forward.h" +#include "chrome/browser/ui/views/extensions/extensions_dialogs_utils.h" +#include "chrome/grit/generated_resources.h" +#include "extensions/common/constants.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/image/image_skia_operations.h" + +namespace { + +class PrintJobConfirmationDialogDelegate : public ui::DialogModelDelegate { + public: + explicit PrintJobConfirmationDialogDelegate( + base::OnceCallback<void(bool)> callback) + : callback_(std::move(callback)) {} + + void OnDialogAccepted() { std::move(callback_).Run(true); } + void OnDialogClosed() { std::move(callback_).Run(false); } + + private: + base::OnceCallback<void(bool)> callback_; +}; + +} // namespace + +namespace extensions { + +void ShowPrintJobConfirmationDialog(gfx::NativeWindow parent, + const extensions::ExtensionId& extension_id, + const std::u16string& extension_name, + const gfx::ImageSkia& extension_icon, + const std::u16string& print_job_title, + const std::u16string& printer_name, + base::OnceCallback<void(bool)> callback) { + auto bubble_delegate_unique = + std::make_unique<PrintJobConfirmationDialogDelegate>(std::move(callback)); + PrintJobConfirmationDialogDelegate* bubble_delegate = + bubble_delegate_unique.get(); + + auto dialog_model = + ui::DialogModel::Builder(std::move(bubble_delegate_unique)) + .SetTitle(l10n_util::GetStringUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_BUBBLE_TITLE)) + .OverrideShowCloseButton(false) + .SetIcon(ui::ImageModel::FromImageSkia( + gfx::ImageSkiaOperations::CreateResizedImage( + extension_icon, + skia::ImageOperations::ResizeMethod::RESIZE_GOOD, + gfx::Size(extension_misc::EXTENSION_ICON_SMALL, + extension_misc::EXTENSION_ICON_SMALL)))) + .AddOkButton( + base::BindOnce( + &PrintJobConfirmationDialogDelegate::OnDialogAccepted, + base::Unretained(bubble_delegate)), + l10n_util::GetStringUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_ALLOW)) + .AddCancelButton( + base::BindOnce( + &PrintJobConfirmationDialogDelegate::OnDialogClosed, + base::Unretained(bubble_delegate)), + l10n_util::GetStringUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_DENY)) + .AddBodyText( + ui::DialogModelLabel( + l10n_util::GetStringFUTF16( + IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_BUBBLE_HEADING, + extension_name, print_job_title, printer_name)) + .set_is_secondary() + .set_allow_character_break()) + .Build(); + + ShowDialog(parent, extension_id, std::move(dialog_model)); +} + +} // namespace extensions
diff --git a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.cc b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.cc deleted file mode 100644 index fa95c73..0000000 --- a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.cc +++ /dev/null
@@ -1,138 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.h" - -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "chrome/browser/ui/views/chrome_typography.h" -#include "chrome/browser/ui/views/extensions/extensions_dialogs_utils.h" -#include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h" -#include "chrome/grit/generated_resources.h" -#include "components/constrained_window/constrained_window_views.h" -#include "components/strings/grit/components_strings.h" -#include "content/public/browser/browser_context.h" -#include "extensions/common/constants.h" -#include "extensions/common/extension.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/metadata/metadata_impl_macros.h" -#include "ui/display/screen.h" -#include "ui/gfx/geometry/insets.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/views/controls/label.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/widget/widget.h" - -// static -void PrintJobConfirmationDialogView::Show( - gfx::NativeWindow parent, - const extensions::ExtensionId& extension_id, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback) { - // TODO(crbug.com/1330637): Migrate PrintJobConfirmationDialogView to use - // DialogModel. Then, we can use ShowDialog(container, extension_id, - // dialog_model) helper method. - ExtensionsToolbarContainer* container = GetExtensionsToolbarContainer(parent); - views::View* anchor_view = - container ? GetDialogAnchorView(container, extension_id) : nullptr; - auto* dialog_view = new PrintJobConfirmationDialogView( - anchor_view, extension_name, extension_icon, print_job_title, - printer_name, std::move(callback)); - - if (container) { - views::Widget* const widget = - views::BubbleDialogDelegateView::CreateBubble(dialog_view); - container->ShowWidgetForExtension(widget, extension_id); - } else { - // We may want to show dialog even if there is no appropriate browser view - // or container, i.e. `parent` is null or kNullNativeWindow. - constrained_window::CreateBrowserModalDialogViews(dialog_view, parent) - ->Show(); - } -} - -PrintJobConfirmationDialogView::PrintJobConfirmationDialogView( - views::View* anchor_view, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback) - : BubbleDialogDelegateView(anchor_view, - anchor_view ? views::BubbleBorder::TOP_RIGHT - : views::BubbleBorder::NONE), - callback_(std::move(callback)) { - SetButtonLabel(ui::DIALOG_BUTTON_OK, - l10n_util::GetStringUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_ALLOW)); - SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, - l10n_util::GetStringUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_DENY)); - SetShowCloseButton(false); - SetShowIcon(true); - SetIcon(gfx::ImageSkiaOperations::CreateResizedImage( - extension_icon, skia::ImageOperations::ResizeMethod::RESIZE_GOOD, - gfx::Size(extension_misc::EXTENSION_ICON_SMALL, - extension_misc::EXTENSION_ICON_SMALL))); - SetTitle(l10n_util::GetStringUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_BUBBLE_TITLE)); - - auto run_callback = [](PrintJobConfirmationDialogView* dialog, bool accept) { - std::move(dialog->callback_).Run(accept); - }; - SetAcceptCallback(base::BindOnce(run_callback, base::Unretained(this), true)); - SetCancelCallback( - base::BindOnce(run_callback, base::Unretained(this), false)); - - ChromeLayoutProvider* const provider = ChromeLayoutProvider::Get(); - SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kVertical, gfx::Insets(), - provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL))); - const bool dialog_is_bubble = anchor_view != nullptr; - SetModalType(dialog_is_bubble ? ui::MODAL_TYPE_NONE : ui::MODAL_TYPE_WINDOW); - set_fixed_width(provider->GetDistanceMetric( - dialog_is_bubble ? views::DISTANCE_BUBBLE_PREFERRED_WIDTH - : views::DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH)); - - // Add margins for the icon plus the icon-title padding so that the dialog - // contents align with the title text. - set_margins( - margins() + - gfx::Insets::TLBR( - 0, margins().left() + extension_misc::EXTENSION_ICON_SMALL, 0, 0)); - - auto heading = std::make_unique<views::Label>( - l10n_util::GetStringFUTF16( - IDS_EXTENSIONS_PRINTING_API_PRINT_REQUEST_BUBBLE_HEADING, - extension_name, print_job_title, printer_name), - views::style::CONTEXT_DIALOG_BODY_TEXT, views::style::STYLE_SECONDARY); - heading->SetMultiLine(true); - heading->SetHorizontalAlignment(gfx::ALIGN_LEFT); - heading->SetAllowCharacterBreak(true); - AddChildView(std::move(heading)); -} - -PrintJobConfirmationDialogView::~PrintJobConfirmationDialogView() = default; - -BEGIN_METADATA(PrintJobConfirmationDialogView, views::BubbleDialogDelegateView) -END_METADATA - -namespace chrome { - -void ShowPrintJobConfirmationDialog(gfx::NativeWindow parent, - const extensions::ExtensionId& extension_id, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback) { - PrintJobConfirmationDialogView::Show(parent, extension_id, extension_name, - extension_icon, print_job_title, - printer_name, std::move(callback)); -} - -} // namespace chrome
diff --git a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.h b/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.h deleted file mode 100644 index ded18bf..0000000 --- a/chrome/browser/ui/views/extensions/print_job_confirmation_dialog_view.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PRINT_JOB_CONFIRMATION_DIALOG_VIEW_H_ -#define CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PRINT_JOB_CONFIRMATION_DIALOG_VIEW_H_ - -#include <memory> -#include <string> - -#include "base/callback_forward.h" -#include "extensions/common/extension_id.h" -#include "ui/base/metadata/metadata_header_macros.h" -#include "ui/base/ui_base_types.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/bubble/bubble_dialog_delegate_view.h" - -// The dialog's view, owned by the views framework. -class PrintJobConfirmationDialogView : public views::BubbleDialogDelegateView { - public: - METADATA_HEADER(PrintJobConfirmationDialogView); - - static void Show(gfx::NativeWindow parent, - const extensions::ExtensionId& extension_id, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback); - - PrintJobConfirmationDialogView(views::View* anchor_view, - const std::u16string& extension_name, - const gfx::ImageSkia& extension_icon, - const std::u16string& print_job_title, - const std::u16string& printer_name, - base::OnceCallback<void(bool)> callback); - PrintJobConfirmationDialogView(const PrintJobConfirmationDialogView&) = - delete; - PrintJobConfirmationDialogView& operator=( - const PrintJobConfirmationDialogView&) = delete; - ~PrintJobConfirmationDialogView() override; - - private: - // The name of the extension we are showing the dialog for. - const std::u16string extension_name_; - - // Callback to call after the dialog is accepted or rejected. - base::OnceCallback<void(bool)> callback_; -}; - -#endif // CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PRINT_JOB_CONFIRMATION_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/webui/access_code_cast/access_code_cast_handler.cc b/chrome/browser/ui/webui/access_code_cast/access_code_cast_handler.cc index 0249584..8c815058 100644 --- a/chrome/browser/ui/webui/access_code_cast/access_code_cast_handler.cc +++ b/chrome/browser/ui/webui/access_code_cast/access_code_cast_handler.cc
@@ -165,10 +165,10 @@ return; } AddSinkCallback callback_with_default_invoker = - mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), - AddSinkResultCode::UNKNOWN_ERROR); + mojo::WrapCallbackWithDefaultInvokeIfNotRun( + std::move(callback), AddSinkResultCode::UNKNOWN_ERROR); add_sink_callback_ = std::move(base::BindOnce(&AddSinkMetricsCallback)) - .Then(std::move(callback_with_default_invoker)); + .Then(std::move(callback_with_default_invoker)); access_code_sink_service_->DiscoverSink( access_code, base::BindOnce(&AccessCodeCastHandler::OnSinkAddedResult, weak_ptr_factory_.GetWeakPtr())); @@ -197,11 +197,6 @@ return; } - // Sink has been completely added so caller can be alerted. - if (base::FeatureList::IsEnabled(features::kAccessCodeCastRememberDevices)) { - access_code_sink_service_->StoreSinkAndSetExpirationTimer(sink_id_.value()); - } - std::move(add_sink_callback_).Run(AddSinkResultCode::OK); } @@ -221,6 +216,12 @@ } if (sink_id) { sink_id_ = sink_id; + // Sink has been completely added so caller can be alerted. + if (base::FeatureList::IsEnabled( + features::kAccessCodeCastRememberDevices)) { + access_code_sink_service_->StoreSinkAndSetExpirationTimer( + sink_id_.value()); + } } CheckForDiscoveryCompletion(); }
diff --git a/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc b/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc index 7941527f0..916f942d 100644 --- a/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc +++ b/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc
@@ -77,6 +77,11 @@ source->AddBoolean("isActiveDirectoryUser", user && user->IsActiveDirectoryUser()); + // Check if Kerberos was and still is enabled via policy at the creation time + // of SmbService. As a result, if Kerberos policy was enabled during a user + // session, SSO option will not be available/visible. + // TODO(crbug.com/1040138): subscribe to pref. changes in SmbService and setup + // Kerberos after it is enabled during a user session. const ash::smb_client::SmbService* const smb_service = ash::smb_client::SmbServiceFactory::Get(profile); bool is_kerberos_enabled =
diff --git a/chrome/browser/ui/webui/settings/chromeos/main_section.cc b/chrome/browser/ui/webui/settings/chromeos/main_section.cc index b06c135..91d3ce8 100644 --- a/chrome/browser/ui/webui/settings/chromeos/main_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/main_section.cc
@@ -131,6 +131,7 @@ {"extensionsLinkTooltip", IDS_SETTINGS_MENU_EXTENSIONS_LINK_TOOLTIP}, {"learnMore", IDS_LEARN_MORE}, {"shortcutBannerDismissed", IDS_SETTINGS_SHORTCUT_BANNER_DISMISSED}, + {"manage", IDS_SETTINGS_MANAGE}, {"menu", IDS_MENU}, {"menuButtonLabel", IDS_SETTINGS_MENU_BUTTON_LABEL}, {"moreActions", IDS_SETTINGS_MORE_ACTIONS},
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 0bbc3a8..fed5b99 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -164,6 +164,7 @@ {"extensionsLinkTooltip", IDS_SETTINGS_MENU_EXTENSIONS_LINK_TOOLTIP}, {"fonts", IDS_SETTINGS_FONTS}, {"learnMore", IDS_LEARN_MORE}, + {"manage", IDS_SETTINGS_MANAGE}, {"menu", IDS_MENU}, {"menuButtonLabel", IDS_SETTINGS_MENU_BUTTON_LABEL}, {"moreActions", IDS_SETTINGS_MORE_ACTIONS},
diff --git a/chrome/browser/url_param_filter/url_param_classifications_loader_browsertest.cc b/chrome/browser/url_param_filter/url_param_classifications_loader_browsertest.cc index aaadaaa..0825e7b 100644 --- a/chrome/browser/url_param_filter/url_param_classifications_loader_browsertest.cc +++ b/chrome/browser/url_param_filter/url_param_classifications_loader_browsertest.cc
@@ -28,6 +28,8 @@ enum ShouldFilterState { kUnset, kTrue, kFalse }; +constexpr char DEFAULT_TAG[] = "default"; + std::string ShouldFilterStateToString(ShouldFilterState state) { switch (state) { case ShouldFilterState::kUnset: @@ -107,7 +109,7 @@ component_dir_.GetPath(), CreateSerializedUrlParamFilterClassificationForTesting( {{"source.test", {"plzblock_src"}}}, - {{"dest.test", {"plzblock_dest"}}})); + {{"dest.test", {"plzblock_dest"}}}, {DEFAULT_TAG})); ClassificationsLoaderBrowserTest::SetUpInProcessBrowserTestFixture(); } }; @@ -153,7 +155,7 @@ component_dir_.GetPath(), CreateSerializedUrlParamFilterClassificationForTesting( {{"source.test", {"plzblock_src"}}}, - {{"dest.test", {"plzblock_dest"}}})); + {{"dest.test", {"plzblock_dest"}}}, {DEFAULT_TAG})); ClassificationsLoaderBrowserTest::SetUpInProcessBrowserTestFixture(); } }; @@ -232,7 +234,7 @@ component_dir_.GetPath(), CreateSerializedUrlParamFilterClassificationForTesting( {{"source.test", {"plzblock_src"}}}, - {{"dest.test", {"plzblock_dest"}}})); + {{"dest.test", {"plzblock_dest"}}}, {DEFAULT_TAG})); ClassificationsLoaderBrowserTest::SetUpInProcessBrowserTestFixture(); } }; @@ -333,7 +335,7 @@ component_dir_.GetPath(), CreateSerializedUrlParamFilterClassificationForTesting( {{"source.test", {"plzblock_src"}}}, - {{"dest.test", {"plzblock_dest"}}})); + {{"dest.test", {"plzblock_dest"}}}, {DEFAULT_TAG})); ClassificationsLoaderBrowserTest::SetUpInProcessBrowserTestFixture(); } }; @@ -436,7 +438,7 @@ component_dir_.GetPath(), CreateSerializedUrlParamFilterClassificationForTesting( {{"source.test", {"plzblock_src"}}}, - {{"dest.test", {"plzblock_dest"}}})); + {{"dest.test", {"plzblock_dest"}}}, {DEFAULT_TAG})); ClassificationsLoaderBrowserTest::SetUpInProcessBrowserTestFixture(); } };
diff --git a/chrome/browser/url_param_filter/url_param_filter_browsertest.cc b/chrome/browser/url_param_filter/url_param_filter_browsertest.cc index aed573f..88780be 100644 --- a/chrome/browser/url_param_filter/url_param_filter_browsertest.cc +++ b/chrome/browser/url_param_filter/url_param_filter_browsertest.cc
@@ -28,11 +28,11 @@ namespace { constexpr static const char kCrossOtrResponseMetricName[] = - "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental"; + "Navigation.CrossOtr.ContextMenu.ResponseCode"; constexpr static const char kCrossOtrRefreshCountMetricName[] = - "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental"; + "Navigation.CrossOtr.ContextMenu.RefreshCount"; constexpr static const char kFilteredParamCountMetricName[] = - "Navigation.UrlParamFilter.FilteredParamCountExperimental"; + "Navigation.UrlParamFilter.FilteredParamCount"; } // namespace
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 1123ab7..dd13145 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1654603015-199fdfb58f98954b170b12d533b2673f3f633812.profdata +chrome-linux-main-1654624801-4beb99d41aaf96bbdc7070975c5f320f7318ff27.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 26db89b..e6c3f3d 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1654603015-d9dad202fdaa1e4462fed9ca9139098fbb6bc795.profdata +chrome-mac-main-1654624801-66a145255216a1f1944cb932354219e9baefb2eb.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index b2c1040d..c84fe62c 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1654603015-9126bc929470ecf8c6caa947e84bbb43d4ba145a.profdata +chrome-win32-main-1654624801-e58407eebb69390990328b70c211e26c87fb2630.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 0611b3f..93d4e6b 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1654603015-311860ed5734faa04dcf0c94724c3f0555f21f4e.profdata +chrome-win64-main-1654624801-e4d832a678dfba5d2b61017d09a28ca27c9cbbda.profdata
diff --git a/chrome/common/extensions/api/autotest_private.idl b/chrome/common/extensions/api/autotest_private.idl index 4043dfa1..c43b02f 100644 --- a/chrome/common/extensions/api/autotest_private.idl +++ b/chrome/common/extensions/api/autotest_private.idl
@@ -661,7 +661,6 @@ callback GetLoginEventRecorderLoginEventsCallback = void (LoginEventRecorderData[] data); - interface Functions { // Must be called to allow autotestPrivateAPI events to be fired. static void initializeEvents(); @@ -1331,6 +1330,9 @@ // Adds login event to test LoginEventRecorderDataCollection API. static void addLoginEventForTesting(VoidCallback callback); + + // Force auto theme mode in dark mode or light mode for testing. + [supportsPromises] static void forceAutoThemeMode(boolean darkModeEnabled, VoidCallback callback); }; interface Events {
diff --git a/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc b/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc index cfa4f6e5..8c3049a 100644 --- a/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc +++ b/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc
@@ -183,11 +183,11 @@ ExtensionMsg_TabConnectionInfo tab_connection_info; tab_connection_info.frame_id = 0; - const int tab_id = 10; GURL source_url("http://example.com"); - tab_connection_info.tab.Swap( - DictionaryBuilder().Set("tabId", tab_id).Build().get()); ExtensionMsg_ExternalConnectionInfo external_connection_info; + // We'd normally also have a tab here (stored in `tab_connection_info.tab`), + // but then we need a very large JSON object for it to comply with our + // schema. Just pretend it's not there. external_connection_info.target_id = extension()->id(); external_connection_info.source_endpoint = MessagingEndpoint::ForExtension(extension()->id());
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 4dad2c9..8ea0501 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -580,10 +580,9 @@ } if (is_win || is_mac || is_linux || is_chromeos_lacros) { - public_deps += [ "//ui/base:pixel_diff_test_support" ] - sources += [ - "pixel/browser_skia_gold_pixel_diff.cc", - "pixel/browser_skia_gold_pixel_diff.h", + public_deps += [ + "//ui/base:pixel_diff_test_support", + "//ui/views:view_pixel_diff_test_support", ] } @@ -4717,9 +4716,6 @@ # For tests in tools/perf/process_perf_results_unittest.py "//build/android/pylib/", "//third_party/logdog/logdog", - - # For representative perf testing run_rendering_benchmark_with_gated_performance.py - "//testing/scripts/run_rendering_benchmark_with_gated_performance.py", ] data_deps = [ "//testing:test_scripts_shared" ] @@ -4801,12 +4797,7 @@ testonly = true deps = [ "//tools/perf/:perf_without_chrome" ] - data = [ - # crbug.com/1048153 - "//testing/scripts/run_rendering_benchmark_with_gated_performance.py", - - "//tools/perf/contrib/cluster_telemetry/", - ] + data = [ "//tools/perf/contrib/cluster_telemetry/" ] data_deps = [ "//components/subresource_filter/tools:index_ruleset", @@ -8531,7 +8522,6 @@ "../browser/ui/profile_picker_unittest.cc", "../browser/ui/webui/signin/enterprise_profile_welcome_handler_unittest.cc", "../browser/ui/webui/signin/turn_sync_on_helper_unittest.cc", - "../test/pixel/browser_skia_gold_pixel_diff_unittest.cc", ] } @@ -10358,49 +10348,6 @@ } } -if (is_mac || is_win || is_android) { - group("rendering_representative_perf_tests_base") { - testonly = true - data = [ - "//build/android/pylib", - "//chrome/test/data/perf", - "//components/variations/service/generate_ui_string_overrider.py", - "//testing/scripts", - "//third_party/catapult", - "//tools/perf", - ] - data_deps = [ "//testing:test_scripts_shared" ] - } - - if (!is_android) { - group("rendering_representative_perf_tests") { - testonly = true - data_deps = [ - ":rendering_representative_perf_tests_base", - "//tools/perf/chrome_telemetry_build:telemetry_chrome_test", - ] - } - } else { - template("rendering_representative_perf_tests_android_template") { - forward_variables_from(invoker, [ "telemetry_target_suffix" ]) - group(target_name) { - testonly = true - data_deps = [ - ":rendering_representative_perf_tests_base", - "//tools/perf/chrome_telemetry_build:telemetry_chrome_test${telemetry_target_suffix}", - ] - } - } - - foreach(_target_suffix, telemetry_android_browser_target_suffixes) { - rendering_representative_perf_tests_android_template( - "rendering_representative_perf_tests${_target_suffix}") { - telemetry_target_suffix = _target_suffix - } - } - } -} - if (is_win) { test("delayloads_unittests") { output_name = "delayloads_unittests"
diff --git a/chrome/test/data/extensions/api_test/debugger_check_inner_url/background.js b/chrome/test/data/extensions/api_test/debugger_check_inner_url/background.js index d453fb87..657b546 100644 --- a/chrome/test/data/extensions/api_test/debugger_check_inner_url/background.js +++ b/chrome/test/data/extensions/api_test/debugger_check_inner_url/background.js
@@ -42,7 +42,7 @@ await new Promise(resolve => chrome.debugger.sendCommand(subframeDebuggee, 'Page.navigate', { - url: 'filesystem:chrome://version/non-existent/'}, resolve)); + url: 'blob:chrome://non-existent/'}, resolve)); chrome.test.assertLastError(DETACHED_WHILE_HANDLING);
diff --git a/chrome/test/data/webrtc/region_capture_embedded.html b/chrome/test/data/webrtc/region_capture_embedded.html index 2fa99fc..9efd10f 100644 --- a/chrome/test/data/webrtc/region_capture_embedded.html +++ b/chrome/test/data/webrtc/region_capture_embedded.html
@@ -1,77 +1,16 @@ <html> <head> <link rel="icon" href="data:," /> + <script src="region_capture_helpers.js"></script> <script> "use strict"; - let capturedStream; - let capturedVideoTrack; + setRole("embedded"); - async function startCapture() { - if (capturedStream) { - window.domAutomationController.send("error-multiple-embedded-captures"); - return; - } + registerEmbeddedListeners(); - try { - capturedStream = await navigator.mediaDevices.getDisplayMedia(); - [capturedVideoTrack] = capturedStream.getVideoTracks(); - window.domAutomationController.send("embedded-capture-success"); - } catch (e) { - window.domAutomationController.send("embedded-capture-failure"); - } - } - - async function cropTargetFromElement(elementId) { - const element = document.getElementById(elementId); - let cropId; - try { - cropId = await CropTarget.fromElement(element); - // Explicitly note emptiness to make it clear this is genuine emptiness - // and not a test error on the C++/JS boundary. - window.domAutomationController.send( - cropId == "" ? "empty-crop-target" : cropId); - } catch (e) { - window.domAutomationController.send("embedded-produce-crop-target-error"); - } - } - - async function crop(cropId) { - if (!capturedVideoTrack) { - window.domAutomationController.send("embedded-crop-error-no-track"); - return; - } - - try { - await capturedVideoTrack.cropTo(cropId); - window.domAutomationController.send("embedded-crop-success"); - return; - } catch (e) { - window.domAutomationController.send("embedded-crop-error"); - } - } - - // Allows creating new div-elements for which new crop-targets may be created. - async function createNewDivElement(divId) { - let newDiv = document.createElement("div"); - newDiv.id = divId; - document.body.appendChild(newDiv); - window.domAutomationController.send("embedded-new-div-success"); - } - - window.addEventListener("message", (event) => { - if (event.data == "start-capture") { - startCapture(); - } else if (event.data.startsWith("produce-crop-target:")) { - cropTargetFromElement(event.data.substr("produce-crop-target:".length)); - } else if (event.data.startsWith("crop-to:")) { - crop(event.data.substr("crop-to:".length)); - } else if (event.data.startsWith("create-new-div-element:")) { - createNewDivElement(event.data.substr("create-new-div-element:".length)); - } else { - window.domAutomationController.send("unrecognized-message"); - } - }); + let track; + let trackClone; function reportEmbeddingSuccess() { window.domAutomationController.send("embedding-done"); @@ -83,5 +22,6 @@ <!-- This DIV is just a convenient target for cropTargetFromElement. --> <h1>Region Capture Test - Page 1 (Embedded)</h1> </div> + <iframe id="mailman_frame"></iframe> </body> </html>
diff --git a/chrome/test/data/webrtc/region_capture_helpers.js b/chrome/test/data/webrtc/region_capture_helpers.js new file mode 100644 index 0000000..0e877b75 --- /dev/null +++ b/chrome/test/data/webrtc/region_capture_helpers.js
@@ -0,0 +1,216 @@ +/** + * Copyright 2022 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +"use strict"; + +/////////////////////////// +// Test page management. // +/////////////////////////// + +let role; +function setRole(value) { + role = value; +} + +function startEmbeddingFrame(url) { + const embedded_frame = document.getElementById("embedded_frame"); + embedded_frame.src = url; + // window.domAutomationController.send() called by embedded page. +} + +function registerEmbeddedListeners() { + window.addEventListener("message", (event) => { + const type = event.data.messageType; + if (type == "setup-mailman") { + setUpMailman(event.data.url); + } else if (type == "start-capture") { + startCapture(); + } else if (type == "produce-crop-target") { + cropTargetFromElement("embedded", event.data.element); + } else if (type == "crop-to") { + cropTo(event.data.cropTarget, event.data.targetTrackStr); + } else if (type == "create-new-div-element") { + createNewDivElement(event.data.targetFrame, event.data.divId); + } + }); +} + +// Allows creating new div-elements for which new crop-targets may be created. +async function createNewDivElement(targetFrame, divId) { + if (role == targetFrame) { + const newDiv = document.createElement("div"); + newDiv.id = divId; + document.body.appendChild(newDiv); + window.domAutomationController.send(`${role}-new-div-success`); + } else { + if (role != "top-level") { + window.domAutomationController.send(`${role}-new-div-error`) + return; + } + const embedded_frame = document.getElementById("embedded_frame"); + embedded_frame.contentWindow.postMessage({ + messageType: "create-new-div-element", + targetFrame: targetFrame, + divId: divId + }, "*"); + // window.domAutomationController.send() called by embedded page. + } +} + + +///////////////////////////////////////// +// Main actions from C++ test fixture. // +///////////////////////////////////////// + +async function startCapture() { + if (track || trackClone) { + window.domAutomationController.send("error-multiple-captures"); + return; + } + + try { + const stream = await navigator.mediaDevices.getDisplayMedia(); + [track] = stream.getVideoTracks(); + window.domAutomationController.send(`${role}-capture-success`); + } catch (e) { + window.domAutomationController.send(`${role}-capture-failure`); + } +} + +async function cropTargetFromElement(targetFrame, elementId) { + if (role == targetFrame) { + try { + const element = document.getElementById(elementId); + makeCropTargetProxy(await CropTarget.fromElement(element)); + // window.domAutomationController.send() called after + // the CropTarget is propagated to all participating pages. + } catch (e) { + window.domAutomationController.send(`${role}-produce-crop-target-error`); + } + } else { + const embedded_frame = document.getElementById("embedded_frame"); + embedded_frame.contentWindow.postMessage({ + messageType: "produce-crop-target", + element: elementId + }, "*"); + // window.domAutomationController.send() called by embedded page. + } +} + +async function cropTo(cropTarget, targetTrackStr) { + const targetTrack = (targetTrackStr == "original" ? track : trackClone); + if (targetTrack) { + try { + await targetTrack.cropTo(cropTarget); + window.domAutomationController.send(`${role}-crop-success`); + } catch (e) { + window.domAutomationController.send(`${role}-crop-error`); + } + } else { + if (role != "top-level") { + window.domAutomationController.send(`${role}-crop-error`) + return; + } + const embedded_frame = document.getElementById("embedded_frame"); + embedded_frame.contentWindow.postMessage({ + messageType: "crop-to", + cropTarget: cropTarget, + targetTrackStr: targetTrackStr + }, "*"); + // window.domAutomationController.send() called by embedded page. + } +} + +//////////////////////////////////////////////////////////// +// Communication with other pages belonging to this page. // +//////////////////////////////////////////////////////////// + +function setUpMailman(url) { + const mailman_frame = document.getElementById("mailman_frame"); + mailman_frame.src = url; + + window.addEventListener("message", (event) => { + if (event.data.messageType == "mailman-embedded") { + if (role == "top-level") { + const embedded_frame = document.getElementById("embedded_frame"); + embedded_frame.contentWindow.postMessage({ + messageType: "setup-mailman", + url: url + }, "*"); + // window.domAutomationController.send() called by embedded page. + } else { + window.domAutomationController.send("mailman-ready"); + } + } else if (event.data.messageType == "announce-crop-target") { + registerRemoteCropTarget(event.data.cropTarget, event.data.index); + } else if (event.data.messageType == "ack-crop-target") { + onAckReceived(event.data.index); + } + }); +} + +function broadcast(msg) { + const mailman_frame = document.getElementById("mailman_frame"); + mailman_frame.contentWindow.postMessage(msg, "*"); +} + + +////////////////////////////////////////////////////////////////// +// Maintenance of a shared CropTarget database so that any page // +// could be tested in cropping to a target in any other page. // +////////////////////////////////////////////////////////////////// + +// Because CropTargets are not stringifiable, we cache them here and give +// the C++ test fixture their index. When the C++ test fixture hands back +// the index as input to an action, we use the relevant CropTarget stored here. +// +// When a page mints a CropTarget, it propagates it to all other pages. +// Each page acks it back, and when the minter receives the expected +// number of acks, it returns control to the C++ fixture. + +// Contains all of the CropTargets this page knows of. +const cropTargets = []; + +const EXPECTED_ACKS = 3; +let ackCount; +let expectedAckIndex; + +function makeCropTargetProxy(cropTarget) { + cropTargets.push(cropTarget); + + ackCount = 0; + expectedAckIndex = cropTargets.length - 1; + + broadcast({ + messageType: "announce-crop-target", + cropTarget: cropTarget, + index: expectedAckIndex + }); +} + +function getCropTarget(cropTargetIndex) { + return cropTargets[cropTargetIndex]; +} + + +function registerRemoteCropTarget(cropTarget, index) { + cropTargets.push(cropTarget); + broadcast({messageType: "ack-crop-target", index: index}); +} + +function onAckReceived(index) { + if (index != expectedAckIndex) { + return; + } + + if (++ackCount != EXPECTED_ACKS) { + return; + } + + ackCount = undefined; + expectedAckIndex = undefined; + window.domAutomationController.send(`${cropTargets.length - 1}`); +}
diff --git a/chrome/test/data/webrtc/region_capture_mailman.html b/chrome/test/data/webrtc/region_capture_mailman.html new file mode 100644 index 0000000..79061c9 --- /dev/null +++ b/chrome/test/data/webrtc/region_capture_mailman.html
@@ -0,0 +1,27 @@ +<html> + <head> + <title>Region Capture Mailman</title> + <link rel="icon" href="data:," /> + <script> + "use strict"; + + function reportEmbeddingSuccess() { + window.parent.postMessage({messageType: "mailman-embedded"}, "*"); + } + + const cropTargetBc = new BroadcastChannel("cropTargetBc"); + + // Forward all messages from parent to the BroadcastChannel. + window.addEventListener("message", (event) => { + cropTargetBc.postMessage(event.data, "*"); + }); + + // Forward all messages from the BroadcastChannel to the parent. + cropTargetBc.onmessage = (msg) => { + window.parent.postMessage(msg.data, "*"); + } + </script> + </head> + <body onload="reportEmbeddingSuccess();"> + </body> +</html>
diff --git a/chrome/test/data/webrtc/region_capture_main.html b/chrome/test/data/webrtc/region_capture_main.html index b0e0b37..cb7befa 100644 --- a/chrome/test/data/webrtc/region_capture_main.html +++ b/chrome/test/data/webrtc/region_capture_main.html
@@ -3,90 +3,51 @@ <!-- The test scans for which source to share according to the title. --> <title>Region Capture Test - Page 1 (Main)</title> <link rel="icon" href="data:," /> + <script src="region_capture_helpers.js"></script> <script> "use strict"; - let capturedStream; - let capturedVideoTrack; + setRole("top-level"); - function startEmbeddingFrame(url) { - document.getElementById("embedded_frame").src = url; - // window.domAutomationController.send() called by embedded page. - } - - async function startCapture() { - if (capturedStream) { - window.domAutomationController.send("error-multiple-captures"); - return; - } - - try { - capturedStream = await navigator.mediaDevices.getDisplayMedia(); - [capturedVideoTrack] = capturedStream.getVideoTracks(); - window.domAutomationController.send("capture-success"); - } catch (e) { - window.domAutomationController.send("capture-failure"); - } - } + let track; + let trackClone; function startCaptureFromEmbeddedFrame() { document .getElementById("embedded_frame") - .contentWindow.postMessage("start-capture", "*"); + .contentWindow.postMessage({messageType: "start-capture"}, "*"); // window.domAutomationController.send() called by embedded page. } - async function cropTargetFromElement(targetFrame, elementId) { - if (targetFrame == "top") { - const element = document.getElementById(elementId); - let cropId; - try { - cropId = await CropTarget.fromElement(element); - } catch (e) { - window.domAutomationController.send("top-level-produce-crop-target-error"); - return; - } - // Explicitly note emptiness so as to make it clear that this is - // genuine emptiness and not a test error on the C++/JS boundary. - window.domAutomationController.send( - cropId == "" ? "empty-crop-target" : cropId); - } else { - document - .getElementById("embedded_frame") - .contentWindow.postMessage("produce-crop-target:" + elementId, "*"); - // window.domAutomationController.send() called by embedded page. - } + async function cropToByIndex(cropTargetIndex, targetTrack) { + const cropTarget = + (cropTargetIndex == "undefined" + ? undefined + : getCropTarget(cropTargetIndex)); + cropTo(cropTarget, targetTrack); } - async function cropTo(cropId) { - if (capturedVideoTrack) { - try { - await capturedVideoTrack.cropTo(cropId); - window.domAutomationController.send("top-level-crop-success"); - return; - } catch (e) { - window.domAutomationController.send("top-level-crop-error"); - } - } else { - document - .getElementById("embedded_frame") - .contentWindow.postMessage("crop-to:" + cropId, "*"); - // window.domAutomationController.send() called by embedded page. + // Clones |track| into |trackClone|. + function clone() { + if (!track || !!trackClone) { + window.domAutomationController.send("clone-track-failure"); + return; } + trackClone = track.clone(); + window.domAutomationController.send("clone-track-success"); } - // Allows creating new div-elements for which new crop-targets may be created. - async function createNewDivElement(targetFrame, divId) { - if (targetFrame == "top") { - let newDiv = document.createElement("div"); - newDiv.id = divId; - document.body.appendChild(newDiv); - window.domAutomationController.send("top-level-new-div-success"); + function deallocate(targetTrack) { + if (targetTrack == "original") { + track = undefined; + gc(); + window.domAutomationController.send("deallocate-success"); + } else if (targetTrack == "clone") { + trackClone = undefined; + gc(); + window.domAutomationController.send("deallocate-success"); } else { - document - .getElementById("embedded_frame") - .contentWindow.postMessage("create-new-div-element:" + divId, "*"); - // window.domAutomationController.send() called by embedded page. + window.domAutomationController.send("deallocate-failure"); } } </script> @@ -98,5 +59,6 @@ <br/> </div> <iframe id="embedded_frame" allow="display-capture *"></iframe> + <iframe id="mailman_frame"></iframe> </body> </html>
diff --git a/chrome/test/data/webrtc/region_capture_other_embedded.html b/chrome/test/data/webrtc/region_capture_other_embedded.html index 6898a66..3c1e6f4 100644 --- a/chrome/test/data/webrtc/region_capture_other_embedded.html +++ b/chrome/test/data/webrtc/region_capture_other_embedded.html
@@ -1,39 +1,17 @@ <html> <head> <link rel="icon" href="data:," /> + <script src="region_capture_helpers.js"></script> <script> "use strict"; + setRole("embedded"); + + registerEmbeddedListeners(); + function reportEmbeddingSuccess() { window.domAutomationController.send("embedding-done"); } - - async function cropTargetFromElement(elementId) { - const element = document.getElementById(elementId); - let cropId; - try { - try { - cropId = await CropTarget.fromElement(element); - } catch (e) { - window.domAutomationController.send("embedded-produce-crop-target-error"); - return; - } - // Explicitly note emptiness to make it clear this is genuine emptiness - // and not a test error on the C++/JS boundary. - window.domAutomationController.send( - cropId == "" ? "empty-crop-target" : cropId); - } catch (e) { - window.domAutomationController.send("produce-crop-target-embedded-failure"); - } - } - - window.addEventListener("message", (event) => { - if (event.data.startsWith("produce-crop-target:")) { - cropTargetFromElement(event.data.substr("produce-crop-target:".length)); - } else { - window.domAutomationController.send("unrecognized-message"); - } - }); </script> </head> <body onload="reportEmbeddingSuccess();"> @@ -41,5 +19,6 @@ <!-- This DIV is just a convenient target for cropTargetFromElement. --> <h1>Region Capture Test - Page 2 (Embedded)</h1> </div> + <iframe id="mailman_frame"></iframe> </body> </html>
diff --git a/chrome/test/data/webrtc/region_capture_other_main.html b/chrome/test/data/webrtc/region_capture_other_main.html index da4cc1b..8ad30d5e 100644 --- a/chrome/test/data/webrtc/region_capture_other_main.html +++ b/chrome/test/data/webrtc/region_capture_other_main.html
@@ -3,35 +3,11 @@ <!-- The test scans for which source to share according to the title. --> <title>Region Capture Test - Page 2 (Main)</title> <link rel="icon" href="data:," /> + <script src="region_capture_helpers.js"></script> <script> "use strict"; - function startEmbeddingFrame(url) { - document.getElementById("embedded_frame").src = url; - // window.domAutomationController.send() called by embedded page. - } - - async function cropTargetFromElement(targetFrame, elementId) { - if (targetFrame == "top") { - const element = document.getElementById(elementId); - let cropId; - try { - cropId = await CropTarget.fromElement(element); - } catch (e) { - window.domAutomationController.send("top-level-produce-crop-target-error"); - return; - } - // Explicitly note emptiness so as to make it clear that this is - // genuine emptiness and not a test error on the C++/JS boundary. - window.domAutomationController.send( - cropId == "" ? "empty-crop-target" : cropId); - } else { - document - .getElementById("embedded_frame") - .contentWindow.postMessage("produce-crop-target:" + elementId, "*"); - // window.domAutomationController.send() called by embedded page. - } - } + setRole("top-level"); </script> </head> <body> @@ -41,5 +17,6 @@ <br/> <iframe id="embedded_frame" allow="display-capture *"></iframe> </div> + <iframe id="mailman_frame"></iframe> </body> </html>
diff --git a/chrome/test/data/webui/settings/extension_controlled_indicator_tests.ts b/chrome/test/data/webui/settings/extension_controlled_indicator_tests.ts index d9c6371..3e19937 100644 --- a/chrome/test/data/webui/settings/extension_controlled_indicator_tests.ts +++ b/chrome/test/data/webui/settings/extension_controlled_indicator_tests.ts
@@ -4,10 +4,11 @@ // clang-format off import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {ExtensionControlBrowserProxyImpl, ExtensionControlledIndicatorElement} from 'chrome://settings/settings.js'; +import {OpenWindowProxyImpl, ExtensionControlBrowserProxyImpl, ExtensionControlledIndicatorElement} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestExtensionControlBrowserProxy} from './test_extension_control_browser_proxy.js'; +import {TestOpenWindowProxy} from './test_open_window_proxy.js'; // clang-format on @@ -15,10 +16,15 @@ let browserProxy: TestExtensionControlBrowserProxy; let indicator: ExtensionControlledIndicatorElement; + let openWindowProxy: TestOpenWindowProxy; + setup(function() { document.body.innerHTML = ''; browserProxy = new TestExtensionControlBrowserProxy(); ExtensionControlBrowserProxyImpl.setInstance(browserProxy); + openWindowProxy = new TestOpenWindowProxy(); + OpenWindowProxyImpl.setInstance(openWindowProxy); + indicator = document.createElement('extension-controlled-indicator'); indicator.extensionId = 'peiafolljookckjknpgofpbjobgbmpge'; indicator.extensionCanBeDisabled = true; @@ -29,44 +35,34 @@ test('disable button tracks extensionCanBeDisabled', function() { assertTrue(indicator.extensionCanBeDisabled); - assertTrue(!!indicator.shadowRoot!.querySelector('cr-button')); + assertTrue(!!indicator.shadowRoot!.querySelector('#disable')); indicator.extensionCanBeDisabled = false; flush(); - assertFalse(!!indicator.shadowRoot!.querySelector('cr-button')); + assertFalse(!!indicator.shadowRoot!.querySelector('#disable')); }); - test('label text and href', function() { - let imgSrc = indicator.shadowRoot!.querySelector('img')!.src; + test('label icon and text', function() { + const imgSrc = indicator.shadowRoot!.querySelector('img')!.src; assertTrue(imgSrc.includes(indicator.extensionId)); - let label = indicator.shadowRoot!.querySelector('span'); + const label = indicator.shadowRoot!.querySelector('span'); assertTrue(!!label); - let labelLink = label!.querySelector('a'); - assertTrue(!!labelLink); - assertEquals(labelLink!.textContent, indicator.extensionName); + assertTrue(label.textContent!.includes(indicator.extensionName)); + }); - assertEquals('chrome://extensions', new URL(labelLink!.href).origin); - assertTrue(labelLink!.href.includes(indicator.extensionId)); - - indicator.extensionId = 'dpjamkmjmigaoobjbekmfgabipmfilij'; - indicator.extensionName = 'A Slightly Less Good Name (Can\'t Beat That ^)'; - flush(); - - imgSrc = indicator.shadowRoot!.querySelector('img')!.src; - assertTrue(imgSrc.includes(indicator.extensionId)); - - label = indicator.shadowRoot!.querySelector('span'); - assertTrue(!!label); - labelLink = label!.querySelector('a'); - assertTrue(!!labelLink); - assertEquals(labelLink!.textContent, indicator.extensionName); + test('tapping manage button invokes browser proxy', async function() { + const button = indicator.shadowRoot!.querySelector<HTMLElement>('#manage'); + assertTrue(!!button); + button!.click(); + const url = await openWindowProxy.whenCalled('openURL'); + assertEquals(url, `chrome://extensions/?id=${indicator.extensionId}`); }); test('tapping disable button invokes browser proxy', async function() { - const disableButton = indicator.shadowRoot!.querySelector('cr-button'); - assertTrue(!!disableButton); - disableButton!.click(); + const button = indicator.shadowRoot!.querySelector<HTMLElement>('#disable'); + assertTrue(!!button); + button!.click(); const extensionId = await browserProxy.whenCalled('disableExtension'); assertEquals(extensionId, indicator.extensionId); });
diff --git a/chrome/test/interaction/interaction_sequence_browser_util.cc b/chrome/test/interaction/interaction_sequence_browser_util.cc index 98f8223..1dddaea 100644 --- a/chrome/test/interaction/interaction_sequence_browser_util.cc +++ b/chrome/test/interaction/interaction_sequence_browser_util.cc
@@ -33,7 +33,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/browser/ui/test/test_browser_ui.h" #include "chrome/browser/ui/views/frame/browser_view.h" -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/chrome/test/pixel/demo/skia_gold_demo_pixeltest.cc b/chrome/test/pixel/demo/skia_gold_demo_pixeltest.cc index 0e814b0..0cee6c0 100644 --- a/chrome/test/pixel/demo/skia_gold_demo_pixeltest.cc +++ b/chrome/test/pixel/demo/skia_gold_demo_pixeltest.cc
@@ -6,9 +6,9 @@ #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" #include "content/public/test/browser_test.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" +#include "ui/views/test/view_skia_gold_pixel_diff.h" class SkiaGoldDemoPixelTest : public InProcessBrowserTest { protected: @@ -27,10 +27,12 @@ ASSERT_NO_FATAL_FAILURE(pixel_diff_.Init("SkiaGoldDemoPixelTest")); } - const BrowserSkiaGoldPixelDiff& GetPixelDiff() const { return pixel_diff_; } + const views::ViewSkiaGoldPixelDiff& GetPixelDiff() const { + return pixel_diff_; + } private: - BrowserSkiaGoldPixelDiff pixel_diff_; + views::ViewSkiaGoldPixelDiff pixel_diff_; }; // This is a demo test to ensure the omnibox looks as expected. @@ -46,7 +48,7 @@ GURL url("chrome://bookmarks"); ASSERT_TRUE(AddTabAtIndex(0, url, ui::PageTransition::PAGE_TRANSITION_FIRST)); auto* const browser_view = static_cast<BrowserView*>(browser()->window()); - bool ret = GetPixelDiff().CompareScreenshot("omnibox", - browser_view->GetLocationBarView()); + bool ret = GetPixelDiff().CompareViewScreenshot( + "omnibox", browser_view->GetLocationBarView()); EXPECT_TRUE(ret); }
diff --git a/chrome/updater/app/server/win/server.cc b/chrome/updater/app/server/win/server.cc index 34030f4..eef6290 100644 --- a/chrome/updater/app/server/win/server.cc +++ b/chrome/updater/app/server/win/server.cc
@@ -228,8 +228,8 @@ base::ThreadPoolInstance::Create(kThreadPoolName); // Reuses the logic in base::ThreadPoolInstance::StartWithDefaultParams. - const int num_cores = base::SysInfo::NumberOfProcessors(); - const int max_num_foreground_threads = std::max(3, num_cores - 1); + const size_t max_num_foreground_threads = + static_cast<size_t>(std::max(3, base::SysInfo::NumberOfProcessors() - 1)); base::ThreadPoolInstance::InitParams init_params(max_num_foreground_threads); init_params.common_thread_pool_environment = base::ThreadPoolInstance:: InitParams::CommonThreadPoolEnvironment::COM_MTA;
diff --git a/chrome/updater/win/signing/PRESUBMIT.py b/chrome/updater/win/signing/PRESUBMIT.py index 088d5cb0..1462df0e 100644 --- a/chrome/updater/win/signing/PRESUBMIT.py +++ b/chrome/updater/win/signing/PRESUBMIT.py
@@ -11,7 +11,9 @@ def CommonChecks(input_api, output_api): - return input_api.canned_checks.RunPylint(input_api, output_api) + return input_api.canned_checks.RunPylint(input_api, + output_api, + version='2.7') def CheckChangeOnUpload(input_api, output_api):
diff --git a/chrome/updater/win/signing/sign.py b/chrome/updater/win/signing/sign.py index 75a6fd5..fcbef62 100755 --- a/chrome/updater/win/signing/sign.py +++ b/chrome/updater/win/signing/sign.py
@@ -26,10 +26,9 @@ class SigningError(Exception): """Module exception class.""" - pass -class Signer(object): +class Signer: """A container for a signing operation.""" def __init__(self, tmpdir, lzma_exe, signtool_exe, tagging_exe, identity):
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index eb41270..5153d9e 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -3333,10 +3333,10 @@ <!-- Feedback Tool--> <!-- Search Page --> - <message name="IDS_FEEDBACK_TOOL_CONTINUE_BUTTON_LABEL" translateable="false" desc="Label of the continue button."> + <message name="IDS_FEEDBACK_TOOL_CONTINUE_BUTTON_LABEL" desc="Label of the continue button."> Continue </message> - <message name="IDS_FEEDBACK_TOOL_DESCRIPTION_LABEL" translateable="false" desc="Label of the text box where users can describe a problem they are having"> + <message name="IDS_FEEDBACK_TOOL_DESCRIPTION_LABEL" desc="Label of the text box where users can describe a problem they are having"> Description </message> <message name="IDS_FEEDBACK_TOOL_NO_MATCHED_RESULTS" translateable="false" desc="Label for help content when there are no matched results."> @@ -3351,7 +3351,7 @@ <message name="IDS_FEEDBACK_TOOL_SUGGESTED_HELP_CONTENT" translateable="false" desc="Label for help content when there are matched results."> Suggested help content </message> - <message name="IDS_FEEDBACK_TOOL_DESCRIPTION_REQUIRED" translateable="false" desc="Label showing error message when clicking continue button without a description."> + <message name="IDS_FEEDBACK_TOOL_DESCRIPTION_REQUIRED" desc="Label showing error message when clicking continue button without a description."> Description is required </message> <message name="IDS_FEEDBACK_TOOL_FEEDBACK_HELP_LINK_LABEL" desc="The text used for the link that navigates to the feedback help webpage.">
diff --git a/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_CONTINUE_BUTTON_LABEL.png.sha1 b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_CONTINUE_BUTTON_LABEL.png.sha1 new file mode 100644 index 0000000..3e31bda --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_CONTINUE_BUTTON_LABEL.png.sha1
@@ -0,0 +1 @@ +ddbe227475850ee74139c660e42a0343db67f4dd \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_LABEL.png.sha1 b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_LABEL.png.sha1 new file mode 100644 index 0000000..3e31bda --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_LABEL.png.sha1
@@ -0,0 +1 @@ +ddbe227475850ee74139c660e42a0343db67f4dd \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_REQUIRED.png.sha1 b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_REQUIRED.png.sha1 new file mode 100644 index 0000000..b314a19 --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_FEEDBACK_TOOL_DESCRIPTION_REQUIRED.png.sha1
@@ -0,0 +1 @@ +50897f02c9176a708069933f0a1d41f3ab9af3bd \ No newline at end of file
diff --git a/chromeos/components/quick_answers/quick_answers_client.cc b/chromeos/components/quick_answers/quick_answers_client.cc index 09ee510..ad7dfc1 100644 --- a/chromeos/components/quick_answers/quick_answers_client.cc +++ b/chromeos/components/quick_answers/quick_answers_client.cc
@@ -100,11 +100,6 @@ delegate_->OnNetworkError(); } -void QuickAnswersClient::RequestAccessToken(AccessTokenCallback callback) { - DCHECK(delegate_); - delegate_->RequestAccessToken(std::move(callback)); -} - void QuickAnswersClient::OnQuickAnswerReceived( std::unique_ptr<QuickAnswer> quick_answer) { DCHECK(delegate_);
diff --git a/chromeos/components/quick_answers/quick_answers_client.h b/chromeos/components/quick_answers/quick_answers_client.h index 182a82ec..9937faf6 100644 --- a/chromeos/components/quick_answers/quick_answers_client.h +++ b/chromeos/components/quick_answers/quick_answers_client.h
@@ -30,9 +30,6 @@ // A delegate interface for the QuickAnswersClient. class QuickAnswersDelegate { public: - using AccessTokenCallback = - base::OnceCallback<void(const std::string& access_token)>; - QuickAnswersDelegate(const QuickAnswersDelegate&) = delete; QuickAnswersDelegate& operator=(const QuickAnswersDelegate&) = delete; @@ -48,13 +45,6 @@ // Invoked when there is a network error. virtual void OnNetworkError() {} - // Request for the access token associated with the active user's profile. - // Request is handled asynchronously if the token is not available. - // AccessTokenCallbacks are invoked as soon as the token if fetched. - // If the token is available, AccessTokenCallbacks are invoked - // synchronously before RequestAccessToken() returns. - virtual void RequestAccessToken(AccessTokenCallback callback) {} - protected: QuickAnswersDelegate() = default; virtual ~QuickAnswersDelegate() = default; @@ -86,7 +76,6 @@ void OnNetworkError() override; void OnQuickAnswerReceived( std::unique_ptr<QuickAnswer> quick_answer) override; - void RequestAccessToken(AccessTokenCallback callback) override; // Send a quick answer request for preprocessing only. void SendRequestForPreprocessing(
diff --git a/chromeos/components/quick_answers/quick_answers_client_unittest.cc b/chromeos/components/quick_answers/quick_answers_client_unittest.cc index 56dd012..65daa412 100644 --- a/chromeos/components/quick_answers/quick_answers_client_unittest.cc +++ b/chromeos/components/quick_answers/quick_answers_client_unittest.cc
@@ -131,11 +131,12 @@ return std::move(mock_intent_generator_); } + base::test::TaskEnvironment task_environment_; + std::unique_ptr<QuickAnswersClient> client_; std::unique_ptr<MockQuickAnswersDelegate> mock_delegate_; std::unique_ptr<MockResultLoader> mock_result_loader_; std::unique_ptr<MockIntentGenerator> mock_intent_generator_; - base::test::SingleThreadTaskEnvironment task_environment_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; QuickAnswersClient::ResultLoaderFactoryCallback
diff --git a/chromeos/components/quick_answers/result_loader.h b/chromeos/components/quick_answers/result_loader.h index 71cdf013..ac63e8d 100644 --- a/chromeos/components/quick_answers/result_loader.h +++ b/chromeos/components/quick_answers/result_loader.h
@@ -30,9 +30,6 @@ // A delegate interface for the ResultLoader. class ResultLoaderDelegate { public: - using AccessTokenCallback = - base::OnceCallback<void(const std::string& access_token)>; - ResultLoaderDelegate(const ResultLoaderDelegate&) = delete; ResultLoaderDelegate& operator=(const ResultLoaderDelegate&) = delete; @@ -44,9 +41,6 @@ virtual void OnQuickAnswerReceived( std::unique_ptr<QuickAnswer> quick_answer) {} - // Request for the access token associated with the active user's profile. - virtual void RequestAccessToken(AccessTokenCallback callback) {} - protected: ResultLoaderDelegate() = default; virtual ~ResultLoaderDelegate() = default;
diff --git a/chromeos/components/quick_answers/test/test_helpers.h b/chromeos/components/quick_answers/test/test_helpers.h index 5c73e739..ce26a86 100644 --- a/chromeos/components/quick_answers/test/test_helpers.h +++ b/chromeos/components/quick_answers/test/test_helpers.h
@@ -42,7 +42,6 @@ // ResultLoader::ResultLoaderDelegate: MOCK_METHOD0(OnNetworkError, void()); MOCK_METHOD1(OnQuickAnswerReceived, void(std::unique_ptr<QuickAnswer>)); - MOCK_METHOD1(RequestAccessToken, void(AccessTokenCallback)); }; MATCHER_P(QuickAnswerEqual, quick_answer, "") {
diff --git a/chromeos/components/quick_answers/utils/language_detector.cc b/chromeos/components/quick_answers/utils/language_detector.cc index 919aee4..1b5220f60 100644 --- a/chromeos/components/quick_answers/utils/language_detector.cc +++ b/chromeos/components/quick_answers/utils/language_detector.cc
@@ -11,7 +11,7 @@ namespace quick_answers { namespace { -constexpr double kSelectedTextConfidenceThreshold = 0.8; +constexpr double kSelectedTextConfidenceThreshold = 0.9; constexpr double kSurroundingTextConfidenceThreshold = 0.9;
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 9f4a6fe..3c5d650 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -44,8 +44,7 @@ // Controls whether to always trigger Quick Answers with single word selection. const base::Feature kQuickAnswersAlwaysTriggerForSingleWord{ - "QuickAnswersAlwaysTriggerForSingleWord", - base::FEATURE_DISABLED_BY_DEFAULT}; + "QuickAnswersAlwaysTriggerForSingleWord", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables Quick Answers for more locales. const base::Feature kQuickAnswersForMoreLocales{
diff --git a/chromeos/tast_control.gni b/chromeos/tast_control.gni index 310082a..92a6198 100644 --- a/chromeos/tast_control.gni +++ b/chromeos/tast_control.gni
@@ -236,6 +236,16 @@ # https://crbug.com/1329761 "policy.DefaultSerialGuardSetting", + # https://crbug.com/1334354 + "arc.Boot.vm", + "arc.ChromeCrash.vm_logged_in", + "arc.Drivefs.vm", + "arc.OptinManaged.vm", + "arc.OptinNetworkError.vm", + "arc.RemovableMedia.vm", + "security.NetworkListenersARC.vm", + "security.SELinuxFilesDataDir.vm", + # b/233264555 "inputs.PhysicalKeyboardEmojiSuggestion", "inputs.PhysicalKeyboardEmojiSuggestion.guest",
diff --git a/components/BUILD.gn b/components/BUILD.gn index 1a19c46e..98635a2 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -307,6 +307,7 @@ "//components/signin/public/identity_manager/objc:unit_tests", "//components/translate/ios/browser:unit_tests", "//components/ukm/ios:unit_tests", + "//components/url_param_filter/ios:unit_tests", ] } else { #!is_ios deps += [
diff --git a/components/accuracy_tips/accuracy_service.cc b/components/accuracy_tips/accuracy_service.cc index 65b1b08..9d3a2a8 100644 --- a/components/accuracy_tips/accuracy_service.cc +++ b/components/accuracy_tips/accuracy_service.cc
@@ -156,7 +156,8 @@ if (disable_ui_) { return OnAccuracyTipClosed( - base::TimeTicks(), web_contents->GetMainFrame()->GetPageUkmSourceId(), + base::TimeTicks(), + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId(), AccuracyTipInteraction::kDisabledByExperiment); } @@ -171,9 +172,10 @@ delegate_->ShowAccuracyTip( web_contents, AccuracyTipStatus::kShowAccuracyTip, /*show_opt_out=*/show_opt_out, - base::BindOnce(&AccuracyService::OnAccuracyTipClosed, - weak_factory_.GetWeakPtr(), base::TimeTicks::Now(), - web_contents->GetMainFrame()->GetPageUkmSourceId())); + base::BindOnce( + &AccuracyService::OnAccuracyTipClosed, weak_factory_.GetWeakPtr(), + base::TimeTicks::Now(), + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId())); for (Observer& observer : observers_) observer.OnAccuracyTipShown(); }
diff --git a/components/accuracy_tips/accuracy_web_contents_observer.cc b/components/accuracy_tips/accuracy_web_contents_observer.cc index 5f8eabb8..8aa1476 100644 --- a/components/accuracy_tips/accuracy_web_contents_observer.cc +++ b/components/accuracy_tips/accuracy_web_contents_observer.cc
@@ -43,7 +43,7 @@ return; } - if (web_contents()->GetMainFrame()->GetVisibilityState() != + if (web_contents()->GetPrimaryMainFrame()->GetVisibilityState() != content::PageVisibilityState::kVisible) { return; } @@ -75,7 +75,7 @@ UMA_HISTOGRAM_ENUMERATION("Privacy.AccuracyTip.PageStatus", result); ukm::builders::AccuracyTipStatus( - web_contents()->GetMainFrame()->GetPageUkmSourceId()) + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()) .SetStatus(static_cast<int>(result)) .Record(ukm::UkmRecorder::Get());
diff --git a/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc b/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc index 603eaa1a..0fb6829 100644 --- a/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc +++ b/components/android_autofill/browser/test_support/autofill_provider_test_helper.cc
@@ -39,7 +39,7 @@ content::WebContents::FromJavaWebContents(jweb_contents); CHECK(web_contents); AutofillManager* autofill_manager = - GetAutofillManager(web_contents, web_contents->GetMainFrame()); + GetAutofillManager(web_contents, web_contents->GetPrimaryMainFrame()); CHECK(autofill_manager); return autofill_manager; }
diff --git a/components/autofill/content/browser/content_autofill_driver_factory_unittest.cc b/components/autofill/content/browser/content_autofill_driver_factory_unittest.cc index cb88436..cae01db 100644 --- a/components/autofill/content/browser/content_autofill_driver_factory_unittest.cc +++ b/components/autofill/content/browser/content_autofill_driver_factory_unittest.cc
@@ -126,7 +126,7 @@ agent_ = std::make_unique<MockAutofillAgent>(); blink::AssociatedInterfaceProvider* remote_interfaces = - web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces(); + web_contents()->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( mojom::AutofillAgent::Name_, base::BindRepeating(&MockAutofillAgent::BindPendingReceiver,
diff --git a/components/autofill/content/browser/content_autofill_driver_unittest.cc b/components/autofill/content/browser/content_autofill_driver_unittest.cc index 4beff3e..667a385e 100644 --- a/components/autofill/content/browser/content_autofill_driver_unittest.cc +++ b/components/autofill/content/browser/content_autofill_driver_unittest.cc
@@ -341,11 +341,11 @@ test_autofill_client_ = std::make_unique<MockAutofillClient>(); router_ = std::make_unique<ContentAutofillRouter>(); driver_ = std::make_unique<TestContentAutofillDriver>( - web_contents()->GetMainFrame(), router_.get(), + web_contents()->GetPrimaryMainFrame(), router_.get(), test_autofill_client_.get()); blink::AssociatedInterfaceProvider* remote_interfaces = - web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces(); + web_contents()->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( mojom::AutofillAgent::Name_, base::BindRepeating(&FakeAutofillAgent::BindPendingReceiver, @@ -430,17 +430,19 @@ EXPECT_EQ( form.host_frame, - LocalFrameToken(web_contents()->GetMainFrame()->GetFrameToken().value())); + LocalFrameToken( + web_contents()->GetPrimaryMainFrame()->GetFrameToken().value())); EXPECT_EQ(form.url, GURL("https://hostname/path")); EXPECT_EQ(form.full_url, GURL()); EXPECT_EQ(form.main_frame_origin, - web_contents()->GetMainFrame()->GetLastCommittedOrigin()); + web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin()); EXPECT_EQ(form.main_frame_origin, url::Origin::CreateFromNormalizedTuple("https", "hostname", 443)); ASSERT_EQ(form.fields.size(), 1u); EXPECT_EQ( form.fields.front().host_frame, - LocalFrameToken(web_contents()->GetMainFrame()->GetFrameToken().value())); + LocalFrameToken( + web_contents()->GetPrimaryMainFrame()->GetFrameToken().value())); EXPECT_EQ(form2.host_frame, form.host_frame); EXPECT_EQ(form2.url, form.url); @@ -517,7 +519,8 @@ EXPECT_NE(signature_without_meta_data, CalculateFormSignature(form)); EXPECT_EQ( field.host_frame, - LocalFrameToken(web_contents()->GetMainFrame()->GetFrameToken().value())); + LocalFrameToken( + web_contents()->GetPrimaryMainFrame()->GetFrameToken().value())); EXPECT_EQ(field.host_form_id, form.unique_renderer_id); EXPECT_EQ(field.host_form_signature, CalculateFormSignature(form));
diff --git a/components/autofill/core/browser/autofill_external_delegate.cc b/components/autofill/core/browser/autofill_external_delegate.cc index 5635a170..cf318607 100644 --- a/components/autofill/core/browser/autofill_external_delegate.cc +++ b/components/autofill/core/browser/autofill_external_delegate.cc
@@ -29,6 +29,7 @@ #include "components/autofill/core/common/autofill_util.h" #include "components/signin/public/base/signin_metrics.h" #include "components/strings/grit/components_strings.h" +#include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/base/l10n/l10n_util.h" @@ -232,7 +233,7 @@ void AutofillExternalDelegate::DidAcceptSuggestion( const std::u16string& value, int frontend_id, - const std::string& backend_id, + const Suggestion::Payload& payload, int position) { if (frontend_id == POPUP_ITEM_ID_AUTOFILL_OPTIONS) { // User selected 'Autofill Options'. @@ -272,10 +273,12 @@ } else if (frontend_id == POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY) { // There can be multiple virtual credit cards that all rely on // POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY as a frontend_id. In this case, - // the backend_id identifies the actually chosen credit card. + // the payload contains the backend id, which is a GUID that identifies the + // actually chosen credit card. + DCHECK(absl::holds_alternative<std::string>(payload)); manager_->FillOrPreviewVirtualCardInformation( - mojom::RendererFormDataAction::kFill, backend_id, query_id_, - query_form_, query_field_); + mojom::RendererFormDataAction::kFill, absl::get<std::string>(payload), + query_id_, query_form_, query_field_); } else { if (frontend_id > 0) { // Denotes an Autofill suggestion. AutofillMetrics::LogAutofillSuggestionAcceptedIndex(
diff --git a/components/autofill/core/browser/autofill_external_delegate.h b/components/autofill/core/browser/autofill_external_delegate.h index 268b63e8..c6af1bb01 100644 --- a/components/autofill/core/browser/autofill_external_delegate.h +++ b/components/autofill/core/browser/autofill_external_delegate.h
@@ -51,7 +51,7 @@ const std::string& backend_id) override; void DidAcceptSuggestion(const std::u16string& value, int frontend_id, - const std::string& backend_id, + const Suggestion::Payload& payload, int position) override; bool GetDeletionConfirmationText(const std::u16string& value, int frontend_id,
diff --git a/components/autofill/core/browser/autofill_external_delegate_unittest.cc b/components/autofill/core/browser/autofill_external_delegate_unittest.cc index 7ecee1be..abfa39c2 100644 --- a/components/autofill/core/browser/autofill_external_delegate_unittest.cc +++ b/components/autofill/core/browser/autofill_external_delegate_unittest.cc
@@ -261,7 +261,7 @@ // option. external_delegate_->DidAcceptSuggestion(autofill_item[0].main_text.value, autofill_item[0].frontend_id, - autofill_item[0].backend_id, 0); + autofill_item[0].payload, 0); } // Test that our external delegate does not add the signin promo and its @@ -304,7 +304,7 @@ // option. external_delegate_->DidAcceptSuggestion(autofill_item[0].main_text.value, autofill_item[0].frontend_id, - autofill_item[0].backend_id, 0); + autofill_item[0].payload, 0); } // Test that our external delegate properly adds the signin promo and no @@ -344,8 +344,8 @@ // This should trigger a call to start the signin flow and hide the popup // since we've selected the sign-in promo option. external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO, std::string(), - 0); + std::u16string(), POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO, + Suggestion::Payload{}, 0); } // Test that data list elements for a node will appear in the Autofill popup. @@ -610,8 +610,8 @@ HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); EXPECT_CALL(*browser_autofill_manager_, FillOrPreviewForm(_, _, _, _, _)) .Times(0); - external_delegate_->DidAcceptSuggestion(std::u16string(), -1, std::string(), - 0); + external_delegate_->DidAcceptSuggestion(std::u16string(), -1, + Suggestion::Payload{}, 0); } // Test that the Autofill delegate still allows previewing and filling @@ -649,8 +649,8 @@ EXPECT_CALL(*autofill_driver_, RendererShouldFillFieldWithValue(field_id_, promo_code_value)); external_delegate_->DidAcceptSuggestion( - promo_code_value, POPUP_ITEM_ID_MERCHANT_PROMO_CODE_ENTRY, std::string(), - 0); + promo_code_value, POPUP_ITEM_ID_MERCHANT_PROMO_CODE_ENTRY, + Suggestion::Payload{}, 0); } // Test that the ClearPreview call is only sent if the form was being previewed @@ -708,7 +708,7 @@ EXPECT_CALL(*autofill_driver_, RendererShouldAcceptDataListSuggestion(field_id_, dummy_string)); external_delegate_->DidAcceptSuggestion( - dummy_string, POPUP_ITEM_ID_DATALIST_ENTRY, std::string(), 0); + dummy_string, POPUP_ITEM_ID_DATALIST_ENTRY, Suggestion::Payload{}, 0); } // Test that an accepted autofill suggestion will fill the form. @@ -721,7 +721,7 @@ FillOrPreviewForm(mojom::RendererFormDataAction::kFill, _, _, _, kAutofillProfileId)); external_delegate_->DidAcceptSuggestion(dummy_string, kAutofillProfileId, - std::string(), + Suggestion::Payload{}, 2); // Row 2 } @@ -733,7 +733,7 @@ EXPECT_CALL(*autofill_driver_, RendererShouldClearFilledSection()); external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_CLEAR_FORM, std::string(), 0); + std::u16string(), POPUP_ITEM_ID_CLEAR_FORM, Suggestion::Payload{}, 0); } // Test that autofill client will scan a credit card after use accepted the @@ -742,8 +742,9 @@ EXPECT_CALL(autofill_client_, ScanCreditCard(_)); EXPECT_CALL(autofill_client_, HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); - external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_SCAN_CREDIT_CARD, std::string(), 0); + external_delegate_->DidAcceptSuggestion(std::u16string(), + POPUP_ITEM_ID_SCAN_CREDIT_CARD, + Suggestion::Payload{}, 0); } TEST_F(AutofillExternalDelegateUnitTest, ScanCreditCardPromptMetricsTest) { @@ -766,8 +767,9 @@ IssueOnQuery(kRecentQueryId); IssueOnSuggestionsReturned(kRecentQueryId); external_delegate_->OnPopupShown(); - external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_SCAN_CREDIT_CARD, std::string(), 0); + external_delegate_->DidAcceptSuggestion(std::u16string(), + POPUP_ITEM_ID_SCAN_CREDIT_CARD, + Suggestion::Payload{}, 0); histogram.ExpectBucketCount("Autofill.ScanCreditCardPrompt", AutofillMetrics::SCAN_CARD_ITEM_SHOWN, 1); histogram.ExpectBucketCount("Autofill.ScanCreditCardPrompt", @@ -785,7 +787,7 @@ IssueOnSuggestionsReturned(kRecentQueryId); external_delegate_->OnPopupShown(); external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_CLEAR_FORM, std::string(), 0); + std::u16string(), POPUP_ITEM_ID_CLEAR_FORM, Suggestion::Payload{}, 0); histogram.ExpectBucketCount("Autofill.ScanCreditCardPrompt", AutofillMetrics::SCAN_CARD_ITEM_SHOWN, 1); histogram.ExpectBucketCount("Autofill.ScanCreditCardPrompt", @@ -814,8 +816,8 @@ EXPECT_CALL(autofill_client_, HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO, std::string(), - 0); + std::u16string(), POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO, + Suggestion::Payload{}, 0); } MATCHER_P(CreditCardMatches, card, "") { @@ -957,8 +959,8 @@ FillOrPreviewVirtualCardInformation( mojom::RendererFormDataAction::kFill, _, _, _, _)); external_delegate_->DidAcceptSuggestion( - std::u16string(), POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY, std::string(), - 0); + std::u16string(), POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY, + Suggestion::Payload{}, 0); } TEST_F(AutofillExternalDelegateUnitTest, SelectVirtualCardOptionItem) {
diff --git a/components/autofill/core/browser/autofill_suggestion_generator.cc b/components/autofill/core/browser/autofill_suggestion_generator.cc index 547352d..7db2eba 100644 --- a/components/autofill/core/browser/autofill_suggestion_generator.cc +++ b/components/autofill/core/browser/autofill_suggestion_generator.cc
@@ -75,8 +75,8 @@ // Adjust phone number to display in prefix/suffix case. if (autofill_field.Type().group() == FieldTypeGroup::kPhoneHome) { for (auto& suggestion : suggestions) { - const AutofillProfile* profile = - personal_data_->GetProfileByGUID(suggestion.backend_id); + const AutofillProfile* profile = personal_data_->GetProfileByGUID( + suggestion.GetPayload<std::string>()); if (profile) { const std::u16string phone_home_city_and_number = profile->GetInfo(PHONE_HOME_CITY_AND_NUMBER, app_locale); @@ -91,7 +91,7 @@ for (auto& suggestion : suggestions) { suggestion.frontend_id = - MakeFrontendId(std::string(), suggestion.backend_id); + MakeFrontendId(std::string(), suggestion.GetPayload<std::string>()); } return suggestions; @@ -172,7 +172,7 @@ for (Suggestion& suggestion : suggestions) { if (suggestion.frontend_id == 0) { suggestion.frontend_id = - MakeFrontendId(suggestion.backend_id, std::string()); + MakeFrontendId(suggestion.GetPayload<std::string>(), std::string()); } } @@ -191,8 +191,7 @@ Suggestion* suggestion = &suggestions.back(); suggestion->label = base::ASCIIToUTF16( promo_code_offer->GetDisplayStrings().value_prop_text); - suggestion->backend_id = - base::NumberToString(promo_code_offer->GetOfferId()); + suggestion->payload = base::NumberToString(promo_code_offer->GetOfferId()); suggestion->frontend_id = POPUP_ITEM_ID_MERCHANT_PROMO_CODE_ENTRY; } return suggestions; @@ -306,7 +305,7 @@ server_duplicate_card->card_art_url(); backend_id = server_duplicate_card->guid(); } - suggestion.backend_id = backend_id; + suggestion.payload = backend_id; // Get the nickname for the card suggestion, which may not be the same as // the card's nickname if there are duplicates of the card on file.
diff --git a/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc b/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc index 15f0974..7ddd68c9 100644 --- a/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc +++ b/components/autofill/core/browser/autofill_suggestion_generator_unittest.cc
@@ -287,7 +287,7 @@ EXPECT_EQ(virtual_card_suggestion.frontend_id, POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY); - EXPECT_EQ(virtual_card_suggestion.backend_id, + EXPECT_EQ(absl::get<std::string>(virtual_card_suggestion.payload), "00000000-0000-0000-0000-000000000001"); Suggestion real_card_suggestion = @@ -297,7 +297,7 @@ ""); EXPECT_EQ(real_card_suggestion.frontend_id, 0); - EXPECT_EQ(real_card_suggestion.backend_id, + EXPECT_EQ(absl::get<std::string>(real_card_suggestion.payload), "00000000-0000-0000-0000-000000000001"); } @@ -326,7 +326,7 @@ EXPECT_EQ(virtual_card_suggestion.frontend_id, POPUP_ITEM_ID_VIRTUAL_CREDIT_CARD_ENTRY); - EXPECT_EQ(virtual_card_suggestion.backend_id, + EXPECT_EQ(absl::get<std::string>(virtual_card_suggestion.payload), "00000000-0000-0000-0000-000000000001"); Suggestion real_card_suggestion = @@ -336,7 +336,7 @@ ""); EXPECT_EQ(real_card_suggestion.frontend_id, 0); - EXPECT_EQ(real_card_suggestion.backend_id, + EXPECT_EQ(absl::get<std::string>(real_card_suggestion.payload), "00000000-0000-0000-0000-000000000002"); EXPECT_TRUE(real_card_suggestion.custom_icon.IsEmpty()); } @@ -435,13 +435,13 @@ EXPECT_EQ(promo_code_suggestions[0].main_text.value, u"test_promo_code_1"); EXPECT_EQ(promo_code_suggestions[0].label, u"test_value_prop_text_1"); - EXPECT_EQ(promo_code_suggestions[0].backend_id, "1"); + EXPECT_EQ(absl::get<std::string>(promo_code_suggestions[0].payload), "1"); EXPECT_EQ(promo_code_suggestions[0].frontend_id, POPUP_ITEM_ID_MERCHANT_PROMO_CODE_ENTRY); EXPECT_EQ(promo_code_suggestions[1].main_text.value, u"test_promo_code_2"); EXPECT_EQ(promo_code_suggestions[1].label, u"test_value_prop_text_2"); - EXPECT_EQ(promo_code_suggestions[1].backend_id, "2"); + EXPECT_EQ(absl::get<std::string>(promo_code_suggestions[1].payload), "2"); EXPECT_EQ(promo_code_suggestions[1].frontend_id, POPUP_ITEM_ID_MERCHANT_PROMO_CODE_ENTRY); }
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 09b605d2..0d1ae16 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
@@ -348,8 +348,9 @@ bool CreditCardFormEventLogger::DoesCardHaveOffer( const CreditCard& credit_card) { for (auto& suggestion : suggestions_) { - if (suggestion.backend_id == credit_card.guid()) + if (suggestion.GetPayload<std::string>() == credit_card.guid()) { return !suggestion.offer_label.empty(); + } } return false; }
diff --git a/components/autofill/core/browser/payments/autofill_offer_manager.cc b/components/autofill/core/browser/payments/autofill_offer_manager.cc index a9d9ef2..b677767 100644 --- a/components/autofill/core/browser/payments/autofill_offer_manager.cc +++ b/components/autofill/core/browser/payments/autofill_offer_manager.cc
@@ -53,7 +53,7 @@ // Update |offer_label| for each suggestion. for (auto& suggestion : suggestions) { - std::string id = suggestion.backend_id; + std::string id = suggestion.GetPayload<std::string>(); if (eligible_offers_map.count(id)) { suggestion.offer_label = l10n_util::GetStringUTF16(IDS_AUTOFILL_OFFERS_CASHBACK);
diff --git a/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc b/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc index 0a437107..ee42c8f 100644 --- a/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc +++ b/components/autofill/core/browser/payments/autofill_offer_manager_unittest.cc
@@ -138,7 +138,7 @@ CreateCreditCardOfferForCard(card, "5%")); std::vector<Suggestion> suggestions = {Suggestion()}; - suggestions[0].backend_id = kTestGuid; + suggestions[0].payload = kTestGuid; autofill_offer_manager_->UpdateSuggestionsWithOffers(GURL(kTestUrlWithParam), suggestions); @@ -152,7 +152,7 @@ CreateCreditCardOfferForCard(card, "5%", /*expired=*/true)); std::vector<Suggestion> suggestions = {Suggestion()}; - suggestions[0].backend_id = kTestGuid; + suggestions[0].payload = kTestGuid; autofill_offer_manager_->UpdateSuggestionsWithOffers(GURL(kTestUrlWithParam), suggestions); @@ -165,7 +165,7 @@ CreateCreditCardOfferForCard(card, "5%")); std::vector<Suggestion> suggestions = {Suggestion()}; - suggestions[0].backend_id = kTestGuid; + suggestions[0].payload = kTestGuid; autofill_offer_manager_->UpdateSuggestionsWithOffers( GURL("http://wrongurl.com/"), suggestions); @@ -181,8 +181,8 @@ CreateCreditCardOfferForCard(cardWithOffer, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; - suggestions[0].backend_id = kTestGuid; - suggestions[1].backend_id = kTestGuid2; + suggestions[0].payload = kTestGuid; + suggestions[1].payload = kTestGuid2; autofill_offer_manager_->UpdateSuggestionsWithOffers(GURL(kTestUrlWithParam), suggestions); @@ -190,8 +190,8 @@ // suggestion[0] EXPECT_TRUE(!suggestions[0].offer_label.empty()); EXPECT_TRUE(suggestions[1].offer_label.empty()); - EXPECT_EQ(suggestions[0].backend_id, kTestGuid2); - EXPECT_EQ(suggestions[1].backend_id, kTestGuid); + EXPECT_EQ(absl::get<std::string>(suggestions[0].payload), kTestGuid2); + EXPECT_EQ(absl::get<std::string>(suggestions[1].payload), kTestGuid); } TEST_F(AutofillOfferManagerTest, @@ -206,8 +206,8 @@ CreateCreditCardOfferForCard(cardWithOffer, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; - suggestions[0].backend_id = kTestGuid; - suggestions[1].backend_id = kTestGuid2; + suggestions[0].payload = kTestGuid; + suggestions[1].payload = kTestGuid2; autofill_offer_manager_->UpdateSuggestionsWithOffers(GURL(kTestUrlWithParam), suggestions); @@ -215,8 +215,8 @@ // is turned off. EXPECT_TRUE(suggestions[0].offer_label.empty()); EXPECT_TRUE(!suggestions[1].offer_label.empty()); - EXPECT_EQ(suggestions[0].backend_id, kTestGuid); - EXPECT_EQ(suggestions[1].backend_id, kTestGuid2); + EXPECT_EQ(absl::get<std::string>(suggestions[0].payload), kTestGuid); + EXPECT_EQ(absl::get<std::string>(suggestions[1].payload), kTestGuid2); } TEST_F(AutofillOfferManagerTest, @@ -229,13 +229,13 @@ CreateCreditCardOfferForCard(card2, "5%")); std::vector<Suggestion> suggestions = {Suggestion(), Suggestion()}; - suggestions[0].backend_id = kTestGuid; - suggestions[1].backend_id = kTestGuid2; + suggestions[0].payload = kTestGuid; + suggestions[1].payload = kTestGuid2; autofill_offer_manager_->UpdateSuggestionsWithOffers(GURL(kTestUrlWithParam), suggestions); - EXPECT_EQ(suggestions[0].backend_id, kTestGuid); - EXPECT_EQ(suggestions[1].backend_id, kTestGuid2); + EXPECT_EQ(absl::get<std::string>(suggestions[0].payload), kTestGuid); + EXPECT_EQ(absl::get<std::string>(suggestions[1].payload), kTestGuid2); } TEST_F(AutofillOfferManagerTest, IsUrlEligible) {
diff --git a/components/autofill/core/browser/ui/autofill_popup_delegate.h b/components/autofill/core/browser/ui/autofill_popup_delegate.h index beef2b4..32b1e5a 100644 --- a/components/autofill/core/browser/ui/autofill_popup_delegate.h +++ b/components/autofill/core/browser/ui/autofill_popup_delegate.h
@@ -9,6 +9,7 @@ #include "base/callback_forward.h" #include "components/autofill/core/browser/ui/popup_types.h" +#include "components/autofill/core/browser/ui/suggestion.h" #include "third_party/abseil-cpp/absl/types/variant.h" namespace password_manager { @@ -46,11 +47,12 @@ // negative values (see popup_item_ids.h) which have special built-in meanings // while others have positive values which represents the backend data model // this suggestion relates to. See 'MakeFrontendID' in BrowserAutofillManager. - // |backend_id| is the guid of the backend data model. |position| refers to - // the index of the suggestion in the suggestion list. + // |payload| is the payload of the suggestion, and it represents the GUID of + // the backend data model. |position| refers to the index of the suggestion in + // the suggestion list. virtual void DidAcceptSuggestion(const std::u16string& value, int frontend_id, - const std::string& backend_id, + const Suggestion::Payload& payload, int position) = 0; // Returns whether the given value can be deleted, and if true,
diff --git a/components/autofill/core/browser/ui/suggestion.h b/components/autofill/core/browser/ui/suggestion.h index a5af9f73..494bc5a3 100644 --- a/components/autofill/core/browser/ui/suggestion.h +++ b/components/autofill/core/browser/ui/suggestion.h
@@ -10,13 +10,17 @@ #include "base/strings/string_piece.h" #include "base/types/strong_alias.h" #include "build/build_config.h" +#include "components/autofill/core/browser/ui/popup_item_ids.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" + namespace autofill { struct Suggestion { using IsLoading = base::StrongAlias<class IsLoadingTag, bool>; + using Payload = absl::variant<std::string>; enum MatchMode { PREFIX_MATCH, // for prefix matched suggestions; @@ -69,9 +73,14 @@ Suggestion& operator=(Suggestion&& other); ~Suggestion(); - // GUID generated by the backend layer. This identifies the exact autofill - // profile that generated this suggestion. - std::string backend_id; + template <typename T> + T GetPayload() const { + return absl::holds_alternative<T>(payload) ? absl::get<T>(payload) : T{}; + } + + // Payload generated by the backend layer. This payload is a GUID that + // identifies the exact autofill profile that generated this suggestion. + Payload payload; // TODO(crbug.com/1325509): Convert |frontend_id| from an int to a // PopupItemId.
diff --git a/components/autofill/core/browser/ui/suggestion_selection.cc b/components/autofill/core/browser/ui/suggestion_selection.cc index 7697f3087..64a56eb 100644 --- a/components/autofill/core/browser/ui/suggestion_selection.cc +++ b/components/autofill/core/browser/ui/suggestion_selection.cc
@@ -126,7 +126,7 @@ } suggestions.emplace_back(value); - suggestions.back().backend_id = profile->guid(); + suggestions.back().payload = profile->guid(); suggestions.back().match = prefix_matched_suggestion ? Suggestion::PREFIX_MATCH : Suggestion::SUBSTRING_MATCH;
diff --git a/components/autofill_assistant/browser/actions/action_delegate_util_unittest.cc b/components/autofill_assistant/browser/actions/action_delegate_util_unittest.cc index 533d0698..d7f9b58 100644 --- a/components/autofill_assistant/browser/actions/action_delegate_util_unittest.cc +++ b/components/autofill_assistant/browser/actions/action_delegate_util_unittest.cc
@@ -218,7 +218,7 @@ auto element = std::make_unique<ElementFinderResult>(); content::WebContentsTester::For(web_contents_.get()) ->NavigateAndCommit(GURL("https://www.example.com")); - element->SetRenderFrameHost(web_contents_->GetMainFrame()); + element->SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); user_data_.selected_login_ = absl::make_optional<WebsiteLoginManager::Login>( GURL("https://www.example.com"), "username"); @@ -241,7 +241,7 @@ TEST_F(ActionDelegateUtilTest, PerformWithFailingPasswordManagerValue) { auto element = std::make_unique<ElementFinderResult>(); - element->SetRenderFrameHost(web_contents_->GetMainFrame()); + element->SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); user_data_.selected_login_ = absl::make_optional<WebsiteLoginManager::Login>( GURL("https://www.example.com"), "username");
diff --git a/components/autofill_assistant/browser/actions/collect_user_data_action.cc b/components/autofill_assistant/browser/actions/collect_user_data_action.cc index 504b805d..5177a342 100644 --- a/components/autofill_assistant/browser/actions/collect_user_data_action.cc +++ b/components/autofill_assistant/browser/actions/collect_user_data_action.cc
@@ -698,8 +698,9 @@ DCHECK(user_data); if (!shown_to_user_) { shown_to_user_ = true; - metrics_data_.source_id = - delegate_->GetWebContents()->GetMainFrame()->GetPageUkmSourceId(); + metrics_data_.source_id = delegate_->GetWebContents() + ->GetPrimaryMainFrame() + ->GetPageUkmSourceId(); metrics_data_.user_data_source = user_data_source; FillInitialDataStateForMetrics(user_data->available_contacts_, user_data->available_addresses_,
diff --git a/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc b/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc index e9ceb51..7febc8c 100644 --- a/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc
@@ -153,7 +153,7 @@ content::WebContentsTester::For(web_contents_.get()) ->SetLastCommittedURL(GURL(kFakeUrl)); ukm::InitializeSourceUrlRecorderForWebContents(web_contents_.get()); - source_id_ = web_contents_->GetMainFrame()->GetPageUkmSourceId(); + source_id_ = web_contents_->GetPrimaryMainFrame()->GetPageUkmSourceId(); ON_CALL(mock_action_delegate_, GetPersonalDataManager) .WillByDefault(Return(&mock_personal_data_manager_));
diff --git a/components/autofill_assistant/browser/actions/get_element_status_action_unittest.cc b/components/autofill_assistant/browser/actions/get_element_status_action_unittest.cc index 48b9607..4fdd67b 100644 --- a/components/autofill_assistant/browser/actions/get_element_status_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/get_element_status_action_unittest.cc
@@ -705,7 +705,7 @@ .WillOnce(WithArgs<1>([this](auto&& callback) { std::unique_ptr<ElementFinderResult> element = std::make_unique<ElementFinderResult>(); - element->SetRenderFrameHost(web_contents_->GetMainFrame()); + element->SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); std::move(callback).Run(OkClientStatus(), std::move(element)); })); EXPECT_CALL(mock_website_login_manager_, GetPasswordForLogin(_, _))
diff --git a/components/autofill_assistant/browser/actions/send_keystroke_events_action_unittest.cc b/components/autofill_assistant/browser/actions/send_keystroke_events_action_unittest.cc index 4e07f99..f41c3ff1 100644 --- a/components/autofill_assistant/browser/actions/send_keystroke_events_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/send_keystroke_events_action_unittest.cc
@@ -120,7 +120,7 @@ content::WebContentsTester::For(web_contents_.get()) ->NavigateAndCommit(GURL(kUrl)); element.SetObjectId("id"); - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); mock_action_delegate_.GetElementStore()->AddElement("e", element.dom_object()); @@ -161,7 +161,7 @@ content::WebContentsTester::For(web_contents_.get()) ->NavigateAndCommit(GURL(kUrl)); element.SetObjectId("id"); - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); mock_action_delegate_.GetElementStore()->AddElement("e", element.dom_object());
diff --git a/components/autofill_assistant/browser/controller_unittest.cc b/components/autofill_assistant/browser/controller_unittest.cc index 6cbb3e55..69df4d8 100644 --- a/components/autofill_assistant/browser/controller_unittest.cc +++ b/components/autofill_assistant/browser/controller_unittest.cc
@@ -216,7 +216,7 @@ void SimulateNavigateToUrl(const GURL& url) { SetLastCommittedUrl(url); content::NavigationSimulator::NavigateAndCommitFromDocument( - url, web_contents()->GetMainFrame()); + url, web_contents()->GetPrimaryMainFrame()); content::WebContentsTester::For(web_contents())->TestSetIsLoading(false); controller_->DidFinishLoad(nullptr, GURL("")); } @@ -784,7 +784,7 @@ NavigationStateChangeListener listener(controller_.get()); controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); controller_->RemoveNavigationListener(&listener); EXPECT_FALSE(controller_->IsNavigatingToNewDocument()); @@ -802,7 +802,7 @@ controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndFailFromDocument( GURL("http://initialurl.com"), net::ERR_CONNECTION_TIMED_OUT, - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); controller_->RemoveNavigationListener(&listener); EXPECT_FALSE(controller_->IsNavigatingToNewDocument()); @@ -821,7 +821,8 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( - GURL("http://original.example.com/"), web_contents()->GetMainFrame()); + GURL("http://original.example.com/"), + web_contents()->GetPrimaryMainFrame()); simulator->SetTransition(ui::PAGE_TRANSITION_LINK); simulator->Start(); EXPECT_TRUE(controller_->IsNavigatingToNewDocument()); @@ -850,9 +851,9 @@ controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndFailFromDocument( GURL("http://initialurl.com"), net::ERR_CONNECTION_TIMED_OUT, - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); controller_->RemoveNavigationListener(&listener); EXPECT_FALSE(controller_->IsNavigatingToNewDocument()); @@ -874,15 +875,15 @@ NavigationStateChangeListener listener(controller_.get()); controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); listener.events.clear(); controller_->RemoveNavigationListener(&listener); content::NavigationSimulator::NavigateAndFailFromDocument( GURL("http://initialurl.com"), net::ERR_CONNECTION_TIMED_OUT, - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); EXPECT_THAT(listener.events, IsEmpty()); } @@ -976,7 +977,8 @@ EXPECT_THAT(processed_actions_capture, SizeIs(0)); std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( - GURL("http://a.example.com/path"), web_contents()->GetMainFrame()); + GURL("http://a.example.com/path"), + web_contents()->GetPrimaryMainFrame()); simulator->SetTransition(ui::PAGE_TRANSITION_LINK); simulator->Start(); task_environment()->FastForwardBy(base::Seconds(1)); @@ -1728,7 +1730,7 @@ EXPECT_CALL(mock_client_, Shutdown(_)).Times(0); EXPECT_CALL(mock_client_, RecordDropOut(_)).Times(0); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://a.example.com/page"), web_contents()->GetMainFrame()); + GURL("http://a.example.com/page"), web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(AutofillAssistantState::PROMPT, controller_->GetState()); // Expected browser initiated navigation is allowed. @@ -1776,7 +1778,7 @@ EXPECT_CALL(mock_client_, Shutdown(_)).Times(0); EXPECT_CALL(mock_client_, RecordDropOut(_)).Times(0); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://a.example.com/page"), web_contents()->GetMainFrame()); + GURL("http://a.example.com/page"), web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(AutofillAssistantState::RUNNING, controller_->GetState()); // Expected browser initiated navigation while in RUNNING state: @@ -2098,7 +2100,8 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( - GURL("http://a.example.com/path"), web_contents()->GetMainFrame()); + GURL("http://a.example.com/path"), + web_contents()->GetPrimaryMainFrame()); simulator->SetTransition(ui::PAGE_TRANSITION_LINK); simulator->Start(); task_environment()->FastForwardBy(base::Seconds(1)); @@ -2223,7 +2226,7 @@ controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); EXPECT_THAT( listener.events, @@ -2281,7 +2284,7 @@ controller_->AddNavigationListener(&listener); content::NavigationSimulator::NavigateAndCommitFromDocument( - GURL("http://initialurl.com"), web_contents()->GetMainFrame()); + GURL("http://initialurl.com"), web_contents()->GetPrimaryMainFrame()); EXPECT_THAT( listener.events, @@ -2292,10 +2295,10 @@ listener.events.clear(); // Create a fenced frame. - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->InitializeRenderFrameIfNeeded(); content::RenderFrameHost* fenced_frame_rfh = - CreateFencedFrame(web_contents()->GetMainFrame()); + CreateFencedFrame(web_contents()->GetPrimaryMainFrame()); GURL kFencedFrameUrl("https://fencedframe.com"); std::unique_ptr<content::NavigationSimulator> navigation_simulator = content::NavigationSimulator::CreateRendererInitiated(kFencedFrameUrl,
diff --git a/components/autofill_assistant/browser/full_card_requester.cc b/components/autofill_assistant/browser/full_card_requester.cc index b7361300..f5359ca 100644 --- a/components/autofill_assistant/browser/full_card_requester.cc +++ b/components/autofill_assistant/browser/full_card_requester.cc
@@ -38,7 +38,7 @@ } autofill::ContentAutofillDriver* driver = - factory->DriverForFrame(web_contents->GetMainFrame()); + factory->DriverForFrame(web_contents->GetPrimaryMainFrame()); if (!driver) { OnFullCardRequestFailed(FullCardRequest::FailureType::GENERIC_FAILURE); return;
diff --git a/components/autofill_assistant/browser/starter.cc b/components/autofill_assistant/browser/starter.cc index a1bc80a..2139db3 100644 --- a/components/autofill_assistant/browser/starter.cc +++ b/components/autofill_assistant/browser/starter.cc
@@ -179,7 +179,7 @@ : content::WebContentsObserver(web_contents), content::WebContentsUserData<Starter>(*web_contents), current_ukm_source_id_( - web_contents->GetMainFrame()->GetPageUkmSourceId()), + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId()), cached_failed_trigger_script_fetches_( GetOrCreateFailedTriggerScriptFetchesCache()), user_denylisted_domains_(kMaxUserDenylistedCacheSize), @@ -425,7 +425,7 @@ fetch_trigger_scripts_on_navigation_) { MaybeStartImplicitlyForUrl( web_contents()->GetLastCommittedURL(), - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); } } @@ -513,7 +513,7 @@ if (IsTriggerScriptContext(*pending_trigger_context_) && !url_utils::IsSamePublicSuffixDomain( - web_contents()->GetMainFrame()->GetLastCommittedURL(), + web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), startup_url.value_or(GURL()))) { waiting_for_deeplink_navigation_ = true; return;
diff --git a/components/autofill_assistant/browser/starter_unittest.cc b/components/autofill_assistant/browser/starter_unittest.cc index 84befed..f871e19 100644 --- a/components/autofill_assistant/browser/starter_unittest.cc +++ b/components/autofill_assistant/browser/starter_unittest.cc
@@ -182,20 +182,20 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( web_contents()->GetLastCommittedURL(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); simulator->Start(); for (const auto& url : urls) { simulator->Redirect(url); } simulator->Commit(); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); } void SimulateNavigateToUrl(const GURL& url) { content::WebContentsTester::For(web_contents())->NavigateAndCommit(url); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); } // Each request sender is only good for one trigger script. This call will @@ -1345,13 +1345,13 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( web_contents()->GetLastCommittedURL(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); simulator->Start(); simulator->Redirect(GURL("https://redirect.com/to/www/example/com")); simulator->Fail(net::ERR_BLOCKED_BY_CLIENT); simulator->CommitErrorPage(); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); // Note that this impression is recorded for the last URL that a navigation- // start event occurred for. We never reached the target domain, so this is @@ -1391,7 +1391,7 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( web_contents()->GetLastCommittedURL(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); simulator->Start(); simulator->Redirect(GURL("https://redirect.com/to/www/example/com")); starter_->Start(std::make_unique<TriggerContext>( @@ -1399,7 +1399,7 @@ simulator->Redirect(GURL(kExampleDeeplink)); simulator->Commit(); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); EXPECT_THAT(GetUkmTriggerScriptStarted(ukm_recorder_), ElementsAreArray(ToHumanReadableMetrics( @@ -1426,7 +1426,7 @@ std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( web_contents()->GetLastCommittedURL(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); simulator->Start(); simulator->Redirect(GURL("https://redirect.com/to/www/example/com")); @@ -2293,10 +2293,10 @@ TriggerContext::Options())); // Create a fenced frame and navigate to the example deeplink. The navigation // should not start because it is not in the primary main frame. - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->InitializeRenderFrameIfNeeded(); content::RenderFrameHost* fenced_frame_rfh = - CreateFencedFrame(web_contents()->GetMainFrame()); + CreateFencedFrame(web_contents()->GetPrimaryMainFrame()); std::unique_ptr<content::NavigationSimulator> navigation_simulator = content::NavigationSimulator::CreateRendererInitiated( GURL(kExampleDeeplink), fenced_frame_rfh);
diff --git a/components/autofill_assistant/browser/suppress_keyboard_raii.cc b/components/autofill_assistant/browser/suppress_keyboard_raii.cc index 7873af5..104bdec 100644 --- a/components/autofill_assistant/browser/suppress_keyboard_raii.cc +++ b/components/autofill_assistant/browser/suppress_keyboard_raii.cc
@@ -36,7 +36,7 @@ } void SuppressKeyboardRAII::SuppressKeyboard(bool suppress) { - web_contents()->GetMainFrame()->ForEachRenderFrameHost( + web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHost( base::BindRepeating(&SuppressKeyboardForFrame, suppress)); }
diff --git a/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator.cc b/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator.cc index 932503a..2cc6ee3 100644 --- a/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator.cc +++ b/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator.cc
@@ -626,7 +626,8 @@ } GURL TriggerScriptCoordinator::GetCurrentURL() const { - GURL current_url = web_contents()->GetMainFrame()->GetLastCommittedURL(); + GURL current_url = + web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(); if (current_url.is_empty()) { return deeplink_url_; }
diff --git a/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator_unittest.cc b/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator_unittest.cc index 07d2b248..193eb909 100644 --- a/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator_unittest.cc +++ b/components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator_unittest.cc
@@ -105,7 +105,7 @@ std::move(mock_web_controller), std::move(mock_request_sender), GURL(kFakeServerUrl), std::move(mock_static_trigger_conditions), std::move(mock_dynamic_trigger_conditions), &ukm_recorder_, - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); } void TearDown() override { coordinator_.reset(); } @@ -127,10 +127,10 @@ void SimulateNavigateToUrl(const GURL& url) { content::WebContentsTester::For(web_contents())->SetLastCommittedURL(url); content::NavigationSimulator::NavigateAndCommitFromDocument( - url, web_contents()->GetMainFrame()); + url, web_contents()->GetPrimaryMainFrame()); content::WebContentsTester::For(web_contents())->TestSetIsLoading(false); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); } protected: @@ -1360,7 +1360,7 @@ EXPECT_CALL(*mock_ui_delegate_, ShowTriggerScript).Times(1); content::NavigationSimulator::Reload(web_contents()); navigation_ids_.emplace_back( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); EXPECT_CALL(*mock_ui_delegate_, HideTriggerScript).Times(0); task_environment()->FastForwardBy(base::Seconds(1));
diff --git a/components/autofill_assistant/browser/user_data_util_unittest.cc b/components/autofill_assistant/browser/user_data_util_unittest.cc index 6316eae..eb715bd 100644 --- a/components/autofill_assistant/browser/user_data_util_unittest.cc +++ b/components/autofill_assistant/browser/user_data_util_unittest.cc
@@ -1263,7 +1263,7 @@ GURL("https://www.example.com"), "username"); ElementFinderResult element; - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); PasswordManagerValue password_manager_value; password_manager_value.set_credential_type(PasswordManagerValue::USERNAME); @@ -1281,7 +1281,7 @@ GURL("https://www.example.com"), "username"); ElementFinderResult element; - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); PasswordManagerValue password_manager_value; password_manager_value.set_credential_type(PasswordManagerValue::PASSWORD); @@ -1303,7 +1303,7 @@ ElementFinderResult element; content::WebContentsTester::For(web_contents_.get()) ->NavigateAndCommit(GURL("https://www.example.com")); - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); PasswordManagerValue password_manager_value; password_manager_value.set_credential_type(PasswordManagerValue::PASSWORD); @@ -1419,7 +1419,7 @@ ElementFinderResult element; content::WebContentsTester::For(web_contents_.get()) ->NavigateAndCommit(GURL("https://www.example.com")); - element.SetRenderFrameHost(web_contents_->GetMainFrame()); + element.SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); TextValue text_value; text_value.mutable_password_manager_value()->set_credential_type(
diff --git a/components/autofill_assistant/browser/web/css_element_finder.cc b/components/autofill_assistant/browser/web/css_element_finder.cc index 2a1fe69..a7c9c6e5 100644 --- a/components/autofill_assistant/browser/web/css_element_finder.cc +++ b/components/autofill_assistant/browser/web/css_element_finder.cc
@@ -108,7 +108,7 @@ current_frame_ = start_element.render_frame_host(); if (current_frame_ == nullptr) { - current_frame_ = web_contents_->GetMainFrame(); + current_frame_ = web_contents_->GetPrimaryMainFrame(); } current_frame_id_ = start_element.node_frame_id(); frame_stack_ = start_element.frame_stack();
diff --git a/components/autofill_assistant/browser/web/element.cc b/components/autofill_assistant/browser/web/element.cc index 8fb951d..526ca8a 100644 --- a/components/autofill_assistant/browser/web/element.cc +++ b/components/autofill_assistant/browser/web/element.cc
@@ -50,19 +50,21 @@ const std::string& frame_id, content::WebContents* web_contents) { if (frame_id.empty()) { - return web_contents->GetMainFrame(); + return web_contents->GetPrimaryMainFrame(); } content::RenderFrameHost* result = nullptr; - web_contents->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - [](const std::string& frame_id, content::RenderFrameHost** result, - content::RenderFrameHost* render_frame_host) { - if (render_frame_host->GetDevToolsFrameToken().ToString() == frame_id) { - *result = render_frame_host; - return content::RenderFrameHost::FrameIterationAction::kStop; - } - return content::RenderFrameHost::FrameIterationAction::kContinue; - }, - frame_id, &result)); + web_contents->GetPrimaryMainFrame()->ForEachRenderFrameHost( + base::BindRepeating( + [](const std::string& frame_id, content::RenderFrameHost** result, + content::RenderFrameHost* render_frame_host) { + if (render_frame_host->GetDevToolsFrameToken().ToString() == + frame_id) { + *result = render_frame_host; + return content::RenderFrameHost::FrameIterationAction::kStop; + } + return content::RenderFrameHost::FrameIterationAction::kContinue; + }, + frame_id, &result)); return result; }
diff --git a/components/autofill_assistant/browser/web/element_store_unittest.cc b/components/autofill_assistant/browser/web/element_store_unittest.cc index 1451fd47..bca656e 100644 --- a/components/autofill_assistant/browser/web/element_store_unittest.cc +++ b/components/autofill_assistant/browser/web/element_store_unittest.cc
@@ -34,8 +34,9 @@ const std::string& object_id) { auto element = std::make_unique<ElementFinderResult>(); element->SetObjectId(object_id); - element->SetNodeFrameId( - web_contents_->GetMainFrame()->GetDevToolsFrameToken().ToString()); + element->SetNodeFrameId(web_contents_->GetPrimaryMainFrame() + ->GetDevToolsFrameToken() + .ToString()); return element; } @@ -93,7 +94,7 @@ ElementFinderResult result; EXPECT_EQ(ACTION_APPLIED, element_store_->GetElement("1", &result).proto_status()); - EXPECT_EQ(web_contents_->GetMainFrame(), result.render_frame_host()); + EXPECT_EQ(web_contents_->GetPrimaryMainFrame(), result.render_frame_host()); } TEST_F(ElementStoreTest, AddElementToStoreOverwrites) {
diff --git a/components/autofill_assistant/browser/web/fake_element_store.cc b/components/autofill_assistant/browser/web/fake_element_store.cc index 7fc1400b..8568a79 100644 --- a/components/autofill_assistant/browser/web/fake_element_store.cc +++ b/components/autofill_assistant/browser/web/fake_element_store.cc
@@ -27,7 +27,7 @@ out_element->SetNodeFrameId(it->second.object_data.node_frame_id); out_element->SetFrameStack(it->second.frame_stack); if (web_contents_ != nullptr) { - out_element->SetRenderFrameHost(web_contents_->GetMainFrame()); + out_element->SetRenderFrameHost(web_contents_->GetPrimaryMainFrame()); } return OkClientStatus(); }
diff --git a/components/autofill_assistant/browser/web/mock_autofill_assistant_agent.cc b/components/autofill_assistant/browser/web/mock_autofill_assistant_agent.cc index 5811665..93594192 100644 --- a/components/autofill_assistant/browser/web/mock_autofill_assistant_agent.cc +++ b/components/autofill_assistant/browser/web/mock_autofill_assistant_agent.cc
@@ -24,7 +24,7 @@ void MockAutofillAssistantAgent::RegisterForAllFrames( content::WebContents* web_contents, MockAutofillAssistantAgent* agent) { - web_contents->GetMainFrame()->ForEachRenderFrameHost( + web_contents->GetPrimaryMainFrame()->ForEachRenderFrameHost( base::BindLambdaForTesting([agent](content::RenderFrameHost* host) { host->GetRemoteAssociatedInterfaces()->OverrideBinderForTesting( mojom::AutofillAssistantAgent::Name_,
diff --git a/components/autofill_assistant/browser/web/semantic_element_finder.cc b/components/autofill_assistant/browser/web/semantic_element_finder.cc index 8ba3af6..5ed6bf8 100644 --- a/components/autofill_assistant/browser/web/semantic_element_finder.cc +++ b/components/autofill_assistant/browser/web/semantic_element_finder.cc
@@ -102,7 +102,7 @@ auto* start_frame = start_element.render_frame_host(); if (!start_frame) { - start_frame = web_contents_->GetMainFrame(); + start_frame = web_contents_->GetPrimaryMainFrame(); } RunAnnotateDomModel(start_frame); }
diff --git a/components/autofill_assistant/browser/web/web_controller_browsertest.cc b/components/autofill_assistant/browser/web/web_controller_browsertest.cc index 0b6088d..aed1001c 100644 --- a/components/autofill_assistant/browser/web/web_controller_browsertest.cc +++ b/components/autofill_assistant/browser/web/web_controller_browsertest.cc
@@ -560,11 +560,11 @@ void CheckFindElementResult(const ElementFinderResult& result, bool is_main_frame) { if (is_main_frame) { - EXPECT_EQ(shell()->web_contents()->GetMainFrame(), + EXPECT_EQ(shell()->web_contents()->GetPrimaryMainFrame(), result.render_frame_host()); EXPECT_EQ(result.frame_stack().size(), 0u); } else { - EXPECT_NE(shell()->web_contents()->GetMainFrame(), + EXPECT_NE(shell()->web_contents()->GetPrimaryMainFrame(), result.render_frame_host()); EXPECT_GE(result.frame_stack().size(), 1u); } @@ -2702,7 +2702,7 @@ // This makes the devtools action fail. ElementFinderResult element; element.SetNodeFrameId("doesnotexist"); - element.SetRenderFrameHost(web_contents()->GetMainFrame()); + element.SetRenderFrameHost(web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(ELEMENT_POSITION_NOT_FOUND, WaitUntilElementIsStable(element, 10, base::Milliseconds(100))
diff --git a/components/autofill_assistant/browser/website_login_manager_impl.cc b/components/autofill_assistant/browser/website_login_manager_impl.cc index f3f5b48..c74f7c2fa 100644 --- a/components/autofill_assistant/browser/website_login_manager_impl.cc +++ b/components/autofill_assistant/browser/website_login_manager_impl.cc
@@ -465,7 +465,8 @@ // TODO(crbug.com/1043132): Add support for non-main frames. If another // frame has a different origin than the main frame, passwords-related // features may not work. - auto* driver = factory->GetDriverForFrame(web_contents_->GetMainFrame()); + auto* driver = + factory->GetDriverForFrame(web_contents_->GetPrimaryMainFrame()); if (!driver) { return absl::nullopt; }
diff --git a/components/autofill_assistant/content/browser/content_autofill_assistant_driver_unittest.cc b/components/autofill_assistant/content/browser/content_autofill_assistant_driver_unittest.cc index 1fa0bd2..743e1904 100644 --- a/components/autofill_assistant/content/browser/content_autofill_assistant_driver_unittest.cc +++ b/components/autofill_assistant/content/browser/content_autofill_assistant_driver_unittest.cc
@@ -48,8 +48,8 @@ &browser_context_, nullptr); // Constructor of ContentAutofillAssistantDriver is private, cannot use // std::make_unique. - driver_ = base::WrapUnique( - new ContentAutofillAssistantDriver(web_contents_->GetMainFrame())); + driver_ = base::WrapUnique(new ContentAutofillAssistantDriver( + web_contents_->GetPrimaryMainFrame())); driver_->SetAnnotateDomModelService(annotate_dom_model_service_.get()); }
diff --git a/components/background_sync/background_sync_permission_context_unittest.cc b/components/background_sync/background_sync_permission_context_unittest.cc index 198fade..341a4fb 100644 --- a/components/background_sync/background_sync_permission_context_unittest.cc +++ b/components/background_sync/background_sync_permission_context_unittest.cc
@@ -43,8 +43,8 @@ base::RunLoop run_loop; const permissions::PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); permission_context->RequestPermission( id, url, /* user_gesture= */ false,
diff --git a/components/blocked_content/popup_blocker_tab_helper.cc b/components/blocked_content/popup_blocker_tab_helper.cc index 0352979..111264a 100644 --- a/components/blocked_content/popup_blocker_tab_helper.cc +++ b/components/blocked_content/popup_blocker_tab_helper.cc
@@ -76,7 +76,7 @@ void PopupBlockerTabHelper::HidePopupNotification() { auto* pscs = content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); if (pscs) pscs->ClearPopupsBlocked(); } @@ -96,7 +96,7 @@ auto* content_settings = content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); if (content_settings) { content_settings->OnContentBlocked(ContentSettingsType::POPUPS); }
diff --git a/components/blocked_content/popup_blocker_tab_helper_unittest.cc b/components/blocked_content/popup_blocker_tab_helper_unittest.cc index a8cf87f8..547f2fe 100644 --- a/components/blocked_content/popup_blocker_tab_helper_unittest.cc +++ b/components/blocked_content/popup_blocker_tab_helper_unittest.cc
@@ -159,7 +159,7 @@ TEST_F(PopupBlockerTabHelperTest, SetsContentSettingsPopupState) { auto* content_settings = content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_FALSE(content_settings->IsContentBlocked(ContentSettingsType::POPUPS)); TestPopupNavigationDelegate::ResultHolder result; @@ -186,12 +186,12 @@ std::make_unique<TestPopupNavigationDelegate>(GURL(kUrl1), &result), blink::mojom::WindowFeatures(), PopupBlockType::kNoGesture); EXPECT_TRUE(content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) ->IsContentBlocked(ContentSettingsType::POPUPS)); NavigateAndCommit(GURL(kUrl2)); EXPECT_FALSE(content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) ->IsContentBlocked(ContentSettingsType::POPUPS)); } @@ -202,24 +202,24 @@ std::make_unique<TestPopupNavigationDelegate>(GURL(kUrl1), &result), blink::mojom::WindowFeatures(), PopupBlockType::kNoGesture); EXPECT_TRUE(content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) ->IsContentBlocked(ContentSettingsType::POPUPS)); // Navigating a non-primary main frame shoudn't clear the popups. content::MockNavigationHandle handle(GURL(kUrl2), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); handle.set_has_committed(true); handle.set_is_in_primary_main_frame(false); helper()->DidFinishNavigation(&handle); EXPECT_TRUE(content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) ->IsContentBlocked(ContentSettingsType::POPUPS)); // Navigating the primary main frame should clear the popups. handle.set_is_in_primary_main_frame(true); helper()->DidFinishNavigation(&handle); EXPECT_FALSE(content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) ->IsContentBlocked(ContentSettingsType::POPUPS)); }
diff --git a/components/blocked_content/popup_opener_tab_helper.cc b/components/blocked_content/popup_opener_tab_helper.cc index c4ba2c9..fbe1c90 100644 --- a/components/blocked_content/popup_opener_tab_helper.cc +++ b/components/blocked_content/popup_opener_tab_helper.cc
@@ -102,7 +102,7 @@ return; const ukm::SourceId source_id = - web_contents()->GetMainFrame()->GetPageUkmSourceId(); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId(); // Do not record duplicate Popup.Page events for popups opened in succession // from the same opener.
diff --git a/components/blocked_content/popup_tracker.cc b/components/blocked_content/popup_tracker.cc index 9d64027..a3577dc 100644 --- a/components/blocked_content/popup_tracker.cc +++ b/components/blocked_content/popup_tracker.cc
@@ -50,7 +50,7 @@ visibility_tracker_( base::DefaultTickClock::GetInstance(), contents->GetVisibility() != content::Visibility::HIDDEN), - opener_source_id_(opener->GetMainFrame()->GetPageUkmSourceId()), + opener_source_id_(opener->GetPrimaryMainFrame()->GetPageUkmSourceId()), window_open_disposition_(disposition) { if (auto* popup_opener = PopupOpenerTabHelper::FromWebContents(opener)) popup_opener->OnOpenedPopup(this);
diff --git a/components/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc b/components/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc index f0f5891..28bacee8 100644 --- a/components/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc +++ b/components/blocked_content/safe_browsing_triggered_popup_blocker_unittest.cc
@@ -192,7 +192,7 @@ for (const auto& test_case : kTestCases) { std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateRendererInitiated( - test_case.initial_url, web_contents()->GetMainFrame()); + test_case.initial_url, web_contents()->GetPrimaryMainFrame()); simulator->Start(); simulator->Redirect(test_case.redirect_url); simulator->Commit();
diff --git a/components/browsing_topics/browsing_topics_page_load_data_tracker_unittest.cc b/components/browsing_topics/browsing_topics_page_load_data_tracker_unittest.cc index 397752c..664bad4 100644 --- a/components/browsing_topics/browsing_topics_page_load_data_tracker_unittest.cc +++ b/components/browsing_topics/browsing_topics_page_load_data_tracker_unittest.cc
@@ -111,12 +111,12 @@ BrowsingTopicsPageLoadDataTracker* GetBrowsingTopicsPageLoadDataTracker() { return BrowsingTopicsPageLoadDataTracker::GetOrCreateForPage( - web_contents()->GetMainFrame()->GetPage()); + web_contents()->GetPrimaryMainFrame()->GetPage()); } content::BrowsingTopicsSiteDataManager* topics_site_data_manager() { return web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess() ->GetStoragePartition() ->GetBrowsingTopicsSiteDataManager();
diff --git a/components/browsing_topics/browsing_topics_service_impl_unittest.cc b/components/browsing_topics/browsing_topics_service_impl_unittest.cc index a86762e..b79fd58c4 100644 --- a/components/browsing_topics/browsing_topics_service_impl_unittest.cc +++ b/components/browsing_topics/browsing_topics_service_impl_unittest.cc
@@ -225,7 +225,7 @@ content::BrowsingTopicsSiteDataManager* topics_site_data_manager() { return web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess() ->GetStoragePartition() ->GetBrowsingTopicsSiteDataManager(); @@ -561,7 +561,7 @@ ->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create( GURL("https://www.bar.com")), - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) .empty()); auto entries = ukm_recorder.GetEntriesByName( ukm::builders::BrowsingTopics_DocumentBrowsingTopicsApiResult:: @@ -589,7 +589,7 @@ ->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create( GURL("https://www.bar.com")), - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) .empty()); EXPECT_FALSE(browsing_topics_service_ ->GetTopicsForSiteForDisplay( @@ -802,7 +802,7 @@ ->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create( GURL("https://www.bar.com")), - web_contents()->GetMainFrame()) + web_contents()->GetPrimaryMainFrame()) .empty()); auto entries = ukm_recorder.GetEntriesByName( @@ -838,7 +838,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_TRUE(result.empty()); @@ -857,7 +857,7 @@ result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 1u); EXPECT_EQ(result[0]->topic, 2); @@ -891,7 +891,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_TRUE(result.empty()); @@ -927,7 +927,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_TRUE(result.empty()); @@ -939,7 +939,7 @@ result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_TRUE(result.empty()); } @@ -988,7 +988,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 3u); std::set<int> result_set; @@ -1002,7 +1002,7 @@ result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 3u); result_set.clear(); @@ -1057,7 +1057,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 2u); std::set<int> result_set; @@ -1070,7 +1070,7 @@ result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 2u); result_set.clear(); @@ -1133,7 +1133,7 @@ std::vector<blink::mojom::EpochTopicPtr> result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(result.size(), 2u); std::set<int> result_set; @@ -1170,7 +1170,7 @@ NavigateToPage(GURL("https://www.foo.com")); browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); std::vector<ApiUsageContext> api_usage_contexts = content::GetBrowsingTopicsApiUsage(topics_site_data_manager()); @@ -1210,7 +1210,7 @@ // any metrics. browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); entries = ukm_recorder.GetEntriesByName( ukm::builders::BrowsingTopics_DocumentBrowsingTopicsApiResult:: @@ -1232,7 +1232,7 @@ browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); entries = ukm_recorder.GetEntriesByName( ukm::builders::BrowsingTopics_DocumentBrowsingTopicsApiResult:: @@ -1315,7 +1315,7 @@ browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://www.bar.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); auto entries = ukm_recorder.GetEntriesByName( ukm::builders::BrowsingTopics_DocumentBrowsingTopicsApiResult:: @@ -1399,7 +1399,7 @@ // Current time is before the epoch switch time. std::vector<privacy_sandbox::CanonicalTopic> result = browsing_topics_service_->GetTopicsForSiteForDisplay( - web_contents()->GetMainFrame()->GetLastCommittedOrigin()); + web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin()); EXPECT_EQ(result.size(), 2u); EXPECT_EQ(result[0].topic_id(), Topic(2)); @@ -1744,7 +1744,7 @@ std::vector<blink::mojom::EpochTopicPtr> api_call_result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://b.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(api_call_result.size(), 1u); EXPECT_EQ(api_call_result[0]->topic, 3); @@ -1772,7 +1772,7 @@ // the same context domain was seen in the page before. api_call_result = browsing_topics_service_->GetBrowsingTopicsForJsApi( /*context_origin=*/url::Origin::Create(GURL("https://b.com")), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); // Since the domain "b.com" is removed. The candidate topic won't be returned. EXPECT_TRUE(api_call_result.empty());
diff --git a/components/cdm/browser/media_drm_storage_impl_unittest.cc b/components/cdm/browser/media_drm_storage_impl_unittest.cc index fb61cad1..edacff4 100644 --- a/components/cdm/browser/media_drm_storage_impl_unittest.cc +++ b/components/cdm/browser/media_drm_storage_impl_unittest.cc
@@ -131,7 +131,7 @@ } content::RenderFrameHost* SimulateNavigation(const GURL& url) { - content::RenderFrameHost* rfh = web_contents()->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents()->GetPrimaryMainFrame(); content::RenderFrameHostTester::For(rfh)->InitializeRenderFrameIfNeeded(); auto navigation_simulator =
diff --git a/components/commerce/content/browser/web_contents_wrapper.cc b/components/commerce/content/browser/web_contents_wrapper.cc index 7274295..e363f90 100644 --- a/components/commerce/content/browser/web_contents_wrapper.cc +++ b/components/commerce/content/browser/web_contents_wrapper.cc
@@ -31,12 +31,12 @@ void WebContentsWrapper::RunJavascript( const std::u16string& script, base::OnceCallback<void(const base::Value)> callback) { - if (!web_contents_ && web_contents_->GetMainFrame()) { + if (!web_contents_ && web_contents_->GetPrimaryMainFrame()) { std::move(callback).Run(base::Value()); return; } - web_contents_->GetMainFrame()->ExecuteJavaScriptInIsolatedWorld( + web_contents_->GetPrimaryMainFrame()->ExecuteJavaScriptInIsolatedWorld( script, std::move(callback), js_world_id_); }
diff --git a/components/content_capture/android/test_support/content_capture_test_support_android.cc b/components/content_capture/android/test_support/content_capture_test_support_android.cc index ab7601e5..33c00009 100644 --- a/components/content_capture/android/test_support/content_capture_test_support_android.cc +++ b/components/content_capture/android/test_support/content_capture_test_support_android.cc
@@ -69,8 +69,8 @@ ToType(*icon.FindKey("type")->GetIfString()), sizes)); } CHECK(!favicon_urls.empty()); - provider->NotifyFaviconURLUpdatedForTesting(web_contents->GetMainFrame(), - favicon_urls); + provider->NotifyFaviconURLUpdatedForTesting( + web_contents->GetPrimaryMainFrame(), favicon_urls); } } // namespace content_capture
diff --git a/components/content_capture/browser/content_capture_receiver_browsertest.cc b/components/content_capture/browser/content_capture_receiver_browsertest.cc index cdc4a14..fa99f1e 100644 --- a/components/content_capture/browser/content_capture_receiver_browsertest.cc +++ b/components/content_capture/browser/content_capture_receiver_browsertest.cc
@@ -23,7 +23,7 @@ // Navigate to the initial page. const GURL main_frame_url = embedded_test_server()->GetURL(kMainFrameUrl); ASSERT_TRUE(NavigateToURL(web_contents(), main_frame_url)); - main_frame_ = web_contents()->GetMainFrame(); + main_frame_ = web_contents()->GetPrimaryMainFrame(); EXPECT_NE(nullptr, main_frame_); // Create a provider and add a consumer.
diff --git a/components/content_capture/browser/content_capture_receiver_test.cc b/components/content_capture/browser/content_capture_receiver_test.cc index 9f934df..62518f96c 100644 --- a/components/content_capture/browser/content_capture_receiver_test.cc +++ b/components/content_capture/browser/content_capture_receiver_test.cc
@@ -45,7 +45,7 @@ // This needed to keep the WebContentsObserverConsistencyChecker checks // happy for when AppendChild is called. NavigateAndCommit(GURL(kMainFrameUrl)); - main_frame_ = web_contents()->GetMainFrame(); + main_frame_ = web_contents()->GetPrimaryMainFrame(); EXPECT_TRUE(main_frame_); main_frame_sender_ = std::make_unique<FakeContentCaptureSender>(); @@ -57,7 +57,7 @@ void NavigateMainFrame(const GURL& url) { consumer()->Reset(); NavigateAndCommit(url); - main_frame_ = web_contents()->GetMainFrame(); + main_frame_ = web_contents()->GetPrimaryMainFrame(); } void NavigateMainFrameSameDocument() { @@ -302,7 +302,7 @@ // This test is for issue crbug.com/995121 . TEST_P(ContentCaptureReceiverTest, RenderFrameHostGone) { auto* receiver = provider()->ContentCaptureReceiverForFrameForTesting( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); // No good way to simulate crbug.com/995121, just set rfh_ to nullptr in // ContentCaptureReceiver, so content::WebContents::FromRenderFrameHost() // won't return WebContents. @@ -316,7 +316,7 @@ TEST_P(ContentCaptureReceiverTest, TitleUpdateTaskDelay) { auto* receiver = provider()->ContentCaptureReceiverForFrameForTesting( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); // Uses TestMockTimeTaskRunner to check the task state. receiver->title_update_task_runner_ = task_runner; @@ -550,7 +550,7 @@ // This needed to keep the WebContentsObserverConsistencyChecker checks // happy for when AppendChild is called. NavigateAndCommit(GURL("about:blank")); - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("child"); helper_.CreateProviderAndConsumer(web_contents());
diff --git a/components/content_capture/browser/onscreen_content_provider.cc b/components/content_capture/browser/onscreen_content_provider.cc index 27d64fb9..b2da426 100644 --- a/components/content_capture/browser/onscreen_content_provider.cc +++ b/components/content_capture/browser/onscreen_content_provider.cc
@@ -144,8 +144,8 @@ void OnscreenContentProvider::TitleWasSet(content::NavigationEntry* entry) { // Set the title to the mainframe. - if (auto* receiver = - ContentCaptureReceiverForFrame(web_contents()->GetMainFrame())) { + if (auto* receiver = ContentCaptureReceiverForFrame( + web_contents()->GetPrimaryMainFrame())) { // To match what the user sees, intentionally get the title from WebContents // instead of NavigationEntry, though they might be same. receiver->SetTitle(web_contents()->GetTitle()); @@ -290,8 +290,8 @@ bool OnscreenContentProvider::BuildContentCaptureSessionForMainFrame( ContentCaptureSession* session) { - if (auto* receiver = - ContentCaptureReceiverForFrame(web_contents()->GetMainFrame())) { + if (auto* receiver = ContentCaptureReceiverForFrame( + web_contents()->GetPrimaryMainFrame())) { session->push_back(receiver->GetContentCaptureFrame()); return true; }
diff --git a/components/content_settings/browser/page_specific_content_settings_unittest.cc b/components/content_settings/browser/page_specific_content_settings_unittest.cc index 0cba80c..30760b8 100644 --- a/components/content_settings/browser/page_specific_content_settings_unittest.cc +++ b/components/content_settings/browser/page_specific_content_settings_unittest.cc
@@ -116,7 +116,8 @@ TEST_F(PageSpecificContentSettingsTest, BlockedContent) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); // Check that after initializing, nothing is blocked. #if !BUILDFLAG(IS_ANDROID) @@ -140,14 +141,14 @@ origin, "A=B", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */)); ASSERT_TRUE(cookie1); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, {*cookie1}, false}); - content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + content_settings = PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); #if !BUILDFLAG(IS_ANDROID) content_settings->OnContentBlocked(ContentSettingsType::IMAGES); #endif @@ -176,7 +177,7 @@ content_settings->IsContentBlocked(ContentSettingsType::MEDIASTREAM_MIC)); EXPECT_TRUE(content_settings->IsContentBlocked( ContentSettingsType::MEDIASTREAM_CAMERA)); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, @@ -188,7 +189,7 @@ origin, "C=D", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */)); ASSERT_TRUE(cookie2); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, @@ -206,25 +207,25 @@ GetHandle()->OnServiceWorkerAccessed( simulator->GetNavigationHandle(), GURL("http://google.com"), content::AllowServiceWorkerResult::FromPolicy(true, false)); - content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + content_settings = PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); EXPECT_FALSE( content_settings->IsContentBlocked(ContentSettingsType::JAVASCRIPT)); simulator->Commit(); - content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + content_settings = PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); // Block a javascript when page starts to start ServiceWorker. GetHandle()->OnServiceWorkerAccessed( - web_contents()->GetMainFrame(), GURL("http://google.com"), + web_contents()->GetPrimaryMainFrame(), GURL("http://google.com"), content::AllowServiceWorkerResult::FromPolicy(true, false)); EXPECT_TRUE( content_settings->IsContentBlocked(ContentSettingsType::JAVASCRIPT)); // Reset blocked content settings. NavigateAndCommit(GURL("http://google.com")); - content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + content_settings = PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); #if !BUILDFLAG(IS_ANDROID) EXPECT_FALSE(content_settings->IsContentBlocked(ContentSettingsType::IMAGES)); #endif @@ -242,7 +243,8 @@ TEST_F(PageSpecificContentSettingsTest, BlockedFileSystems) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); // Access a file system. content_settings->OnStorageAccessed(StorageType::FILE_SYSTEM, @@ -259,7 +261,8 @@ TEST_F(PageSpecificContentSettingsTest, AllowedContent) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); // Test default settings. ASSERT_FALSE(content_settings->IsContentAllowed(ContentSettingsType::IMAGES)); @@ -278,7 +281,7 @@ origin, "A=B", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */)); ASSERT_TRUE(cookie1); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, @@ -293,7 +296,7 @@ origin, "C=D", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */)); ASSERT_TRUE(cookie2); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, @@ -306,14 +309,15 @@ TEST_F(PageSpecificContentSettingsTest, EmptyCookieList) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); ASSERT_FALSE( content_settings->IsContentAllowed(ContentSettingsType::COOKIES)); ASSERT_FALSE( content_settings->IsContentBlocked(ContentSettingsType::COOKIES)); GetHandle()->OnCookiesAccessed( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kRead, GURL("http://google.com"), GURL("http://google.com"), net::CookieList(), true}); ASSERT_FALSE( @@ -325,7 +329,8 @@ TEST_F(PageSpecificContentSettingsTest, SiteDataObserver) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); MockSiteDataObserver mock_observer(web_contents()); EXPECT_CALL(mock_observer, OnSiteDataAccessed()).Times(6); @@ -335,7 +340,7 @@ origin, "A=B", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */)); ASSERT_TRUE(cookie); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kChange, origin, origin, @@ -352,7 +357,7 @@ cookie_list.push_back(*other_cookie); GetHandle()->OnCookiesAccessed( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kRead, GURL("http://google.com"), GURL("http://google.com"), cookie_list, blocked_by_policy}); content_settings->OnStorageAccessed( @@ -368,13 +373,14 @@ TEST_F(PageSpecificContentSettingsTest, LocalSharedObjectsContainer) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); bool blocked_by_policy = false; auto cookie = net::CanonicalCookie::Create( GURL("http://google.com"), "k=v", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kRead, GURL("http://google.com"), GURL("http://google.com"), @@ -423,7 +429,8 @@ TEST_F(PageSpecificContentSettingsTest, LocalSharedObjectsContainerCookie) { NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); bool blocked_by_policy = false; auto cookie1 = net::CanonicalCookie::Create( GURL("http://google.com"), "k1=v", base::Time::Now(), @@ -441,7 +448,7 @@ GURL("http://www.google.com"), "k4=v; Domain=.www.google.com", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kRead, GURL("http://www.google.com"), GURL("http://www.google.com"), @@ -452,7 +459,7 @@ GURL("https://www.google.com"), "k5=v", base::Time::Now(), absl::nullopt /* server_time */, absl::nullopt /* cookie_partition_key */); - GetHandle()->OnCookiesAccessed(web_contents()->GetMainFrame(), + GetHandle()->OnCookiesAccessed(web_contents()->GetPrimaryMainFrame(), {content::CookieAccessDetails::Type::kRead, GURL("https://www.google.com"), GURL("https://www.google.com"), @@ -470,7 +477,8 @@ NavigateAndCommit(GURL("http://google.com")); PageSpecificContentSettings* content_settings = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); // First trigger OnContentBlocked. EXPECT_FALSE(content_settings->IsContentBlocked( @@ -567,11 +575,11 @@ EXPECT_CALL(mock_observer, OnSiteDataAccessed()).Times(1); std::unique_ptr<content::NavigationSimulator> navigation = content::NavigationSimulator::CreateRendererInitiated( - prerender_url, web_contents()->GetMainFrame()); + prerender_url, web_contents()->GetPrimaryMainFrame()); // TODO(https://crbug.com/1181763): Investigate how default referrer value // is set and update here accordingly. navigation->SetReferrer(blink::mojom::Referrer::New( - web_contents()->GetMainFrame()->GetLastCommittedURL(), + web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin)); navigation->Commit(); } @@ -624,9 +632,9 @@ .Times(1); std::unique_ptr<content::NavigationSimulator> navigation = content::NavigationSimulator::CreateRendererInitiated( - prerender_url, web_contents()->GetMainFrame()); + prerender_url, web_contents()->GetPrimaryMainFrame()); navigation->SetReferrer(blink::mojom::Referrer::New( - web_contents()->GetMainFrame()->GetLastCommittedURL(), + web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin)); navigation->Commit(); } @@ -648,7 +656,7 @@ EXPECT_CALL(*mock_delegate, UpdateLocationBar()).Times(1); std::unique_ptr<content::NavigationSimulator> navigation = content::NavigationSimulator::CreateRendererInitiated( - prerender_url, web_contents()->GetMainFrame()); + prerender_url, web_contents()->GetPrimaryMainFrame()); navigation->Commit(); } @@ -673,19 +681,19 @@ .Times(1); std::unique_ptr<content::NavigationSimulator> navigation = content::NavigationSimulator::CreateRendererInitiated( - prerender_url, web_contents()->GetMainFrame()); + prerender_url, web_contents()->GetPrimaryMainFrame()); // TODO(https://crbug.com/1181763): Investigate how default referrer value is // set and update here accordingly. navigation->SetReferrer(blink::mojom::Referrer::New( - web_contents()->GetMainFrame()->GetLastCommittedURL(), + web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin)); navigation->Commit(); } TEST_F(PageSpecificContentSettingsTest, Topics) { NavigateAndCommit(GURL("http://google.com")); - PageSpecificContentSettings* pscs = - PageSpecificContentSettings::GetForFrame(web_contents()->GetMainFrame()); + PageSpecificContentSettings* pscs = PageSpecificContentSettings::GetForFrame( + web_contents()->GetPrimaryMainFrame()); EXPECT_FALSE(pscs->HasAccessedTopics()); EXPECT_THAT(pscs->GetAccessedTopics(), testing::IsEmpty()); @@ -709,7 +717,8 @@ content::RenderFrameHost* CreateFencedFrame(const GURL& url) { content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For( + web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); std::unique_ptr<content::NavigationSimulator> navigation_simulator = content::NavigationSimulator::CreateRendererInitiated(
diff --git a/components/continuous_search/browser/search_result_extractor_client.cc b/components/continuous_search/browser/search_result_extractor_client.cc index 0bfa4518..3faa3f06 100644 --- a/components/continuous_search/browser/search_result_extractor_client.cc +++ b/components/continuous_search/browser/search_result_extractor_client.cc
@@ -34,8 +34,8 @@ content::WebContents* web_contents, const std::vector<mojom::ResultType>& result_types, RequestDataCallback callback) { - if (!web_contents || !web_contents->GetMainFrame() || - !web_contents->GetMainFrame()->GetRemoteAssociatedInterfaces()) { + if (!web_contents || !web_contents->GetPrimaryMainFrame() || + !web_contents->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces()) { std::move(callback).Run(SearchResultExtractorClientStatus::kWebContentsGone, mojom::CategoryResults::New()); return; @@ -50,8 +50,9 @@ } mojo::AssociatedRemote<mojom::SearchResultExtractor> extractor; - web_contents->GetMainFrame()->GetRemoteAssociatedInterfaces()->GetInterface( - extractor.BindNewEndpointAndPassReceiver()); + web_contents->GetPrimaryMainFrame() + ->GetRemoteAssociatedInterfaces() + ->GetInterface(extractor.BindNewEndpointAndPassReceiver()); mojom::SearchResultExtractor* extractor_ptr = extractor.get(); extractor_ptr->ExtractCurrentSearchResults(
diff --git a/components/continuous_search/browser/search_result_extractor_client_unittest.cc b/components/continuous_search/browser/search_result_extractor_client_unittest.cc index cb36b90..2b9ebd6 100644 --- a/components/continuous_search/browser/search_result_extractor_client_unittest.cc +++ b/components/continuous_search/browser/search_result_extractor_client_unittest.cc
@@ -74,7 +74,7 @@ // interface. void OverrideInterface(FakeSearchResultExtractor* extractor) { web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRemoteAssociatedInterfaces() ->OverrideBinderForTesting( mojom::SearchResultExtractor::Name_,
diff --git a/components/cronet/android/cronet_bidirectional_stream_adapter.cc b/components/cronet/android/cronet_bidirectional_stream_adapter.cc index 9065112..2204c84 100644 --- a/components/cronet/android/cronet_bidirectional_stream_adapter.cc +++ b/components/cronet/android/cronet_bidirectional_stream_adapter.cc
@@ -79,6 +79,7 @@ const base::android::JavaParamRef<jobject>& jbidi_stream, jlong jurl_request_context_adapter, jboolean jsend_request_headers_automatically, + jboolean jenable_metrics, jboolean jtraffic_stats_tag_set, jint jtraffic_stats_tag, jboolean jtraffic_stats_uid_set, @@ -91,9 +92,9 @@ CronetBidirectionalStreamAdapter* adapter = new CronetBidirectionalStreamAdapter( context_adapter, env, jbidi_stream, - jsend_request_headers_automatically, jtraffic_stats_tag_set, - jtraffic_stats_tag, jtraffic_stats_uid_set, jtraffic_stats_uid, - jnetwork_handle); + jsend_request_headers_automatically, jenable_metrics, + jtraffic_stats_tag_set, jtraffic_stats_tag, jtraffic_stats_uid_set, + jtraffic_stats_uid, jnetwork_handle); return reinterpret_cast<jlong>(adapter); } @@ -103,6 +104,7 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& jbidi_stream, bool send_request_headers_automatically, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -111,6 +113,7 @@ : context_(context), owner_(env, jbidi_stream), send_request_headers_automatically_(send_request_headers_automatically), + enable_metrics_(enable_metrics), traffic_stats_tag_set_(traffic_stats_tag_set), traffic_stats_tag_(traffic_stats_tag), traffic_stats_uid_set_(traffic_stats_uid_set), @@ -471,6 +474,9 @@ } void CronetBidirectionalStreamAdapter::MaybeReportMetrics() { + if (!enable_metrics_) + return; + if (!bidi_stream_) return; net::LoadTimingInfo load_timing_info;
diff --git a/components/cronet/android/cronet_bidirectional_stream_adapter.h b/components/cronet/android/cronet_bidirectional_stream_adapter.h index e90b48e..01d5dd3 100644 --- a/components/cronet/android/cronet_bidirectional_stream_adapter.h +++ b/components/cronet/android/cronet_bidirectional_stream_adapter.h
@@ -72,6 +72,7 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& jbidi_stream, bool jsend_request_headers_automatically, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -173,6 +174,8 @@ // Java object that owns this CronetBidirectionalStreamAdapter. base::android::ScopedJavaGlobalRef<jobject> owner_; const bool send_request_headers_automatically_; + // Whether metrics collection is enabled when |this| is created. + const bool enable_metrics_; // Whether |traffic_stats_tag_| should be applied. const bool traffic_stats_tag_set_; // TrafficStats tag to apply to URLRequest.
diff --git a/components/cronet/android/cronet_url_request_adapter.cc b/components/cronet/android/cronet_url_request_adapter.cc index 92a8296..03462e58 100644 --- a/components/cronet/android/cronet_url_request_adapter.cc +++ b/components/cronet/android/cronet_url_request_adapter.cc
@@ -66,6 +66,7 @@ jint jpriority, jboolean jdisable_cache, jboolean jdisable_connection_migration, + jboolean jenable_metrics, jboolean jtraffic_stats_tag_set, jint jtraffic_stats_tag, jboolean jtraffic_stats_uid_set, @@ -84,8 +85,8 @@ CronetURLRequestAdapter* adapter = new CronetURLRequestAdapter( context_adapter, env, jurl_request, url, static_cast<net::RequestPriority>(jpriority), jdisable_cache, - jdisable_connection_migration, jtraffic_stats_tag_set, jtraffic_stats_tag, - jtraffic_stats_uid_set, jtraffic_stats_uid, + jdisable_connection_migration, jenable_metrics, jtraffic_stats_tag_set, + jtraffic_stats_tag, jtraffic_stats_uid_set, jtraffic_stats_uid, static_cast<net::Idempotency>(jidempotency), jnetwork_handle); return reinterpret_cast<jlong>(adapter); @@ -99,6 +100,7 @@ net::RequestPriority priority, jboolean jdisable_cache, jboolean jdisable_connection_migration, + jboolean jenable_metrics, jboolean jtraffic_stats_tag_set, jint jtraffic_stats_tag, jboolean jtraffic_stats_uid_set, @@ -112,6 +114,7 @@ priority, jdisable_cache == JNI_TRUE, jdisable_connection_migration == JNI_TRUE, + jenable_metrics == JNI_TRUE, jtraffic_stats_tag_set == JNI_TRUE, jtraffic_stats_tag, jtraffic_stats_uid_set == JNI_TRUE,
diff --git a/components/cronet/android/cronet_url_request_adapter.h b/components/cronet/android/cronet_url_request_adapter.h index f0157a68..0c9a13df 100644 --- a/components/cronet/android/cronet_url_request_adapter.h +++ b/components/cronet/android/cronet_url_request_adapter.h
@@ -50,6 +50,7 @@ net::RequestPriority priority, jboolean jdisable_cache, jboolean jdisable_connection_migration, + jboolean jenable_metrics, jboolean jtraffic_stats_tag_set, jint jtraffic_stats_tag, jboolean jtraffic_stats_uid_set,
diff --git a/components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java b/components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java index 8af6b26..248d618 100644 --- a/components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java +++ b/components/cronet/android/java/src/org/chromium/net/impl/CronetBidirectionalStream.java
@@ -280,8 +280,9 @@ mNativeStream = CronetBidirectionalStreamJni.get().createBidirectionalStream( CronetBidirectionalStream.this, mRequestContext.getUrlRequestContextAdapter(), - !mDelayRequestHeadersUntilFirstFlush, mTrafficStatsTagSet, mTrafficStatsTag, - mTrafficStatsUidSet, mTrafficStatsUid, mNetworkHandle); + !mDelayRequestHeadersUntilFirstFlush, + mRequestContext.hasRequestFinishedListener(), mTrafficStatsTagSet, + mTrafficStatsTag, mTrafficStatsUidSet, mTrafficStatsUid, mNetworkHandle); mRequestContext.onRequestStarted(); // Non-zero startResult means an argument error. int startResult = CronetBidirectionalStreamJni.get().start(mNativeStream, @@ -836,8 +837,8 @@ // Native methods are implemented in cronet_bidirectional_stream_adapter.cc. long createBidirectionalStream(CronetBidirectionalStream caller, long urlRequestContextAdapter, boolean sendRequestHeadersAutomatically, - boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet, - int trafficStatsUid, long networkHandle); + boolean enableMetricsCollection, boolean trafficStatsTagSet, int trafficStatsTag, + boolean trafficStatsUidSet, int trafficStatsUid, long networkHandle); @NativeClassQualifiedName("CronetBidirectionalStreamAdapter") int start(long nativePtr, CronetBidirectionalStream caller, String url, int priority,
diff --git a/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java b/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java index 3dfbdec..20473d1 100644 --- a/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java +++ b/components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java
@@ -225,6 +225,8 @@ mUrlRequestAdapter = CronetUrlRequestJni.get().createRequestAdapter( CronetUrlRequest.this, mRequestContext.getUrlRequestContextAdapter(), mInitialUrl, mPriority, mDisableCache, mDisableConnectionMigration, + mRequestContext.hasRequestFinishedListener() + || mRequestFinishedListener != null, mTrafficStatsTagSet, mTrafficStatsTag, mTrafficStatsUidSet, mTrafficStatsUid, mIdempotency, mNetworkHandle); mRequestContext.onRequestStarted(); @@ -857,8 +859,9 @@ interface Natives { long createRequestAdapter(CronetUrlRequest caller, long urlRequestContextAdapter, String url, int priority, boolean disableCache, boolean disableConnectionMigration, - boolean trafficStatsTagSet, int trafficStatsTag, boolean trafficStatsUidSet, - int trafficStatsUid, int idempotency, long networkHandle); + boolean enableMetrics, boolean trafficStatsTagSet, int trafficStatsTag, + boolean trafficStatsUidSet, int trafficStatsUid, int idempotency, + long networkHandle); @NativeClassQualifiedName("CronetURLRequestAdapter") boolean setHttpMethod(long nativePtr, CronetUrlRequest caller, String method);
diff --git a/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamTest.java b/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamTest.java index 8451ae7..eb5505c 100644 --- a/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamTest.java +++ b/components/cronet/android/test/javatests/src/org/chromium/net/BidirectionalStreamTest.java
@@ -1151,7 +1151,6 @@ @SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet - @DisabledTest(message = "crbug.com/1334040") public void testSimpleGetBufferUpdates() throws Exception { TestBidirectionalStreamCallback callback = new TestBidirectionalStreamCallback(); callback.setAutoAdvance(false);
diff --git a/components/cronet/cronet_url_request.cc b/components/cronet/cronet_url_request.cc index 762c22e5..3a8c6211 100644 --- a/components/cronet/cronet_url_request.cc +++ b/components/cronet/cronet_url_request.cc
@@ -63,6 +63,7 @@ net::RequestPriority priority, bool disable_cache, bool disable_connection_migration, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -76,6 +77,7 @@ CalculateLoadFlags(context->default_load_flags(), disable_cache, disable_connection_migration), + enable_metrics, traffic_stats_tag_set, traffic_stats_tag, traffic_stats_uid_set, @@ -178,6 +180,7 @@ const GURL& url, net::RequestPriority priority, int load_flags, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -190,6 +193,7 @@ initial_load_flags_(load_flags), received_byte_count_from_redirects_(0l), error_reported_(false), + enable_metrics_(enable_metrics), metrics_reported_(false), traffic_stats_tag_set_(traffic_stats_tag_set), traffic_stats_tag_(traffic_stats_tag), @@ -395,7 +399,7 @@ // be a native URLRequest. In this case, the caller gets the exception // immediately, and the onFailed callback isn't called, so don't report // metrics either. - if (metrics_reported_ || !url_request_) { + if (!enable_metrics_ || metrics_reported_ || !url_request_) { return; } metrics_reported_ = true;
diff --git a/components/cronet/cronet_url_request.h b/components/cronet/cronet_url_request.h index 74e2b91f..fad98e7 100644 --- a/components/cronet/cronet_url_request.h +++ b/components/cronet/cronet_url_request.h
@@ -110,7 +110,8 @@ // methods will be invoked. virtual void OnDestroyed() = 0; - // Invoked right before request is destroyed to report collected metrics. + // Invoked right before request is destroyed to report collected metrics if + // |enable_metrics| is true in CronetURLRequest::CronetURLRequest(). virtual void OnMetricsCollected(const base::Time& request_start_time, const base::TimeTicks& request_start, const base::TimeTicks& dns_start, @@ -145,6 +146,7 @@ net::RequestPriority priority, bool disable_cache, bool disable_connection_migration, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -208,6 +210,7 @@ const GURL& url, net::RequestPriority priority, int load_flags, + bool enable_metrics, bool traffic_stats_tag_set, int32_t traffic_stats_tag, bool traffic_stats_uid_set, @@ -281,6 +284,8 @@ // OnSSLCertificateError(). bool error_reported_; + // Whether detailed metrics should be collected and reported. + const bool enable_metrics_; // Whether metrics have been reported. bool metrics_reported_;
diff --git a/components/cronet/native/url_request.cc b/components/cronet/native/url_request.cc index 02b1d5b..58bc48b 100644 --- a/components/cronet/native/url_request.cc +++ b/components/cronet/native/url_request.cc
@@ -378,6 +378,8 @@ engine_->cronet_url_request_context(), std::move(network_tasks), GURL(url), ConvertRequestPriority(params->priority), params->disable_cache, true /* params->disableConnectionMigration */, + request_finished_listener_ != nullptr || + engine_->HasRequestFinishedListener() /* params->enableMetrics */, // TODO(pauljensen): Consider exposing TrafficStats API via C++ API. false /* traffic_stats_tag_set */, 0 /* traffic_stats_tag */, false /* traffic_stats_uid_set */, 0 /* traffic_stats_uid */,
diff --git a/components/custom_handlers/protocol_handler_registry_browsertest.cc b/components/custom_handlers/protocol_handler_registry_browsertest.cc index 5d3a0025..1a92438b 100644 --- a/components/custom_handlers/protocol_handler_registry_browsertest.cc +++ b/components/custom_handlers/protocol_handler_registry_browsertest.cc
@@ -157,7 +157,7 @@ // Create a FencedFrame. content::RenderFrameHost* fenced_frame_host = fenced_frame_test_helper().CreateFencedFrame( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), embedded_test_server()->GetURL("/fenced_frames/title1.html")); ASSERT_TRUE(fenced_frame_host);
diff --git a/components/desks_storage/BUILD.gn b/components/desks_storage/BUILD.gn index 5e9baf1e..53ee494 100644 --- a/components/desks_storage/BUILD.gn +++ b/components/desks_storage/BUILD.gn
@@ -49,6 +49,10 @@ "core/desk_template_conversion_unittests.cc", "core/desk_template_util_unittests.cc", "core/local_desks_data_manager_unittests.cc", + "core/saved_desk_builder.cc", + "core/saved_desk_builder.h", + "core/saved_desk_test_util.cc", + "core/saved_desk_test_util.h", ] deps = [ ":desks_storage",
diff --git a/components/desks_storage/core/desk_sync_bridge.cc b/components/desks_storage/core/desk_sync_bridge.cc index 1b52e34..23483ac02 100644 --- a/components/desks_storage/core/desk_sync_bridge.cc +++ b/components/desks_storage/core/desk_sync_bridge.cc
@@ -611,10 +611,94 @@ } // Fill `out_app` with `app_restore_data`. -void FillApp(const std::string& app_id, +// Return `false` if app type is unsupported. +bool FillApp(const std::string& app_id, const apps::AppType app_type, const app_restore::AppRestoreData* app_restore_data, WorkspaceDeskSpecifics_App* out_app) { + // See definition in components/services/app_service/public/cpp/app_types.h + switch (app_type) { + case apps::AppType::kWeb: + case apps::AppType::kSystemWeb: { + // System Web Apps. + // kSystemWeb is returned for System Web Apps in Lacros-primary + // configuration. These can be persisted and launched the same way as + // Chrome Apps. + ChromeApp* chrome_app_window = + out_app->mutable_app()->mutable_chrome_app(); + chrome_app_window->set_app_id(app_id); + FillAppWithLaunchContainerAndOpenDisposition(app_restore_data, out_app); + break; + } + + case apps::AppType::kChromeApp: { + // Ash Chrome browser OR PWA OR Chrome App hosted in Ash Chrome. + if (app_constants::kChromeAppId == app_id) { + // This window is either a browser window or a PWA window. + // Both cases are persisted as "browser app" since they are launched the + // same way. PWA window will have field `app_name` and + // `app_type_browser` fields set. FillAppWithAppNameAndTitle has + // persisted `app_name` field. FillBrowserAppWindow will persist + // `app_type_browser` field. + BrowserAppWindow* browser_app_window = + out_app->mutable_app()->mutable_browser_app_window(); + FillBrowserAppWindow(app_restore_data, browser_app_window); + } else { + // Chrome App + ChromeApp* chrome_app_window = + out_app->mutable_app()->mutable_chrome_app(); + chrome_app_window->set_app_id(app_id); + FillAppWithLaunchContainerAndOpenDisposition(app_restore_data, out_app); + } + break; + } + + case apps::AppType::kStandaloneBrowser: { + if (app_constants::kLacrosAppId == app_id) { + // Lacros Chrome browser window or PWA hosted in Lacros Chrome. + BrowserAppWindow* browser_app_window = + out_app->mutable_app()->mutable_browser_app_window(); + FillBrowserAppWindow(app_restore_data, browser_app_window); + } else { + // Chrome app running in Lacros should have + // AppType::kStandaloneBrowserChromeApp and never reach here. + NOTREACHED(); + // Ignore this app type. + return false; + } + + break; + } + + case apps::AppType::kStandaloneBrowserChromeApp: { + // Chrome App hosted in Lacros. + ChromeApp* chrome_app_window = + out_app->mutable_app()->mutable_chrome_app(); + chrome_app_window->set_app_id(app_id); + FillAppWithLaunchContainerAndOpenDisposition(app_restore_data, out_app); + break; + } + + case apps::AppType::kArc: { + ArcApp* arc_app = out_app->mutable_app()->mutable_arc_app(); + arc_app->set_app_id(app_id); + FillArcApp(app_restore_data, arc_app); + break; + } + + case apps::AppType::kBuiltIn: + case apps::AppType::kCrostini: + case apps::AppType::kPluginVm: + case apps::AppType::kUnknown: + case apps::AppType::kMacOs: + case apps::AppType::kRemote: + case apps::AppType::kBorealis: + case apps::AppType::kExtension: + case apps::AppType::kStandaloneBrowserExtension: + // Unsupported app types will be ignored. + return false; + } + FillAppWithWindowInfo(app_restore_data->GetWindowInfo().get(), out_app); // AppRestoreData.GetWindowInfo does not include `display_id` in the returned @@ -626,44 +710,7 @@ // fields. FillAppWithAppNameAndTitle(app_restore_data, out_app); - // See definition components/services/app_service/public/mojom/types.mojom - switch (app_type) { - case apps::AppType::kWeb: - case apps::AppType::kStandaloneBrowser: { - if (app_constants::kChromeAppId == app_id || - app_constants::kLacrosAppId == app_id) { - // Chrome or Lacros Browser Window. - BrowserAppWindow* browser_app_window = - out_app->mutable_app()->mutable_browser_app_window(); - FillBrowserAppWindow(app_restore_data, browser_app_window); - } else { - // PWA app. - ProgressiveWebApp* pwa_window = - out_app->mutable_app()->mutable_progress_web_app(); - pwa_window->set_app_id(app_id); - FillAppWithLaunchContainerAndOpenDisposition(app_restore_data, out_app); - } - break; - } - case apps::AppType::kChromeApp: { - // Chrome extension backed app, Chrome Apps - ChromeApp* chrome_app_window = - out_app->mutable_app()->mutable_chrome_app(); - chrome_app_window->set_app_id(app_id); - FillAppWithLaunchContainerAndOpenDisposition(app_restore_data, out_app); - break; - } - case apps::AppType::kArc: { - ArcApp* arc_app = out_app->mutable_app()->mutable_arc_app(); - arc_app->set_app_id(app_id); - FillArcApp(app_restore_data, arc_app); - break; - } - default: { - // Unhandled app type. - break; - } - } + return true; } void FillArcExtraInfoFromProto(const ArcApp& app, @@ -774,16 +821,16 @@ const int window_id = window_id_to_launch_info.first; const app_restore::AppRestoreData* app_restore_data = window_id_to_launch_info.second.get(); - // The apps cache returns kChromeApp for browser windows, therefore we - // short circuit the cache retrieval if we get the browser ID. - const auto app_type = app_id == app_constants::kChromeAppId - ? apps::AppType::kWeb - : apps_cache->GetAppType(app_id); + + const auto app_type = apps_cache->GetAppType(app_id); WorkspaceDeskSpecifics_App* app = out_entry_proto->mutable_desk()->add_apps(); app->set_window_id(window_id); - FillApp(app_id, app_type, app_restore_data, app); + if (!FillApp(app_id, app_type, app_restore_data, app)) { + // Unsupported app type, remove this app entry. + out_entry_proto->mutable_desk()->mutable_apps()->RemoveLast(); + } } } }
diff --git a/components/desks_storage/core/desk_sync_bridge_unittest.cc b/components/desks_storage/core/desk_sync_bridge_unittest.cc index 626f8cf..5d984a5a 100644 --- a/components/desks_storage/core/desk_sync_bridge_unittest.cc +++ b/components/desks_storage/core/desk_sync_bridge_unittest.cc
@@ -25,6 +25,7 @@ #include "components/desks_storage/core/desk_model_observer.h" #include "components/desks_storage/core/desk_template_conversion.h" #include "components/desks_storage/core/desk_template_util.h" +#include "components/desks_storage/core/saved_desk_builder.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/features.h" #include "components/sync/model/entity_change.h" @@ -91,6 +92,9 @@ constexpr char kTestAppNameFormat[] = "_some_prefix_%s"; constexpr int kDefaultTemplateIndex = 1; constexpr int kBrowserWindowId = 1555; +constexpr int kPwaWindowId = 1666; +constexpr int kChromeAppWindowId = 1777; +constexpr int kUnsupportedAppWindowId = 1888; constexpr char kTestTabGroupName[] = "test_tab_group"; constexpr char kTestTabGroupNameFormat[] = "test_tab_group_%zu"; @@ -99,6 +103,7 @@ constexpr int kExampleDeskArcAppIndex = 1; constexpr int kExampleDeskChromeAppIndex = 2; constexpr int kExampleDeskProgressiveWebAppIndex = 3; +constexpr int kExampleDeskSystemWebAppIndex = 4; const base::GUID kTestUuid1 = base::GUID::ParseCaseInsensitive(base::StringPrintf(kUuidFormat, 1)); @@ -199,8 +204,7 @@ } void FillExampleProgressiveWebAppWindow(WorkspaceDeskSpecifics_App* app) { - ProgressiveWebApp* app_window = - app->mutable_app()->mutable_progress_web_app(); + ChromeApp* app_window = app->mutable_app()->mutable_chrome_app(); app_window->set_app_id(kTestPwaAppId); WindowBound* window_bound = app->mutable_window_bound(); @@ -222,6 +226,30 @@ app->set_window_id(2555); } +void FillExampleSystemWebAppWindow(WorkspaceDeskSpecifics_App* app) { + ChromeApp* app_window = app->mutable_app()->mutable_chrome_app(); + app_window->set_app_id(desk_template_util::kTestSwaAppId); + + WindowBound* window_bound = app->mutable_window_bound(); + window_bound->set_left(220); + window_bound->set_top(230); + window_bound->set_width(2340); + window_bound->set_height(2450); + app->set_window_state( + WindowState::WorkspaceDeskSpecifics_WindowState_MINIMIZED); + app->set_pre_minimized_window_state( + WindowState::WorkspaceDeskSpecifics_WindowState_FULLSCREEN); + app->set_container( + sync_pb::WorkspaceDeskSpecifics_LaunchContainer_LAUNCH_CONTAINER_WINDOW); + app->set_disposition( + sync_pb::WorkspaceDeskSpecifics_WindowOpenDisposition_NEW_WINDOW); + app->set_app_name(base::StringPrintf(kTestAppNameFormat, + desk_template_util::kTestSwaAppId)); + app->set_display_id(99887766l); + app->set_z_index(234); + app->set_window_id(2556); +} + void FillExampleChromeAppWindow(WorkspaceDeskSpecifics_App* app) { ChromeApp* app_window = app->mutable_app()->mutable_chrome_app(); app_window->set_app_id(kTestChromeAppId); @@ -298,6 +326,7 @@ FillExampleArcAppWindow(desk->add_apps()); FillExampleChromeAppWindow(desk->add_apps()); FillExampleProgressiveWebAppWindow(desk->add_apps()); + FillExampleSystemWebAppWindow(desk->add_apps()); return specifics; } @@ -329,6 +358,7 @@ FillExampleArcAppWindow(desk->add_apps()); FillExampleChromeAppWindow(desk->add_apps()); FillExampleProgressiveWebAppWindow(desk->add_apps()); + FillExampleSystemWebAppWindow(desk->add_apps()); return specifics; } @@ -348,29 +378,6 @@ SyncDeskType::WorkspaceDeskSpecifics_DeskType_UNKNOWN_TYPE); } -std::unique_ptr<ash::DeskTemplate> CreateTemplateWithBrowserFromScratch( - int template_index, - const base::Time& created_time) { - const std::string template_uuid = - base::StringPrintf(kUuidFormat, template_index); - const std::string template_name = - base::StringPrintf(kNameFormat, template_index); - auto desk_template = std::make_unique<ash::DeskTemplate>( - template_uuid, DeskTemplateSource::kUser, template_name, created_time, - DeskTemplateType::kTemplate); - - auto restore_data = std::make_unique<app_restore::RestoreData>(); - auto browser_info = std::make_unique<app_restore::AppLaunchInfo>( - app_constants::kChromeAppId, kBrowserWindowId); - browser_info->urls = {GURL(base::StringPrintf(kTestUrlFormat, 1)), - GURL(base::StringPrintf(kTestUrlFormat, 2))}; - - restore_data->AddAppLaunchInfo(std::move(browser_info)); - desk_template->set_desk_restore_data(std::move(restore_data)); - - return desk_template; -} - WorkspaceDeskSpecifics CreateBrowserTemplateExpectedValue( int template_index, const base::Time& created_time) { @@ -397,6 +404,56 @@ return expected_desk_specifics; } +WorkspaceDeskSpecifics CreatePwaTemplateExpectedValue( + int template_index, + const base::Time& created_time) { + WorkspaceDeskSpecifics expected_desk_specifics; + expected_desk_specifics.set_uuid( + base::StringPrintf(kUuidFormat, template_index)); + expected_desk_specifics.set_name( + base::StringPrintf(kNameFormat, template_index)); + expected_desk_specifics.set_created_time_windows_epoch_micros( + created_time.ToDeltaSinceWindowsEpoch().InMicroseconds()); + expected_desk_specifics.set_desk_type( + SyncDeskType::WorkspaceDeskSpecifics_DeskType_TEMPLATE); + Desk* expected_desk = expected_desk_specifics.mutable_desk(); + WorkspaceDeskSpecifics_App* app = expected_desk->add_apps(); + app->set_window_id(kPwaWindowId); + BrowserAppWindow* browser_window = + app->mutable_app()->mutable_browser_app_window(); + + BrowserAppTab* first_tab = browser_window->add_tabs(); + first_tab->set_url(GURL(base::StringPrintf(kTestUrlFormat, 1)).spec()); + + browser_window->set_show_as_app(true); + + return expected_desk_specifics; +} + +WorkspaceDeskSpecifics CreateChromeAppTemplateExpectedValue( + int template_index, + const base::Time& created_time, + int window_id, + const std::string& app_id) { + WorkspaceDeskSpecifics expected_desk_specifics; + expected_desk_specifics.set_uuid( + base::StringPrintf(kUuidFormat, template_index)); + expected_desk_specifics.set_name( + base::StringPrintf(kNameFormat, template_index)); + expected_desk_specifics.set_created_time_windows_epoch_micros( + created_time.ToDeltaSinceWindowsEpoch().InMicroseconds()); + expected_desk_specifics.set_desk_type( + SyncDeskType::WorkspaceDeskSpecifics_DeskType_TEMPLATE); + Desk* expected_desk = expected_desk_specifics.mutable_desk(); + WorkspaceDeskSpecifics_App* app = expected_desk->add_apps(); + app->set_window_id(window_id); + + ChromeApp* app_window = app->mutable_app()->mutable_chrome_app(); + app_window->set_app_id(app_id); + + return expected_desk_specifics; +} + ModelTypeState StateWithEncryption(const std::string& encryption_key_name) { ModelTypeState state; state.set_encryption_key_name(encryption_key_name); @@ -649,6 +706,9 @@ WorkspaceDeskSpecifics converted_desk_proto = bridge()->ToSyncProto(desk_template.get()); + std::unique_ptr<DeskTemplate> converted_desk_template = + DeskSyncBridge::FromSyncProto(converted_desk_proto); + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(desk_proto)); } @@ -696,6 +756,9 @@ desk_proto.mutable_desk() ->mutable_apps(kExampleDeskProgressiveWebAppIndex) ->set_app_name("app name 4"); + desk_proto.mutable_desk() + ->mutable_apps(kExampleDeskSystemWebAppIndex) + ->set_app_name("app name 5"); std::unique_ptr<DeskTemplate> desk_template = DeskSyncBridge::FromSyncProto(desk_proto); @@ -827,20 +890,147 @@ } // Tests that URLs are saved properly when converting a DeskTemplate -// to its protobuf form. -TEST_F(DeskSyncBridgeTest, EnsureBrowserWindowsSavedProperly) { +// to its Protobuf form. +TEST_F(DeskSyncBridgeTest, EnsureAshBrowserWindowsSavedProperly) { CreateBridge(); - base::Time created_time = base::Time::Now(); // Uses a different method to instantiate the template that doesn't rely // on the assumption that the template is instantiated from a proto, but // rather is captured and saved for the first time. std::unique_ptr<DeskTemplate> desk_template = - CreateTemplateWithBrowserFromScratch(kDefaultTemplateIndex, created_time); + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddAshBrowserAppWindow(kBrowserWindowId, + {GURL(base::StringPrintf(kTestUrlFormat, 1)), + GURL(base::StringPrintf(kTestUrlFormat, 2))}) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = bridge()->ToSyncProto(desk_template.get()); WorkspaceDeskSpecifics expected_desk_proto = - CreateBrowserTemplateExpectedValue(kDefaultTemplateIndex, created_time); + CreateBrowserTemplateExpectedValue(kDefaultTemplateIndex, + desk_template->created_time()); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsureLacrosBrowserWindowsCanBeSavedProperly) { + CreateBridge(); + + // Uses a different method to instantiate the template that doesn't rely + // on the assumption that the template is instantiated from a proto, but + // rather is captured and saved for the first time. + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddLacrosBrowserAppWindow( + kBrowserWindowId, {GURL(base::StringPrintf(kTestUrlFormat, 1)), + GURL(base::StringPrintf(kTestUrlFormat, 2))}) + .Build(); + + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = + CreateBrowserTemplateExpectedValue(kDefaultTemplateIndex, + desk_template->created_time()); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsurePwaInAshChromeCanBeSavedProperly) { + CreateBridge(); + + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddAshPwaAppWindow(kPwaWindowId, + base::StringPrintf(kTestUrlFormat, 1)) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = CreatePwaTemplateExpectedValue( + kDefaultTemplateIndex, desk_template->created_time()); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsurePwaInLacrosChromeCanBeSavedProperly) { + CreateBridge(); + + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddLacrosPwaAppWindow(kPwaWindowId, + base::StringPrintf(kTestUrlFormat, 1)) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = CreatePwaTemplateExpectedValue( + kDefaultTemplateIndex, desk_template->created_time()); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsureChromeAppCanBeSavedProperly) { + CreateBridge(); + + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddChromeAppWindow(kChromeAppWindowId, kTestChromeAppId) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = + CreateChromeAppTemplateExpectedValue( + kDefaultTemplateIndex, desk_template->created_time(), + kChromeAppWindowId, kTestChromeAppId); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsureLacrosChromeAppCanBeSavedProperly) { + CreateBridge(); + + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddChromeAppWindow(kChromeAppWindowId, + desk_template_util::kTestLacrosChromeAppId) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = + CreateChromeAppTemplateExpectedValue( + kDefaultTemplateIndex, desk_template->created_time(), + kChromeAppWindowId, desk_template_util::kTestLacrosChromeAppId); + + EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); +} + +TEST_F(DeskSyncBridgeTest, EnsureUnsupportedAppCanBeIgnored) { + CreateBridge(); + + std::unique_ptr<DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(base::StringPrintf(kUuidFormat, kDefaultTemplateIndex)) + .SetName(base::StringPrintf(kNameFormat, kDefaultTemplateIndex)) + .AddChromeAppWindow(kChromeAppWindowId, kTestChromeAppId) + .AddGenericAppWindow(kUnsupportedAppWindowId, + desk_template_util::kTestUnsupportedAppId) + .Build(); + WorkspaceDeskSpecifics converted_desk_proto = + bridge()->ToSyncProto(desk_template.get()); + WorkspaceDeskSpecifics expected_desk_proto = + CreateChromeAppTemplateExpectedValue( + kDefaultTemplateIndex, desk_template->created_time(), + kChromeAppWindowId, kTestChromeAppId); EXPECT_THAT(converted_desk_proto, EqualsSpecifics(expected_desk_proto)); }
diff --git a/components/desks_storage/core/desk_template_conversion.cc b/components/desks_storage/core/desk_template_conversion.cc index 264e901..7802ca4 100644 --- a/components/desks_storage/core/desk_template_conversion.cc +++ b/components/desks_storage/core/desk_template_conversion.cc
@@ -24,6 +24,10 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/geometry/rect.h" +#if !BUILDFLAG(IS_CHROMEOS_LACROS) +#include "chromeos/crosapi/cpp/lacros_startup_state.h" // nogncheck +#endif // !BUILDFLAG(IS_CHROMEOS_LACROS) + namespace { using SyncWindowOpenDisposition = @@ -37,10 +41,11 @@ constexpr char kApps[] = "apps"; constexpr char kAppName[] = "app_name"; constexpr char kAppType[] = "app_type"; +constexpr char kAppTypeArc[] = "ARC"; constexpr char kAppTypeBrowser[] = "BROWSER"; constexpr char kAppTypeChrome[] = "CHROME_APP"; constexpr char kAppTypeProgressiveWeb[] = "PWA"; -constexpr char kAppTypeArc[] = "ARC"; +constexpr char kAppTypeUnsupported[] = "UNSUPPORTED"; constexpr char kBoundsInRoot[] = "bounds_in_root"; constexpr char kCreatedTime[] = "created_time_usec"; constexpr char kDesk[] = "desk"; @@ -191,8 +196,20 @@ return std::string(); // App Type must be specified. if (app_type == kAppTypeBrowser) { + // Return the primary browser's known app ID. + const bool is_lacros = +#if BUILDFLAG(IS_CHROMEOS_LACROS) + true; +#else + // Note that this will launch the browser as lacros if it is enabled, + // even if it was saved as a non-lacros window (and vice-versa). + crosapi::lacros_startup_state::IsLacrosEnabled() && + crosapi::lacros_startup_state::IsLacrosPrimaryEnabled(); +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) + // Browser app has a known app ID. - return std::string(app_constants::kChromeAppId); + return std::string(is_lacros ? app_constants::kLacrosAppId + : app_constants::kChromeAppId); } else if (app_type == kAppTypeChrome || app_type == kAppTypeProgressiveWeb || app_type == kAppTypeArc) { // Read the provided app ID @@ -762,22 +779,45 @@ std::string GetAppTypeForJson(apps::AppRegistryCache* apps_cache, const std::string& app_id) { - const auto app_type = app_id == app_constants::kChromeAppId - ? apps::AppType::kWeb - : apps_cache->GetAppType(app_id); + const auto app_type = apps_cache->GetAppType(app_id); + // This switch should follow the same structure as DeskSyncBridge#FillApp. switch (app_type) { case apps::AppType::kWeb: - return app_id == app_constants::kChromeAppId ? kAppTypeBrowser - : kAppTypeProgressiveWeb; - case apps::AppType::kChromeApp: + case apps::AppType::kSystemWeb: return kAppTypeChrome; + + case apps::AppType::kChromeApp: + if (app_id == app_constants::kChromeAppId) { + return kAppTypeBrowser; + } else { + return kAppTypeChrome; + } + + case apps::AppType::kStandaloneBrowser: + if (app_id == app_constants::kLacrosAppId) { + return kAppTypeBrowser; + } else { + return kAppTypeUnsupported; + } + case apps::AppType::kArc: return kAppTypeArc; - default: - // Default to browser if unsupported, this shouldn't be captured and - // there is no error type in the proto definition. - return kAppTypeBrowser; + + case apps::AppType::kStandaloneBrowserChromeApp: + return kAppTypeChrome; + + case apps::AppType::kBuiltIn: + case apps::AppType::kCrostini: + case apps::AppType::kPluginVm: + case apps::AppType::kUnknown: + case apps::AppType::kMacOs: + case apps::AppType::kRemote: + case apps::AppType::kBorealis: + case apps::AppType::kExtension: + case apps::AppType::kStandaloneBrowserExtension: + // Default to unsupported. This app should not be captured. + return kAppTypeUnsupported; } } @@ -785,6 +825,12 @@ const int window_id, const app_restore::AppRestoreData* app, apps::AppRegistryCache* apps_cache) { + std::string app_type = GetAppTypeForJson(apps_cache, app_id); + + if (kAppTypeUnsupported == app_type) { + return base::Value(base::Value::Type::NONE); + } + base::Value app_data = base::Value(base::Value::Type::DICTIONARY); if (app->current_bounds.has_value()) { @@ -822,8 +868,6 @@ if (app->activation_index.has_value()) app_data.SetKey(kZIndex, base::Value(app->activation_index.value())); - std::string app_type = GetAppTypeForJson(apps_cache, app_id); - app_data.SetKey(kAppType, base::Value(app_type)); if (app->urls.has_value()) @@ -898,8 +942,12 @@ for (const auto& app : restore_data->app_id_to_launch_list()) { for (const auto& window : app.second) { - desk_data.Append(ConvertWindowToDeskApp(app.first, window.first, - window.second.get(), apps_cache)); + auto app_data = ConvertWindowToDeskApp(app.first, window.first, + window.second.get(), apps_cache); + if (app_data.is_none()) + continue; + + desk_data.Append(std::move(app_data)); } }
diff --git a/components/desks_storage/core/desk_template_conversion_unittests.cc b/components/desks_storage/core/desk_template_conversion_unittests.cc index 2274f64..4bb1ce7b 100644 --- a/components/desks_storage/core/desk_template_conversion_unittests.cc +++ b/components/desks_storage/core/desk_template_conversion_unittests.cc
@@ -9,6 +9,7 @@ #include "ash/public/cpp/desk_template.h" #include "base/guid.h" #include "base/json/json_reader.h" +#include "base/json/values_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" #include "base/test/task_environment.h" @@ -19,6 +20,8 @@ #include "components/app_restore/app_restore_data.h" #include "components/app_restore/window_info.h" #include "components/desks_storage/core/desk_template_util.h" +#include "components/desks_storage/core/saved_desk_builder.h" +#include "components/desks_storage/core/saved_desk_test_util.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_registry_cache_wrapper.h" #include "components/services/app_service/public/cpp/app_types.h" @@ -29,8 +32,12 @@ namespace { +const int32_t kTestWindowId = 1234567; const std::string kEmptyJson = "{}"; const std::string kTestUuidBrowser = "040b6112-67f2-4d3c-8ba8-53a117272eba"; +constexpr int kBrowserWindowId = 1555; +const std::string kBrowserUrl1 = "https://example.com/"; +const std::string kBrowserUrl2 = "https://example.com/2"; const std::string kTestUuidChromeAndProgressive = "7f4b7ff0-970a-41bb-aa91-f6c3e2724207"; const std::string kBrowserTemplateName = "BrowserTest"; @@ -44,7 +51,9 @@ "\"1633535632\",\"desk_type\":\"TEMPLATE\",\"desk\":{\"apps\":[{\"window_" "bound\":{\"left\":0,\"top\":1,\"height\":121,\"width\":120},\"window_" "state\":\"NORMAL\",\"z_index\":1,\"app_type\":\"BROWSER\",\"tabs\":[{" - "\"url\":\"https://example.com/\"},{\"url\":\"https://" + "\"url\":\"" + + kBrowserUrl1 + + "\"},{\"url\":\"https://" "example.com/" "2\"}],\"tab_groups\":[{\"first_" "index\":1,\"last_index\":2,\"title\":\"sample_tab_" @@ -66,7 +75,8 @@ "\",\"window_id\":0,\"display_id\":\"100\",\"event_flag\":0,\"pre_" "minimized_window_state\":\"NORMAL\", \"snap_percent\":75},{\"window_" "bound\":{\"left\":0,\"top\":0,\"height\":120,\"width\":120},\"window_" - "state\":\"NORMAL\",\"z_index\":1,\"app_type\":\"PWA\",\"app_id\":\"" + + "state\":\"NORMAL\",\"z_index\":1,\"app_type\":\"CHROME_APP\",\"app_id\":" + "\"" + kProgressiveAppid + "\",\"window_id\":1,\"display_id\":" "\"100\",\"event_flag\":0,\"pre_minimized_window_state\":\"NORMAL\"}]}}"; @@ -77,9 +87,9 @@ "\"1633535632\",\"desk\":{\"apps\":[{\"window_" "bound\":{\"left\":0,\"top\":1,\"height\":121,\"width\":120},\"window_" "state\":\"NORMAL\",\"z_index\":1,\"app_type\":\"BROWSER\",\"tabs\":[{" - "\"url\":\"https://example.com/\"},{\"url\":\"https://" - "example.com/" - "2\"}],\"tab_groups\":[{\"first_" + "\"url\":\"" + + kBrowserUrl1 + "\"},{\"url\":\"" + kBrowserUrl1 + + "\"}],\"tab_groups\":[{\"first_" "index\":1,\"last_index\":2,\"title\":\"sample_tab_" "group\",\"color\":\"GREY\",\"is_collapsed\":false}],\"active_tab_index\":" "1,\"window_id\":0," @@ -159,8 +169,8 @@ // it // https://osscs.corp.google.com/chromium/chromium/src/+/main:components/app_restore/app_restore_data.cc EXPECT_TRUE(ali->urls.has_value()); - EXPECT_EQ(ali->urls.value()[0].spec(), "https://example.com/"); - EXPECT_EQ(ali->urls.value()[1].spec(), "https://example.com/2"); + EXPECT_EQ(ali->urls.value()[0].spec(), kBrowserUrl1); + EXPECT_EQ(ali->urls.value()[1].spec(), kBrowserUrl2); EXPECT_TRUE(ali->tab_group_infos.has_value()); EXPECT_EQ(ali->tab_group_infos.value()[0], MakeSampleTabGroup()); EXPECT_TRUE(wi->window_state_type.has_value()); @@ -314,6 +324,33 @@ EXPECT_EQ(parsed_json.value, desk_template_value); } +TEST_F(DeskTemplateConversionTest, ToJsonIgnoreUnsupportedApp) { + base::StringPiece raw_json = base::StringPiece(kValidTemplateBrowser); + base::JSONReader::ValueWithError parsed_json = + base::JSONReader::ReadAndReturnValueWithError(raw_json); + + EXPECT_TRUE(parsed_json.value.has_value()); + EXPECT_TRUE(parsed_json.value->is_dict()); + + std::unique_ptr<ash::DeskTemplate> desk_template = + desk_template_conversion::ParseDeskTemplateFromSource( + parsed_json.value.value(), ash::DeskTemplateSource::kUser); + + // Adding this unsupported app should not change the serialized JSON content. + saved_desk_test_util::AddGenericAppWindow( + kTestWindowId, desk_template_util::kTestUnsupportedAppId, + desk_template->mutable_desk_restore_data()); + + apps::AppRegistryCache* app_cache = + apps::AppRegistryCacheWrapper::Get().GetAppRegistryCache(account_id_); + + base::Value desk_template_value = + desk_template_conversion::SerializeDeskTemplateAsPolicy( + desk_template.get(), app_cache); + + EXPECT_EQ(parsed_json.value, desk_template_value); +} + TEST_F(DeskTemplateConversionTest, DeskTemplateFromJsonAppTest) { base::StringPiece raw_json = base::StringPiece(kValidTemplateChromeAndProgressive); @@ -337,4 +374,56 @@ EXPECT_EQ(parsed_json.value, desk_template_value); } +TEST_F(DeskTemplateConversionTest, EnsureLacrosBrowserWindowsSavedProperly) { + base::Time created_time = base::Time::Now(); + std::unique_ptr<ash::DeskTemplate> desk_template = + SavedDeskBuilder() + .SetUuid(kTestUuidBrowser) + .SetName(kBrowserTemplateName) + .SetType(ash::DeskTemplateType::kSaveAndRecall) + .SetCreatedTime(created_time) + .AddLacrosBrowserAppWindow(kBrowserWindowId, + {GURL(kBrowserUrl1), GURL(kBrowserUrl2)}) + .Build(); + + apps::AppRegistryCache* app_cache = + apps::AppRegistryCacheWrapper::Get().GetAppRegistryCache(account_id_); + + base::Value desk_template_value = + desk_template_conversion::SerializeDeskTemplateAsPolicy( + desk_template.get(), app_cache); + + base::Value::Dict expected_browser_tab1; + expected_browser_tab1.Set("url", base::Value(kBrowserUrl1)); + base::Value::Dict expected_browser_tab2; + expected_browser_tab2.Set("url", base::Value(kBrowserUrl2)); + base::Value::List expected_tab_list; + expected_tab_list.Append(std::move(expected_browser_tab1)); + expected_tab_list.Append(std::move(expected_browser_tab2)); + + base::Value::Dict expected_browser_app_value; + expected_browser_app_value.Set("app_type", base::Value("BROWSER")); + expected_browser_app_value.Set("event_flag", base::Value(0)); + expected_browser_app_value.Set("window_id", base::Value(kBrowserWindowId)); + expected_browser_app_value.Set("tabs", std::move(expected_tab_list)); + + base::Value::List expected_app_list; + expected_app_list.Append(std::move(expected_browser_app_value)); + + base::Value::Dict expected_desk_value; + expected_desk_value.Set("apps", std::move(expected_app_list)); + + base::Value::Dict expected_value; + expected_value.Set("version", base::Value(1)); + expected_value.Set("uuid", base::Value(kTestUuidBrowser)); + expected_value.Set("name", base::Value(kBrowserTemplateName)); + expected_value.Set("created_time_usec", base::TimeToValue(created_time)); + expected_value.Set("updated_time_usec", + base::TimeToValue(desk_template->GetLastUpdatedTime())); + expected_value.Set("desk_type", base::Value("SAVE_AND_RECALL")); + expected_value.Set("desk", std::move(expected_desk_value)); + + EXPECT_EQ(expected_value, desk_template_value); +} + } // namespace desks_storage
diff --git a/components/desks_storage/core/desk_template_util.cc b/components/desks_storage/core/desk_template_util.cc index 0ac95b6..36c393c 100644 --- a/components/desks_storage/core/desk_template_util.cc +++ b/components/desks_storage/core/desk_template_util.cc
@@ -55,17 +55,26 @@ apps::AppRegistryCache* cache) { std::vector<apps::AppPtr> deltas; - deltas.push_back(MakeApp(kTestPwaAppId, "Test PWA App", apps::AppType::kWeb)); + deltas.push_back( + MakeApp(kTestPwaAppId, "Test PWA App", apps::AppType::kChromeApp)); // chromeAppId returns kExtension in the real Apps cache. - deltas.push_back(MakeApp(app_constants::kChromeAppId, "Chrome Browser", + deltas.push_back(MakeApp(app_constants::kChromeAppId, "Ash Chrome Browser", apps::AppType::kChromeApp)); + deltas.push_back(MakeApp(app_constants::kLacrosAppId, "Lacros Chrome Browser", + apps::AppType::kStandaloneBrowser)); deltas.push_back( MakeApp(kTestChromeAppId, "Test Chrome App", apps::AppType::kChromeApp)); deltas.push_back(MakeApp(kTestArcAppId, "Arc app", apps::AppType::kArc)); deltas.push_back( - MakeApp(kTestPwaAppId1, "Test PWA App", apps::AppType::kWeb)); + MakeApp(kTestPwaAppId1, "Test PWA App 2", apps::AppType::kChromeApp)); + deltas.push_back(MakeApp(kTestChromeAppId1, "Test Chrome App 2", + apps::AppType::kChromeApp)); deltas.push_back( - MakeApp(kTestChromeAppId1, "Test Chrome App", apps::AppType::kChromeApp)); + MakeApp(kTestSwaAppId, "Test System Web App 1", apps::AppType::kWeb)); + deltas.push_back(MakeApp(kTestUnsupportedAppId, "Test Supported App 1", + apps::AppType::kPluginVm)); + deltas.push_back(MakeApp(kTestLacrosChromeAppId, "Test Chrome App", + apps::AppType::kStandaloneBrowserChromeApp)); if (base::FeatureList::IsEnabled(apps::kAppServiceOnAppUpdateWithoutMojom)) { cache->OnApps(std::move(deltas), apps::AppType::kUnknown,
diff --git a/components/desks_storage/core/desk_template_util.h b/components/desks_storage/core/desk_template_util.h index 71424375..0a0c460 100644 --- a/components/desks_storage/core/desk_template_util.h +++ b/components/desks_storage/core/desk_template_util.h
@@ -15,6 +15,10 @@ namespace desk_template_util { +constexpr char kTestSwaAppId[] = "test_swa_app_id"; +constexpr char kTestLacrosChromeAppId[] = "test_lacros_chrome_app_id"; +constexpr char kTestUnsupportedAppId[] = "test_unsupported_app_id"; + ash::DeskTemplate* FindOtherEntryWithName( const std::u16string& name, const base::GUID& uuid,
diff --git a/components/desks_storage/core/desk_template_util_unittests.cc b/components/desks_storage/core/desk_template_util_unittests.cc index dd0500b..59ffbb07 100644 --- a/components/desks_storage/core/desk_template_util_unittests.cc +++ b/components/desks_storage/core/desk_template_util_unittests.cc
@@ -64,7 +64,7 @@ AccountId account_id = AccountId::FromUserEmail("test@gmail.com"); auto cache = std::make_unique<apps::AppRegistryCache>(); desk_template_util::PopulateAppRegistryCache(account_id, cache.get()); - EXPECT_EQ(6ul, cache->GetAllApps().size()); + EXPECT_EQ(10ul, cache->GetAllApps().size()); } TEST_F(DeskTemplateUtilTest, AddOneAppIdToRegistryCacheHasAppInfo) { @@ -73,7 +73,7 @@ desk_template_util::PopulateAppRegistryCache(account_id, cache.get()); desk_template_util::AddAppIdToAppRegistryCache(account_id, cache.get(), "test"); - EXPECT_EQ(7ul, cache->GetAllApps().size()); + EXPECT_EQ(11ul, cache->GetAllApps().size()); } } // namespace desks_storage
diff --git a/components/desks_storage/core/saved_desk_builder.cc b/components/desks_storage/core/saved_desk_builder.cc new file mode 100644 index 0000000..947af91 --- /dev/null +++ b/components/desks_storage/core/saved_desk_builder.cc
@@ -0,0 +1,108 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/desks_storage/core/saved_desk_builder.h" + +#include "ash/public/cpp/desk_template.h" +#include "base/guid.h" +#include "base/time/time.h" +#include "components/app_restore/app_launch_info.h" +#include "components/desks_storage/core/saved_desk_test_util.h" + +namespace desks_storage { + +SavedDeskBuilder::SavedDeskBuilder() + : desk_name_("unnamed desk"), + desk_source_(ash::DeskTemplateSource::kUser), + desk_type_(ash::DeskTemplateType::kTemplate), + restore_data_(std::make_unique<app_restore::RestoreData>()) { + desk_uuid_ = base::GUID::GenerateRandomV4().AsLowercaseString(); + created_time_ = base::Time::Now(); +}; + +SavedDeskBuilder::~SavedDeskBuilder(){}; + +std::unique_ptr<ash::DeskTemplate> SavedDeskBuilder::Build() { + auto desk_template = std::make_unique<ash::DeskTemplate>( + desk_uuid_, desk_source_, desk_name_, created_time_, desk_type_); + + desk_template->set_desk_restore_data(std::move(restore_data_)); + + return desk_template; +} + +SavedDeskBuilder& SavedDeskBuilder::SetUuid(const std::string& uuid) { + desk_uuid_ = uuid; + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::SetName(const std::string& name) { + desk_name_ = name; + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::SetType(ash::DeskTemplateType desk_type) { + desk_type_ = desk_type; + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::SetSource( + ash::DeskTemplateSource desk_source) { + desk_source_ = desk_source; + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::SetCreatedTime(base::Time& created_time) { + created_time_ = created_time; + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddAshBrowserAppWindow( + int window_id, + std::vector<GURL> urls) { + saved_desk_test_util::AddBrowserWindow(/*is_lacros=*/false, window_id, urls, + restore_data_.get()); + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddLacrosBrowserAppWindow( + int window_id, + std::vector<GURL> urls) { + saved_desk_test_util::AddBrowserWindow(/*is_lacros=*/true, window_id, urls, + restore_data_.get()); + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddAshPwaAppWindow(int window_id, + const std::string url) { + saved_desk_test_util::AddPwaWindow(/*is_lacros=*/false, window_id, url, + restore_data_.get()); + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddLacrosPwaAppWindow( + int window_id, + const std::string url) { + saved_desk_test_util::AddPwaWindow(/*is_lacros=*/true, window_id, url, + restore_data_.get()); + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddChromeAppWindow( + int window_id, + const std::string app_id) { + saved_desk_test_util::AddGenericAppWindow(window_id, app_id, + restore_data_.get()); + return *this; +} + +SavedDeskBuilder& SavedDeskBuilder::AddGenericAppWindow( + int window_id, + const std::string app_id) { + saved_desk_test_util::AddGenericAppWindow(window_id, app_id, + restore_data_.get()); + return *this; +} + +} // namespace desks_storage
diff --git a/components/desks_storage/core/saved_desk_builder.h b/components/desks_storage/core/saved_desk_builder.h new file mode 100644 index 0000000..7bef062 --- /dev/null +++ b/components/desks_storage/core/saved_desk_builder.h
@@ -0,0 +1,84 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_BUILDER_H_ +#define COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_BUILDER_H_ + +#include <string> +#include <vector> + +#include "base/time/time.h" +#include "components/app_restore/restore_data.h" +#include "url/gurl.h" + +namespace ash { +class DeskTemplate; +enum class DeskTemplateSource; +enum class DeskTemplateType; +} // namespace ash + +namespace desks_storage { + +// Helper class for building a saved desk for test. +class SavedDeskBuilder { + public: + SavedDeskBuilder(); + SavedDeskBuilder(const SavedDeskBuilder&) = delete; + SavedDeskBuilder& operator=(const SavedDeskBuilder&) = delete; + ~SavedDeskBuilder(); + + // Builds a saved desk. This should only be called once per builder + // instance. + std::unique_ptr<ash::DeskTemplate> Build(); + + // Sets saved desk UUID. If not set, the built desk will have a random UUID. + SavedDeskBuilder& SetUuid(const std::string& uuid); + + // Sets saved desk name. If not set, the built desk will have a fixed name. + SavedDeskBuilder& SetName(const std::string& name); + + // Sets saved desk type. If not set, the built desk will default to + // DeskTemplate. + SavedDeskBuilder& SetType(ash::DeskTemplateType desk_type); + + // Sets saved desk source. If not set, the built desk will default to kUser. + SavedDeskBuilder& SetSource(ash::DeskTemplateSource desk_source); + + // Sets saved desk creation timestamp. If not set, the built desk will have + // its creation timestamp set at the creation time of the SavedDeskBuilder. + SavedDeskBuilder& SetCreatedTime(base::Time& created_time); + + // Adds a Ash Chrome Browser App window. + SavedDeskBuilder& AddAshBrowserAppWindow(int window_id, + std::vector<GURL> urls); + + // Adds a Lacros Chrome Browser App window. + SavedDeskBuilder& AddLacrosBrowserAppWindow(int window_id, + std::vector<GURL> urls); + + // Adds a PWA window hosted in Ash Chrome. + SavedDeskBuilder& AddAshPwaAppWindow(int window_id, const std::string url); + + // Adds a PWA window hosted in Lacros Chrome. + SavedDeskBuilder& AddLacrosPwaAppWindow(int window_id, const std::string url); + + // Adds a Chrome app window. + SavedDeskBuilder& AddChromeAppWindow(int window_id, const std::string app_id); + + // Adds a generic app window. + SavedDeskBuilder& AddGenericAppWindow(int window_id, + const std::string app_id); + + private: + std::string desk_uuid_; + std::string desk_name_; + ash::DeskTemplateSource desk_source_; + ash::DeskTemplateType desk_type_; + base::Time created_time_; + std::unique_ptr<app_restore::RestoreData> restore_data_; +}; + +} // namespace desks_storage + +#endif // COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_BUILDER_H_
diff --git a/components/desks_storage/core/saved_desk_test_util.cc b/components/desks_storage/core/saved_desk_test_util.cc new file mode 100644 index 0000000..ac6697f5 --- /dev/null +++ b/components/desks_storage/core/saved_desk_test_util.cc
@@ -0,0 +1,52 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/desks_storage/core/saved_desk_test_util.h" + +#include "components/app_constants/constants.h" +#include "components/app_restore/app_launch_info.h" +#include "components/app_restore/restore_data.h" + +namespace desks_storage { + +namespace saved_desk_test_util { + +void AddBrowserWindow(bool is_lacros, + int window_id, + std::vector<GURL> urls, + app_restore::RestoreData* out_restore_data) { + auto browser_info = std::make_unique<app_restore::AppLaunchInfo>( + is_lacros ? app_constants::kLacrosAppId : app_constants::kChromeAppId, + window_id); + browser_info->urls = urls; + + out_restore_data->AddAppLaunchInfo(std::move(browser_info)); +} + +void AddPwaWindow(bool is_lacros, + int window_id, + std::string url, + app_restore::RestoreData* out_restore_data) { + auto app_launch_info = std::make_unique<app_restore::AppLaunchInfo>( + is_lacros ? app_constants::kLacrosAppId : app_constants::kChromeAppId, + window_id); + + app_launch_info->urls = {GURL(url)}; + app_launch_info->app_type_browser = true; + + out_restore_data->AddAppLaunchInfo(std::move(app_launch_info)); +} + +void AddGenericAppWindow(int window_id, + std::string app_id, + app_restore::RestoreData* out_restore_data) { + auto app_launch_info = + std::make_unique<app_restore::AppLaunchInfo>(app_id, window_id); + + out_restore_data->AddAppLaunchInfo(std::move(app_launch_info)); +} + +} // namespace saved_desk_test_util + +} // namespace desks_storage
diff --git a/components/desks_storage/core/saved_desk_test_util.h b/components/desks_storage/core/saved_desk_test_util.h new file mode 100644 index 0000000..edea31d --- /dev/null +++ b/components/desks_storage/core/saved_desk_test_util.h
@@ -0,0 +1,40 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_TEST_UTIL_H_ +#define COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_TEST_UTIL_H_ + +#include <string> +#include <vector> + +#include "base/time/time.h" +#include "components/app_restore/restore_data.h" +#include "url/gurl.h" + +namespace desks_storage { + +namespace saved_desk_test_util { + +// Adds a Chrome browser window to `out_restore_data`. +void AddBrowserWindow(bool is_lacros, + int window_id, + std::vector<GURL> urls, + app_restore::RestoreData* out_restore_data); + +// Adds a PWA window to `out_restore_data`. +void AddPwaWindow(bool is_lacros, + int window_id, + std::string url, + app_restore::RestoreData* out_restore_data); + +// Adds a Generic app window to `out_restore_data`. +void AddGenericAppWindow(int window_id, + std::string app_id, + app_restore::RestoreData* out_restore_data); + +} // namespace saved_desk_test_util + +} // namespace desks_storage + +#endif // COMPONENTS_DESKS_STORAGE_CORE_SAVED_DESK_TEST_UTIL_H_
diff --git a/components/digital_asset_links/digital_asset_links_handler.cc b/components/digital_asset_links/digital_asset_links_handler.cc index e18ada8..34ba3a9a 100644 --- a/components/digital_asset_links/digital_asset_links_handler.cc +++ b/components/digital_asset_links/digital_asset_links_handler.cc
@@ -107,7 +107,7 @@ void AddMessageToConsole(content::WebContents* web_contents, const std::string& message) { if (web_contents) { - web_contents->GetMainFrame()->AddMessageToConsole( + web_contents->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); return; }
diff --git a/components/dom_distiller/content/browser/distillable_page_utils.cc b/components/dom_distiller/content/browser/distillable_page_utils.cc index f1de057..9910e29 100644 --- a/components/dom_distiller/content/browser/distillable_page_utils.cc +++ b/components/dom_distiller/content/browser/distillable_page_utils.cc
@@ -38,7 +38,7 @@ void IsDistillablePageForDetector(content::WebContents* web_contents, const DistillablePageDetector* detector, base::OnceCallback<void(bool)> callback) { - content::RenderFrameHost* main_frame = web_contents->GetMainFrame(); + content::RenderFrameHost* main_frame = web_contents->GetPrimaryMainFrame(); if (!main_frame) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), false));
diff --git a/components/dom_distiller/content/browser/dom_distiller_viewer_source.cc b/components/dom_distiller/content/browser/dom_distiller_viewer_source.cc index adb03f9..4effbe9 100644 --- a/components/dom_distiller/content/browser/dom_distiller_viewer_source.cc +++ b/components/dom_distiller/content/browser/dom_distiller_viewer_source.cc
@@ -110,7 +110,7 @@ } else { DCHECK(buffer_.empty()); if (web_contents()) { - RunIsolatedJavaScript(web_contents()->GetMainFrame(), buffer); + RunIsolatedJavaScript(web_contents()->GetPrimaryMainFrame(), buffer); } } } @@ -186,7 +186,7 @@ // No SendJavaScript() calls allowed before |buffer_| is run and cleared. waiting_for_page_ready_ = false; if (!buffer_.empty()) { - RunIsolatedJavaScript(web_contents()->GetMainFrame(), buffer_); + RunIsolatedJavaScript(web_contents()->GetPrimaryMainFrame(), buffer_); buffer_.clear(); } // No need to Cancel() here.
diff --git a/components/dom_distiller/content/browser/test/dom_distiller_js_browsertest.cc b/components/dom_distiller/content/browser/test/dom_distiller_js_browsertest.cc index ebeca0e..b5a8f4ccc 100644 --- a/components/dom_distiller/content/browser/test/dom_distiller_js_browsertest.cc +++ b/components/dom_distiller/content/browser/test/dom_distiller_js_browsertest.cc
@@ -149,7 +149,7 @@ // QuitClosure multiple times. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_max_timeout()); - web_contents->GetMainFrame()->ExecuteJavaScriptForTests( + web_contents->GetPrimaryMainFrame()->ExecuteJavaScriptForTests( base::UTF8ToUTF16(kRunJsTestsJs), base::BindOnce(&DomDistillerJsTest::OnJsTestExecutionDone, base::Unretained(this)));
diff --git a/components/embedder_support/user_agent_utils.cc b/components/embedder_support/user_agent_utils.cc index b8764e5..acd6038 100644 --- a/components/embedder_support/user_agent_utils.cc +++ b/components/embedder_support/user_agent_utils.cc
@@ -528,11 +528,21 @@ output_version_type); } } -// TODO(crbug.com/1103047): This can be removed/re-refactored once we use -// "macOS" by default + std::string GetPlatformForUAMetadata() { #if BUILDFLAG(IS_MAC) + // TODO(crbug.com/1103047): This can be removed/re-refactored once we use + // "macOS" by default return "macOS"; +#elif BUILDFLAG(IS_CHROMEOS) + // TODO(crbug.com/1334198): The branding change to remove the space caused a + // regression that's solved here. Ideally, we would just use the new OS name + // without the space here too, but that needs a launch plan. +# if BUILDFLAG(GOOGLE_CHROME_BRANDING) + return "Chrome OS"; +# else + return "Chromium OS"; +# endif #else return version_info::GetOSType(); #endif
diff --git a/components/embedder_support/user_agent_utils_unittest.cc b/components/embedder_support/user_agent_utils_unittest.cc index de7fd76c..d8e0413 100644 --- a/components/embedder_support/user_agent_utils_unittest.cc +++ b/components/embedder_support/user_agent_utils_unittest.cc
@@ -15,6 +15,7 @@ #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/version.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "components/embedder_support/pref_names.h" #include "components/prefs/pref_registry_simple.h" @@ -608,12 +609,35 @@ #endif // This makes sure no extra information is added to the platform version. EXPECT_EQ(metadata.platform_version.find(";"), std::string::npos); - // TODO(crbug.com/1103047): This can be removed/re-refactored once we use - // "macOS" by default -#if BUILDFLAG(IS_MAC) + // If you're here because your change to GetOSType broke this test, it likely + // means that GetPlatformForUAMetadata needs a new special case to prevent + // breaking client hints. Check with the code owners for further guidance. +#if BUILDFLAG(IS_WIN) + EXPECT_EQ(metadata.platform, "Windows"); +#elif BUILDFLAG(IS_IOS) + EXPECT_EQ(metadata.platform, "iOS"); +#elif BUILDFLAG(IS_MAC) EXPECT_EQ(metadata.platform, "macOS"); +#elif BUILDFLAG(IS_CHROMEOS) +# if BUILDFLAG(GOOGLE_CHROME_BRANDING) + EXPECT_EQ(metadata.platform, "Chrome OS"); +# else + EXPECT_EQ(metadata.platform, "Chromium OS"); +# endif +#elif BUILDFLAG(IS_ANDROID) + EXPECT_EQ(metadata.platform, "Android"); +#elif BUILDFLAG(IS_LINUX) + EXPECT_EQ(metadata.platform, "Linux"); +#elif BUILDFLAG(IS_FREEBSD) + EXPECT_EQ(metadata.platform, "FreeBSD"); +#elif BUILDFLAG(IS_OPENBSD) + EXPECT_EQ(metadata.platform, "OpenBSD"); +#elif BUILDFLAG(IS_SOLARIS) + EXPECT_EQ(metadata.platform, "Solaris"); +#elif BUILDFLAG(IS_FUCHSIA) + EXPECT_EQ(metadata.platform, "Fuchsia"); #else - EXPECT_EQ(metadata.platform, version_info::GetOSType()); + EXPECT_EQ(metadata.platform, "Unknown"); #endif EXPECT_EQ(metadata.architecture, content::GetCpuArchitecture()); EXPECT_EQ(metadata.model, content::BuildModelInfo());
diff --git a/components/error_page/content/browser/net_error_auto_reloader.cc b/components/error_page/content/browser/net_error_auto_reloader.cc index 872daad..51892722 100644 --- a/components/error_page/content/browser/net_error_auto_reloader.cc +++ b/components/error_page/content/browser/net_error_auto_reloader.cc
@@ -291,7 +291,7 @@ ++num_reloads_for_current_error_; is_auto_reload_in_progress_ = true; - web_contents()->GetMainFrame()->Reload(); + web_contents()->GetPrimaryMainFrame()->Reload(); } std::unique_ptr<content::NavigationThrottle>
diff --git a/components/error_page/content/browser/net_error_auto_reloader_browsertest.cc b/components/error_page/content/browser/net_error_auto_reloader_browsertest.cc index 5951a9c..081edb6 100644 --- a/components/error_page/content/browser/net_error_auto_reloader_browsertest.cc +++ b/components/error_page/content/browser/net_error_auto_reloader_browsertest.cc
@@ -562,7 +562,7 @@ const GURL fenced_frame_url = embedded_test_server()->GetURL("/title2.html"); content::RenderFrameHost* fenced_frame_host = fenced_frame_test_helper().CreateFencedFrame( - shell()->web_contents()->GetMainFrame(), fenced_frame_url, + shell()->web_contents()->GetPrimaryMainFrame(), fenced_frame_url, net::ERR_BLOCKED_BY_RESPONSE); // The fenced frame navigation failed since it doesn't have the
diff --git a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationDelegate.java b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationDelegate.java index c98fd2f..16141f9 100644 --- a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationDelegate.java +++ b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationDelegate.java
@@ -55,10 +55,8 @@ /** * Dispatches the intent through a proxy activity, so that startActivityForResult can be used - * and the intent recipient can verify the caller. Will be invoked only in flows where - * ExternalNavigationDelegate#isIntentForInstantApp() returns true for |intent|. In particular, - * if that method always returns false in the given embedder, then the embedder's implementation - * of this method will never be invoked and can just assert false. + * and the intent recipient can verify the caller. Will be invoked only in delegates where + * ExternalNavigationDelegate#handlesInstantAppLaunchingInternally() returns true. * @param intent The bare intent we were going to send. */ void dispatchAuthenticatedIntent(Intent intent); @@ -167,12 +165,6 @@ boolean isIntentForTrustedCallingApp(Intent intent); /** - * @param intent The intent to launch. - * @return Whether the Intent points to an instant app. - */ - boolean isIntentToInstantApp(Intent intent); - - /** * @param intent The intent to launch * @return Whether the Intent points to Autofill Assistant */
diff --git a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java index c4f7fc5..893436c6 100644 --- a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java +++ b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java
@@ -125,6 +125,14 @@ | Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT; + @VisibleForTesting + static final String INSTANT_APP_SUPERVISOR_PKG = "com.google.android.instantapps.supervisor"; + + @VisibleForTesting + static final String[] INSTANT_APP_START_ACTIONS = {"com.google.android.instantapps.START", + "com.google.android.instantapps.nmr1.INSTALL", + "com.google.android.instantapps.nmr1.VIEW"}; + // These values are persisted in histograms. Please do not renumber. Append only. @IntDef({AiaIntent.FALLBACK_USED, AiaIntent.SERP, AiaIntent.OTHER}) @Retention(RetentionPolicy.SOURCE) @@ -367,7 +375,7 @@ return OverrideUrlLoadingResult.forNoOverride(); } - if (mDelegate.isIntentToInstantApp(targetIntent)) { + if (isIntentToInstantApp(targetIntent)) { RecordHistogram.recordEnumeratedHistogram("Android.InstantApps.DirectInstantAppsIntent", AiaIntent.FALLBACK_USED, AiaIntent.NUM_ENTRIES); } @@ -1007,9 +1015,9 @@ * For security reasons, we disable all intent:// URLs to Instant Apps that are not coming from * SERP. */ - private boolean preventDirectInstantAppsIntent( - boolean isDirectInstantAppsIntent, boolean shouldProxyForInstantApps) { - if (!isDirectInstantAppsIntent || shouldProxyForInstantApps) return false; + private boolean preventDirectInstantAppsIntent(Intent intent) { + if (!isIntentToInstantApp(intent)) return false; + if (isSerpReferrer() && mDelegate.handlesInstantAppLaunchingInternally()) return false; if (DEBUG) Log.i(TAG, "Intent URL to an Instant App"); RecordHistogram.recordEnumeratedHistogram("Android.InstantApps.DirectInstantAppsIntent", AiaIntent.OTHER, AiaIntent.NUM_ENTRIES); @@ -1363,6 +1371,10 @@ if (isUnhandledWtaiProtocol(params)) return OverrideUrlLoadingResult.forNoOverride(); + if (preventDirectInstantAppsIntent(targetIntent)) { + return OverrideUrlLoadingResult.forNoOverride(); + } + if (redirectShouldStayInApp(params, isExternalProtocol, targetIntent)) { return OverrideUrlLoadingResult.forNoOverride(); } @@ -1404,13 +1416,8 @@ return OverrideUrlLoadingResult.forNoOverride(); } - boolean isDirectInstantAppsIntent = - isExternalProtocol && mDelegate.isIntentToInstantApp(targetIntent); - boolean shouldProxyForInstantApps = isDirectInstantAppsIntent && isSerpReferrer(); - if (preventDirectInstantAppsIntent(isDirectInstantAppsIntent, shouldProxyForInstantApps)) { - return OverrideUrlLoadingResult.forNoOverride(); - } - + boolean shouldProxyForInstantApps = mDelegate.handlesInstantAppLaunchingInternally() + && isIntentToInstantApp(targetIntent) && isSerpReferrer(); prepareExternalIntent( targetIntent, params, resolvingInfos.get(), shouldProxyForInstantApps); // As long as our intent resolution hasn't changed, resolvingInfos won't need to be @@ -2104,4 +2111,21 @@ return (params.isLinkTransition() && params.isFromIntent() && params.isRedirect()) || isOnEffectiveIntentRedirect; } + + /** + * Checks whether {@param intent} is for an Instant App. Considers both package and actions that + * would resolve to Supervisor. + * @return Whether the given intent is going to open an Instant App. + */ + private static boolean isIntentToInstantApp(Intent intent) { + if (INSTANT_APP_SUPERVISOR_PKG.equals(intent.getPackage())) return true; + + String intentAction = intent.getAction(); + for (String action : INSTANT_APP_START_ACTIONS) { + if (action.equals(intentAction)) { + return true; + } + } + return false; + } }
diff --git a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java index 7d87c1b..e3ad817e 100644 --- a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java +++ b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java
@@ -907,7 +907,7 @@ + "https%3A%2F%2Fwww.google.com;end"; mUrlHandler.mIsSerpReferrer = true; - mDelegate.setIsIntentToInstantApp(true); + mDelegate.setHandlesInstantAppLaunchingInternally(true); checkUrl(intentUrl).expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, START_OTHER_ACTIVITY | PROXY_FOR_INSTANT_APPS); Assert.assertTrue( @@ -917,14 +917,34 @@ mUrlHandler.mIsSerpReferrer = false; checkUrl(intentUrl).expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, IGNORE); - // Check that that just having the SERP referrer alone doesn't cause intents to be treated - // as intents to instant apps if the delegate indicates that they shouldn't be. + // Check that that just having the SERP referrer alone doesn't cause instant app intents to + // launched through the proxy. mUrlHandler.mIsSerpReferrer = true; - mDelegate.setIsIntentToInstantApp(false); - checkUrl(intentUrl).expecting( - OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, START_OTHER_ACTIVITY); - Assert.assertFalse( - mUrlHandler.mStartActivityIntent.getBooleanExtra(IS_INSTANT_APP_EXTRA, true)); + mDelegate.setHandlesInstantAppLaunchingInternally(false); + checkUrl(intentUrl).expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, IGNORE); + } + + @Test + @SmallTest + public void testIsIntentToInstantApp() { + // Check that the delegate correctly distinguishes instant app intents from others. + String instantAppIntentUrlPrefix = "intent://buzzfeed.com/tasty#Intent;scheme=http;"; + + mUrlHandler.mIsSerpReferrer = true; + mDelegate.setHandlesInstantAppLaunchingInternally(true); + + // Check that Supervisor is detected by action even without package. + for (String action : ExternalNavigationHandler.INSTANT_APP_START_ACTIONS) { + String intentUrl = instantAppIntentUrlPrefix + "action=" + action + ";end"; + checkUrl(intentUrl).expecting( + OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, + START_OTHER_ACTIVITY | PROXY_FOR_INSTANT_APPS); + } + + String intentUrl = instantAppIntentUrlPrefix + + "package=" + ExternalNavigationHandler.INSTANT_APP_SUPERVISOR_PKG + ";end"; + checkUrl(intentUrl).expecting(OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT, + START_OTHER_ACTIVITY | PROXY_FOR_INSTANT_APPS); } @Test @@ -2738,7 +2758,7 @@ @Override public boolean handlesInstantAppLaunchingInternally() { - return false; + return mHandlesInstantAppLaunchingInternally; } @Override @@ -2835,11 +2855,6 @@ } @Override - public boolean isIntentToInstantApp(Intent intent) { - return mIsIntentToInstantApp; - } - - @Override public boolean isIntentToAutofillAssistant(Intent intent) { return mIsIntentToAutofillAssistant; } @@ -2930,10 +2945,6 @@ mShouldDisableExternalIntentRequests = disable; } - public void setIsIntentToInstantApp(boolean value) { - mIsIntentToInstantApp = value; - } - public void setIsIntentToAutofillAssistant(boolean value) { mIsIntentToAutofillAssistant = value; } @@ -2971,6 +2982,10 @@ mShouldEmbedderInitiatedNavigationsStayInBrowser = value; } + public void setHandlesInstantAppLaunchingInternally(boolean value) { + mHandlesInstantAppLaunchingInternally = value; + } + public boolean startIncognitoIntentCalled; public boolean maybeSetRequestMetadataCalled; public Callback<Boolean> incognitoDialogUserDecisionCallback; @@ -2985,7 +3000,6 @@ public boolean mIsChromeAppInForeground = true; private boolean mIsCallingAppTrusted; private boolean mShouldDisableExternalIntentRequests; - private boolean mIsIntentToInstantApp; private boolean mIsIntentToAutofillAssistant; private @IntentToAutofillAllowingAppResult int mAutofillAssistantAllowAppOverrideResult; private boolean mCanLoadUrlInTab; @@ -2996,6 +3010,7 @@ private boolean mWillResolveToDisambiguationDialog; private Context mContext; private boolean mShouldEmbedderInitiatedNavigationsStayInBrowser = true; + private boolean mHandlesInstantAppLaunchingInternally = true; } private void checkIntentSanity(Intent intent, String name) {
diff --git a/components/favicon/content/content_favicon_driver_unittest.cc b/components/favicon/content/content_favicon_driver_unittest.cc index 656a702..046a858f 100644 --- a/components/favicon/content/content_favicon_driver_unittest.cc +++ b/components/favicon/content/content_favicon_driver_unittest.cc
@@ -39,7 +39,7 @@ ContentFaviconDriver::FromWebContents(web_contents); content::WebContentsTester::For(web_contents)->NavigateAndCommit(page_url); static_cast<content::WebContentsObserver*>(favicon_driver) - ->DidUpdateFaviconURL(web_contents->GetMainFrame(), candidates); + ->DidUpdateFaviconURL(web_contents->GetPrimaryMainFrame(), candidates); base::RunLoop().RunUntilIdle(); } @@ -116,13 +116,14 @@ navigation->SetKeepLoading(true); navigation->Commit(); GURL manifest_url = kFakeManifestURL; - auto* rfh_tester = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()); + auto* rfh_tester = content::RenderFrameHostTester::For( + web_contents()->GetPrimaryMainFrame()); rfh_tester->SimulateManifestURLUpdate(manifest_url); static_cast<content::WebContentsObserver*>(favicon_driver) - ->DidUpdateWebManifestURL(web_contents()->GetMainFrame(), manifest_url); - EXPECT_EQ(GURL(), - favicon_driver->GetManifestURL(web_contents()->GetMainFrame())); + ->DidUpdateWebManifestURL(web_contents()->GetPrimaryMainFrame(), + manifest_url); + EXPECT_EQ(GURL(), favicon_driver->GetManifestURL( + web_contents()->GetPrimaryMainFrame())); } // Ensures that we use a manifest URL if it arrives after the onload handler @@ -136,13 +137,14 @@ navigation->Commit(); navigation->StopLoading(); GURL manifest_url = kFakeManifestURL; - auto* rfh_tester = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()); + auto* rfh_tester = content::RenderFrameHostTester::For( + web_contents()->GetPrimaryMainFrame()); rfh_tester->SimulateManifestURLUpdate(manifest_url); static_cast<content::WebContentsObserver*>(favicon_driver) - ->DidUpdateWebManifestURL(web_contents()->GetMainFrame(), manifest_url); - EXPECT_EQ(kFakeManifestURL, - favicon_driver->GetManifestURL(web_contents()->GetMainFrame())); + ->DidUpdateWebManifestURL(web_contents()->GetPrimaryMainFrame(), + manifest_url); + EXPECT_EQ(kFakeManifestURL, favicon_driver->GetManifestURL( + web_contents()->GetPrimaryMainFrame())); } // Test that no download is initiated when @@ -159,7 +161,8 @@ favicon_urls.push_back(blink::mojom::FaviconURL::New( kIconURL, blink::mojom::FaviconIconType::kFavicon, kEmptyIconSizes)); static_cast<content::WebContentsObserver*>(favicon_driver) - ->DidUpdateFaviconURL(web_contents()->GetMainFrame(), favicon_urls); + ->DidUpdateFaviconURL(web_contents()->GetPrimaryMainFrame(), + favicon_urls); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(web_contents_tester()->HasPendingDownloadImage(kIconURL)); @@ -223,7 +226,7 @@ // Trigger downloading a manifest. static_cast<content::WebContentsObserver*>(driver)->DidUpdateWebManifestURL( - web_contents()->GetMainFrame(), GURL("http://bad.manifest.com")); + web_contents()->GetPrimaryMainFrame(), GURL("http://bad.manifest.com")); // The request for the manifest is still pending, delete the WebContents, // which should trigger notifying the callback for the manifest and *not*
diff --git a/components/find_in_page/find_tab_helper.cc b/components/find_in_page/find_tab_helper.cc index 4aa33ba4..a1d8477 100644 --- a/components/find_in_page/find_tab_helper.cc +++ b/components/find_in_page/find_tab_helper.cc
@@ -127,8 +127,9 @@ } void FindTabHelper::ActivateFindInPageResultForAccessibility() { - GetWebContents().GetMainFrame()->ActivateFindInPageResultForAccessibility( - current_find_request_id_); + GetWebContents() + .GetPrimaryMainFrame() + ->ActivateFindInPageResultForAccessibility(current_find_request_id_); } std::u16string FindTabHelper::GetInitialSearchText() {
diff --git a/components/guest_view/browser/guest_view_base.cc b/components/guest_view/browser/guest_view_base.cc index 476d5c3..033264f9 100644 --- a/components/guest_view/browser/guest_view_base.cc +++ b/components/guest_view/browser/guest_view_base.cc
@@ -416,7 +416,10 @@ } const GURL& GuestViewBase::GetOwnerSiteURL() const { - return owner_web_contents()->GetMainFrame()->GetSiteInstance()->GetSiteURL(); + return owner_web_contents() + ->GetPrimaryMainFrame() + ->GetSiteInstance() + ->GetSiteURL(); } bool GuestViewBase::ShouldDestroyOnDetach() const { @@ -554,7 +557,7 @@ void GuestViewBase::DidStopLoading() { content::RenderViewHost* rvh = - web_contents()->GetMainFrame()->GetRenderViewHost(); + web_contents()->GetPrimaryMainFrame()->GetRenderViewHost(); if (IsPreferredSizeModeEnabled()) rvh->EnablePreferredSizeMode();
diff --git a/components/guest_view/browser/guest_view_manager.cc b/components/guest_view/browser/guest_view_manager.cc index a16ee6c..167aa21 100644 --- a/components/guest_view/browser/guest_view_manager.cc +++ b/components/guest_view/browser/guest_view_manager.cc
@@ -520,7 +520,7 @@ guest_view->CanBeEmbeddedInsideCrossProcessFrames() ? guest_view->GetOwnerSiteInstance()->GetProcess()->GetID() : guest_view->owner_web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess() ->GetID();
diff --git a/components/javascript_dialogs/app_modal_dialog_manager.cc b/components/javascript_dialogs/app_modal_dialog_manager.cc index 78c50b4..0f73eb2 100644 --- a/components/javascript_dialogs/app_modal_dialog_manager.cc +++ b/components/javascript_dialogs/app_modal_dialog_manager.cc
@@ -85,8 +85,9 @@ return base::UTF8ToUTF16(name); // Otherwise, return the formatted URL. - return GetTitleImpl(web_contents->GetMainFrame()->GetLastCommittedOrigin(), - alerting_frame_origin); + return GetTitleImpl( + web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), + alerting_frame_origin); } namespace {
diff --git a/components/javascript_dialogs/tab_modal_dialog_manager.cc b/components/javascript_dialogs/tab_modal_dialog_manager.cc index 9a5f740..075a078 100644 --- a/components/javascript_dialogs/tab_modal_dialog_manager.cc +++ b/components/javascript_dialogs/tab_modal_dialog_manager.cc
@@ -69,12 +69,12 @@ content::WebContents* web_contents, content::RenderFrameHost* alerting_frame) { url::Origin main_frame_origin = - web_contents->GetMainFrame()->GetLastCommittedOrigin(); + web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(); if (!main_frame_origin.GetURL().SchemeIsHTTPOrHTTPS()) return DialogOriginRelationship::NON_HTTP_MAIN_FRAME; - if (alerting_frame == web_contents->GetMainFrame()) + if (alerting_frame == web_contents->GetPrimaryMainFrame()) return DialogOriginRelationship::HTTP_MAIN_FRAME; url::Origin alerting_frame_origin = alerting_frame->GetLastCommittedOrigin(); @@ -377,8 +377,9 @@ // WebContents that had the alert call in it. For 99.9999% of cases they're // the same, but for instances like the <webview> tag in extensions and PDF // files that alert they may differ. - ukm::SourceId source_id = - WebContentsObserver::web_contents()->GetMainFrame()->GetPageUkmSourceId(); + ukm::SourceId source_id = WebContentsObserver::web_contents() + ->GetPrimaryMainFrame() + ->GetPageUkmSourceId(); if (source_id != ukm::kInvalidSourceId) { ukm::builders::AbusiveExperienceHeuristic_JavaScriptDialog(source_id) .SetDismissalCause(static_cast<int64_t>(cause))
diff --git a/components/js_injection/browser/js_communication_host.cc b/components/js_injection/browser/js_communication_host.cc index fe477eb..e171897 100644 --- a/components/js_injection/browser/js_communication_host.cc +++ b/components/js_injection/browser/js_communication_host.cc
@@ -115,7 +115,7 @@ scripts_.emplace_back(script, origin_matcher, next_script_id_++); ForEachRenderFrameHostWithinSameWebContents( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &JsCommunicationHost::NotifyFrameForAddDocumentStartJavaScript, base::Unretained(this), &*scripts_.rbegin())); @@ -128,7 +128,7 @@ if (it->script_id_ == script_id) { scripts_.erase(it); ForEachRenderFrameHostWithinSameWebContents( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &JsCommunicationHost::NotifyFrameForRemoveDocumentStartJavaScript, base::Unretained(this), script_id)); @@ -158,7 +158,7 @@ js_object_name, origin_matcher, std::move(factory))); ForEachRenderFrameHostWithinSameWebContents( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &JsCommunicationHost::NotifyFrameForWebMessageListener, base::Unretained(this))); @@ -172,7 +172,7 @@ if ((*iterator)->name == js_object_name) { js_objects_.erase(iterator); ForEachRenderFrameHostWithinSameWebContents( - web_contents()->GetMainFrame(), + web_contents()->GetPrimaryMainFrame(), base::BindRepeating( &JsCommunicationHost::NotifyFrameForWebMessageListener, base::Unretained(this)));
diff --git a/components/js_injection/browser/js_to_browser_messaging.cc b/components/js_injection/browser/js_to_browser_messaging.cc index d79e726..f7a7e5f 100644 --- a/components/js_injection/browser/js_to_browser_messaging.cc +++ b/components/js_injection/browser/js_to_browser_messaging.cc
@@ -112,7 +112,7 @@ if (!host_) { const std::string origin_string = GetOriginString(source_origin); const bool is_main_frame = - web_contents->GetMainFrame() == render_frame_host_; + web_contents->GetPrimaryMainFrame() == render_frame_host_; host_ = connection_factory_->CreateHost(origin_string, is_main_frame, reply_proxy_.get()); @@ -127,7 +127,8 @@ // PostMessage() has been received. #if DCHECK_IS_ON() DCHECK_EQ(GetOriginString(source_origin), origin_string_); - DCHECK_EQ(is_main_frame_, web_contents->GetMainFrame() == render_frame_host_); + DCHECK_EQ(is_main_frame_, + web_contents->GetPrimaryMainFrame() == render_frame_host_); #endif std::unique_ptr<WebMessage> web_message = std::make_unique<WebMessage>(); web_message->message = message;
diff --git a/components/lens/lens_entrypoints.cc b/components/lens/lens_entrypoints.cc index 5d906cd..8ef27c0 100644 --- a/components/lens/lens_entrypoints.cc +++ b/components/lens/lens_entrypoints.cc
@@ -19,6 +19,7 @@ constexpr char kChromeRegionSearchMenuItem[] = "crs"; constexpr char kChromeSearchWithGoogleLensContextMenuItem[] = "ccm"; constexpr char kChromeOpenNewTabSidePanel[] = "cnts"; +constexpr char kChromeFullscreenSearchMenuItem[] = "cfs"; constexpr char kSurfaceQueryParameter[] = "s"; constexpr char kStartTimeQueryParameter[] = "st"; @@ -52,11 +53,7 @@ break; case lens::CHROME_FULLSCREEN_SEARCH_MENU_ITEM: query_parameters.insert( - {kEntryPointQueryParameter, kChromeRegionSearchMenuItem}); - // TODO(b/233774783): Remove adding the side panel surface query parameter - // when we have a proper AVS entry point that can conform Lens Web to - // spec. - query_parameters.insert({kSurfaceQueryParameter, kSidePanel}); + {kEntryPointQueryParameter, kChromeFullscreenSearchMenuItem}); break; default: // Empty strings are ignored when query parameters are built.
diff --git a/components/lens/lens_entrypoints_unittest.cc b/components/lens/lens_entrypoints_unittest.cc index 8b877003..652af0f 100644 --- a/components/lens/lens_entrypoints_unittest.cc +++ b/components/lens/lens_entrypoints_unittest.cc
@@ -59,7 +59,7 @@ lens::EntryPoint::CHROME_FULLSCREEN_SEARCH_MENU_ITEM; std::string query_param = lens::GetQueryParametersForLensRequest( lens_ep, /*is_side_panel_request=*/false); - EXPECT_THAT(query_param, MatchesRegex("ep=crs&s=csp&st=\\d+")); + EXPECT_THAT(query_param, MatchesRegex("ep=cfs&s=&st=\\d+")); } TEST(LensEntryPointsTest, GetUnknownEntryPointTest) { @@ -126,7 +126,7 @@ GURL original_url = GURL("https://lens.google.com/"); GURL url = lens::AppendOrReplaceQueryParametersForLensRequest( original_url, lens_ep, /*is_side_panel_request=*/false); - EXPECT_THAT(url.query(), MatchesRegex("ep=crs&s=csp&st=\\d+")); + EXPECT_THAT(url.query(), MatchesRegex("ep=cfs&s=&st=\\d+")); } TEST(LensEntryPointsTest, AppendUnknownEntryPointTest) {
diff --git a/components/live_caption/views/caption_bubble.cc b/components/live_caption/views/caption_bubble.cc index af9d489..ac3258fe 100644 --- a/components/live_caption/views/caption_bubble.cc +++ b/components/live_caption/views/caption_bubble.cc
@@ -1071,8 +1071,6 @@ if (HasMediaFoundationError()) return; - Hide(); - // Clear the partial and final text in the caption bubble model and the label. // Does not affect the speech service. The speech service will emit a final // result after ~10-15 seconds of no audio which the caption bubble will @@ -1082,6 +1080,8 @@ // contain text cleared by the UI. if (model_) model_->ClearText(); + + Hide(); } void CaptionBubble::MediaFoundationErrorCheckboxPressed() {
diff --git a/components/metrics/content/subprocess_metrics_provider_browsertest.cc b/components/metrics/content/subprocess_metrics_provider_browsertest.cc index df52b0bc..64a2a80 100644 --- a/components/metrics/content/subprocess_metrics_provider_browsertest.cc +++ b/components/metrics/content/subprocess_metrics_provider_browsertest.cc
@@ -74,18 +74,18 @@ base::PersistentHistogramAllocator* GetMainFrameAllocator() { return get_allocators_by_id().Lookup( - shell()->web_contents()->GetMainFrame()->GetProcess()->GetID()); + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()); } void SimulateRenderProcessExit() { provider_->RenderProcessExited( - shell()->web_contents()->GetMainFrame()->GetProcess(), + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(), content::ChildProcessTerminationInfo()); } void SimulateRenderProcessHostDestroyed() { provider_->RenderProcessHostDestroyed( - shell()->web_contents()->GetMainFrame()->GetProcess()); + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()); } protected: @@ -153,7 +153,7 @@ << " The histogram in the context is " << render_process_histogram; auto* main_frame_process_host = - shell()->web_contents()->GetMainFrame()->GetProcess(); + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(); SimulateRenderProcessHostDestroyed(); // Verify the observer removed. EXPECT_FALSE( @@ -200,7 +200,7 @@ << " The histogram in the context is " << render_process_histogram; auto* main_frame_process_host = - shell()->web_contents()->GetMainFrame()->GetProcess(); + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(); SimulateRenderProcessHostDestroyed(); // Verify the observer removed. EXPECT_FALSE(
diff --git a/components/no_state_prefetch/browser/no_state_prefetch_contents.cc b/components/no_state_prefetch/browser/no_state_prefetch_contents.cc index e5b0b24..666eca6 100644 --- a/components/no_state_prefetch/browser/no_state_prefetch_contents.cc +++ b/components/no_state_prefetch/browser/no_state_prefetch_contents.cc
@@ -210,7 +210,7 @@ // TODO(davidben): This logic assumes each prerender has at most one // process. https://crbug.com/440544 no_state_prefetch_manager()->AddPrerenderProcessHost( - GetMainFrame()->GetProcess()); + GetPrimaryMainFrame()->GetProcess()); NotifyPrefetchStart(); @@ -437,7 +437,7 @@ void NoStatePrefetchContents::DestroyWhenUsingTooManyResources() { if (process_pid_ == base::kNullProcessId) { - RenderFrameHost* rfh = GetMainFrame(); + RenderFrameHost* rfh = GetPrimaryMainFrame(); if (!rfh) return; @@ -484,9 +484,9 @@ } } -RenderFrameHost* NoStatePrefetchContents::GetMainFrame() { +RenderFrameHost* NoStatePrefetchContents::GetPrimaryMainFrame() { return no_state_prefetch_contents_ - ? no_state_prefetch_contents_->GetMainFrame() + ? no_state_prefetch_contents_->GetPrimaryMainFrame() : nullptr; }
diff --git a/components/no_state_prefetch/browser/no_state_prefetch_contents.h b/components/no_state_prefetch/browser/no_state_prefetch_contents.h index 6c92ac0dd..eabd5e4a 100644 --- a/components/no_state_prefetch/browser/no_state_prefetch_contents.h +++ b/components/no_state_prefetch/browser/no_state_prefetch_contents.h
@@ -124,7 +124,7 @@ // it if not. void DestroyWhenUsingTooManyResources(); - content::RenderFrameHost* GetMainFrame(); + content::RenderFrameHost* GetPrimaryMainFrame(); NoStatePrefetchManager* no_state_prefetch_manager() { return no_state_prefetch_manager_;
diff --git a/components/optimization_guide/content/browser/page_text_observer_unittest.cc b/components/optimization_guide/content/browser/page_text_observer_unittest.cc index e1b480c6..97f8acf 100644 --- a/components/optimization_guide/content/browser/page_text_observer_unittest.cc +++ b/components/optimization_guide/content/browser/page_text_observer_unittest.cc
@@ -205,7 +205,8 @@ } void CallDidFinishLoad() { - PageTextObserver::DidFinishLoad(web_contents()->GetMainFrame(), GURL()); + PageTextObserver::DidFinishLoad(web_contents()->GetPrimaryMainFrame(), + GURL()); } private: @@ -273,7 +274,7 @@ content::NavigationSimulator::NavigateAndCommitFromDocument( GURL("http://subframe.com"), - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); EXPECT_FALSE(consumer.was_called()); @@ -1112,7 +1113,7 @@ // Activate the prerendered page. content::NavigationSimulator::NavigateAndCommitFromDocument( - prerender_url, web_contents()->GetMainFrame()); + prerender_url, web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(prerender_frame->GetLifecycleState(), content::RenderFrameHost::LifecycleState::kActive); EXPECT_TRUE(consumer.was_called());
diff --git a/components/page_info/page_info.cc b/components/page_info/page_info.cc index c890eaff..8af14cd 100644 --- a/components/page_info/page_info.cc +++ b/components/page_info/page_info.cc
@@ -419,7 +419,7 @@ if (web_contents_) { ukm::builders::PageInfoBubble( - web_contents_->GetMainFrame()->GetPageUkmSourceId()) + web_contents_->GetPrimaryMainFrame()->GetPageUkmSourceId()) .SetActionTaken(action) .Record(ukm::UkmRecorder::Get()); } @@ -1288,7 +1288,7 @@ // anything? DCHECK(web_contents_); return content_settings::PageSpecificContentSettings::GetForFrame( - web_contents_->GetMainFrame()); + web_contents_->GetPrimaryMainFrame()); } bool PageInfo::HasContentSettingChangedViaPageInfo(ContentSettingsType type) {
diff --git a/components/page_load_metrics/browser/metrics_web_contents_observer.cc b/components/page_load_metrics/browser/metrics_web_contents_observer.cc index 83e1b85c..6b076d8c 100644 --- a/components/page_load_metrics/browser/metrics_web_contents_observer.cc +++ b/components/page_load_metrics/browser/metrics_web_contents_observer.cc
@@ -249,7 +249,8 @@ if (embedder_interface_->IsNoStatePrefetch(web_contents)) in_foreground_ = false; - RegisterInputEventObserver(web_contents->GetMainFrame()->GetRenderViewHost()); + RegisterInputEventObserver( + web_contents->GetPrimaryMainFrame()->GetRenderViewHost()); } void MetricsWebContentsObserver::WillStartNavigationRequestImpl(
diff --git a/components/page_load_metrics/browser/metrics_web_contents_observer_unittest.cc b/components/page_load_metrics/browser/metrics_web_contents_observer_unittest.cc index 824c385..5bcd6eff 100644 --- a/components/page_load_metrics/browser/metrics_web_contents_observer_unittest.cc +++ b/components/page_load_metrics/browser/metrics_web_contents_observer_unittest.cc
@@ -112,7 +112,7 @@ } void SimulateTimingUpdate(const mojom::PageLoadTiming& timing) { - SimulateTimingUpdate(timing, web_contents()->GetMainFrame()); + SimulateTimingUpdate(timing, web_contents()->GetPrimaryMainFrame()); } void SimulateCpuTimingUpdate(const mojom::CpuTiming& timing, @@ -1294,14 +1294,14 @@ auto navigation_simulator = content::NavigationSimulator::CreateRendererInitiated( - main_resource_url, web_contents()->GetMainFrame()); + main_resource_url, web_contents()->GetPrimaryMainFrame()); navigation_simulator->Start(); navigation_simulator->Commit(); const auto request_id = navigation_simulator->GetGlobalRequestID(); observer()->ResourceLoadComplete( - web_contents()->GetMainFrame(), request_id, + web_contents()->GetPrimaryMainFrame(), request_id, *CreateResourceLoadInfo(main_resource_url, network::mojom::RequestDestination::kFrame)); EXPECT_EQ(1u, loaded_resources().size()); @@ -1313,7 +1313,7 @@ // Deliver a second main frame resource. This one should be ignored, since the // specified |request_id| is no longer associated with any tracked page loads. observer()->ResourceLoadComplete( - web_contents()->GetMainFrame(), request_id, + web_contents()->GetPrimaryMainFrame(), request_id, *CreateResourceLoadInfo(main_resource_url, network::mojom::RequestDestination::kFrame)); EXPECT_EQ(1u, loaded_resources().size()); @@ -1326,7 +1326,7 @@ web_contents(), GURL(kDefaultTestUrl)); GURL loaded_resource_url("http://www.other.com/"); observer()->ResourceLoadComplete( - web_contents()->GetMainFrame(), content::GlobalRequestID(), + web_contents()->GetPrimaryMainFrame(), content::GlobalRequestID(), *CreateResourceLoadInfo(loaded_resource_url, network::mojom::RequestDestination::kScript)); @@ -1340,7 +1340,7 @@ content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); - content::RenderFrameHost* old_rfh = web_contents()->GetMainFrame(); + content::RenderFrameHost* old_rfh = web_contents()->GetPrimaryMainFrame(); content::LeaveInPendingDeletionState(old_rfh); content::NavigationSimulator::NavigateAndCommitFromBrowser( @@ -1361,7 +1361,7 @@ web_contents(), GURL(kDefaultTestUrl)); GURL loaded_resource_url("data:text/html,Hello world"); observer()->ResourceLoadComplete( - web_contents()->GetMainFrame(), content::GlobalRequestID(), + web_contents()->GetPrimaryMainFrame(), content::GlobalRequestID(), *CreateResourceLoadInfo(loaded_resource_url, network::mojom::RequestDestination::kScript));
diff --git a/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.cc b/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.cc index 166bbdd96..d68306d1 100644 --- a/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -613,7 +613,8 @@ content::RenderFrameHost* render_frame_host, const gfx::Rect& main_frame_intersection_rect) { int frame_tree_node_id = render_frame_host->GetFrameTreeNodeId(); - if (render_frame_host == GetDelegate().GetWebContents()->GetMainFrame()) { + if (render_frame_host == + GetDelegate().GetWebContents()->GetPrimaryMainFrame()) { page_ad_density_tracker_.UpdateMainFrameRect(main_frame_intersection_rect); return; } @@ -661,7 +662,7 @@ // violations after the first are ignored. Ad frame violations are // attributed to the main frame url. throttle_manager->OnAdsViolationTriggered( - GetDelegate().GetWebContents()->GetMainFrame(), + GetDelegate().GetWebContents()->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation:: kMobileAdDensityByHeightAbove30); } @@ -1211,7 +1212,7 @@ // violations after the first are ignored. Ad frame violations are // attributed to the main frame url. throttle_manager->OnAdsViolationTriggered( - GetDelegate().GetWebContents()->GetMainFrame(), + GetDelegate().GetWebContents()->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation:: kHeavyAdsInterventionAtHostLimit); }
diff --git a/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc index 6b6a16b6..215ab44 100644 --- a/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc
@@ -482,7 +482,7 @@ // Returns the final RenderFrameHost after navigation commits. RenderFrameHost* NavigateMainFrame(const std::string& url) { - return NavigateFrame(url, web_contents()->GetMainFrame()); + return NavigateFrame(url, web_contents()->GetPrimaryMainFrame()); } void OnCpuTimingUpdate(RenderFrameHost* render_frame_host, @@ -1245,8 +1245,8 @@ TEST_P(AdsPageLoadMetricsObserverTest, MainFrameResource) { // Start main-frame navigation - auto navigation_simulator = - CreateNavigationSimulator(kNonAdUrl, web_contents()->GetMainFrame()); + auto navigation_simulator = CreateNavigationSimulator( + kNonAdUrl, web_contents()->GetPrimaryMainFrame()); navigation_simulator->Start(); navigation_simulator->Commit(); @@ -1290,8 +1290,8 @@ TEST_P(AdsPageLoadMetricsObserverTest, NoBytesLoaded_NoHistogramsRecorded) { // Start main-frame navigation - auto navigation_simulator = - CreateNavigationSimulator(kNonAdUrl, web_contents()->GetMainFrame()); + auto navigation_simulator = CreateNavigationSimulator( + kNonAdUrl, web_contents()->GetPrimaryMainFrame()); navigation_simulator->Start(); navigation_simulator->Commit();
diff --git a/components/page_load_metrics/browser/observers/back_forward_cache_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/back_forward_cache_page_load_metrics_observer_unittest.cc index e0d7b0f..bffe402a 100644 --- a/components/page_load_metrics/browser/observers/back_forward_cache_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/back_forward_cache_page_load_metrics_observer_unittest.cc
@@ -133,7 +133,7 @@ navigation_handle_.set_is_served_from_bfcache(true); tester()->SimulateMetadataUpdate(NonAmpMetadata(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); observer_->OnRestoreFromBackForwardCache(timing_, &navigation_handle_); AssertHistoryNavigationRecordedAmpNavigation(false); @@ -145,7 +145,7 @@ navigation_handle_.set_is_served_from_bfcache(true); tester()->SimulateMetadataUpdate(AmpMetadata(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); observer_->OnRestoreFromBackForwardCache(timing_, &navigation_handle_); AssertHistoryNavigationRecordedAmpNavigation(true); @@ -157,7 +157,7 @@ navigation_handle_.set_is_served_from_bfcache(false); tester()->SimulateMetadataUpdate(NonAmpMetadata(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); // Since there was no call to observer_->OnRestoreFromBackForwardCache, there // should be no HistoryNavigation UKM entry.
diff --git a/components/page_load_metrics/browser/observers/core/uma_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/core/uma_page_load_metrics_observer_unittest.cc index 1ed74d21..d58fde4 100644 --- a/components/page_load_metrics/browser/observers/core/uma_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/core/uma_page_load_metrics_observer_unittest.cc
@@ -678,9 +678,11 @@ TEST_F(UmaPageLoadMetricsObserverTest, CpuUsageCounted) { NavigateAndCommit(GURL(kDefaultTestUrl)); - OnCpuTimingUpdate(web_contents()->GetMainFrame(), base::Milliseconds(750)); + OnCpuTimingUpdate(web_contents()->GetPrimaryMainFrame(), + base::Milliseconds(750)); web_contents()->WasHidden(); // Set the web contents as backgrounded. - OnCpuTimingUpdate(web_contents()->GetMainFrame(), base::Milliseconds(250)); + OnCpuTimingUpdate(web_contents()->GetPrimaryMainFrame(), + base::Milliseconds(250)); NavigateAndCommit(GURL(kDefaultTestUrl2)); tester()->histogram_tester().ExpectUniqueSample( @@ -784,7 +786,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -827,7 +829,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -864,7 +866,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -910,7 +912,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -955,7 +957,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -996,7 +998,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -1044,7 +1046,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -1399,7 +1401,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL("https://google.com/subframe.html"), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Notify that memory measurements are available for each frame. @@ -1430,12 +1432,12 @@ RenderFrameHost* subframe1 = NavigationSimulator::NavigateAndCommitFromDocument( GURL("https://google.com/subframe.html"), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe1")); RenderFrameHost* subframe2 = NavigationSimulator::NavigateAndCommitFromDocument( GURL("https://google.com/subframe2.html"), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe2")); RenderFrameHost* subframe3 = NavigationSimulator::NavigateAndCommitFromDocument( @@ -1502,7 +1504,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -1545,7 +1547,7 @@ RenderFrameHost* subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSubframeTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe")); // Simulate timing updates in the main frame and the subframe. @@ -1599,12 +1601,12 @@ RenderFrameHost* first_party_subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kSameSiteSubFrameTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe1")); RenderFrameHost* cross_site_subframe = NavigationSimulator::NavigateAndCommitFromDocument( GURL(kCrossSiteSubFrameTestUrl), - RenderFrameHostTester::For(web_contents()->GetMainFrame()) + RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendChild("subframe2")); // Simulate timing updates in the main frame and the subframe.
diff --git a/components/page_load_metrics/browser/observers/fenced_frames_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/fenced_frames_page_load_metrics_observer_unittest.cc index 013f8eda8..9e709e5 100644 --- a/components/page_load_metrics/browser/observers/fenced_frames_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/fenced_frames_page_load_metrics_observer_unittest.cc
@@ -82,7 +82,7 @@ NavigateAndCommit(GURL(kTestUrl)); content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); ASSERT_TRUE(fenced_frame_root->IsFencedFrameRoot()); @@ -129,7 +129,7 @@ web_contents()->WasHidden(); content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); ASSERT_TRUE(fenced_frame_root->IsFencedFrameRoot());
diff --git a/components/page_load_metrics/browser/observers/page_load_metrics_observer_tester.cc b/components/page_load_metrics/browser/observers/page_load_metrics_observer_tester.cc index 89758e4..c2e00f04 100644 --- a/components/page_load_metrics/browser/observers/page_load_metrics_observer_tester.cc +++ b/components/page_load_metrics/browser/observers/page_load_metrics_observer_tester.cc
@@ -125,7 +125,7 @@ void PageLoadMetricsObserverTester::SimulateTimingUpdate( const mojom::PageLoadTiming& timing) { - SimulateTimingUpdate(timing, web_contents()->GetMainFrame()); + SimulateTimingUpdate(timing, web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateTimingUpdate( @@ -139,7 +139,7 @@ void PageLoadMetricsObserverTester::SimulateCpuTimingUpdate( const mojom::CpuTiming& cpu_timing) { - SimulateCpuTimingUpdate(cpu_timing, web_contents()->GetMainFrame()); + SimulateCpuTimingUpdate(cpu_timing, web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateCpuTimingUpdate( @@ -155,7 +155,8 @@ void PageLoadMetricsObserverTester::SimulateInputTimingUpdate( const mojom::InputTiming& input_timing) { - SimulateInputTimingUpdate(input_timing, web_contents()->GetMainFrame()); + SimulateInputTimingUpdate(input_timing, + web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateMobileFriendlinessUpdate( @@ -186,7 +187,7 @@ SimulatePageLoadTimingUpdate( timing, metadata, /* new_features= */ {}, mojom::FrameRenderDataUpdate(), mojom::CpuTiming(), mojom::InputTiming(), blink::MobileFriendliness(), - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateMetadataUpdate( @@ -205,12 +206,12 @@ SimulatePageLoadTimingUpdate( mojom::PageLoadTiming(), mojom::FrameMetadata(), new_features, mojom::FrameRenderDataUpdate(), mojom::CpuTiming(), mojom::InputTiming(), - blink::MobileFriendliness(), web_contents()->GetMainFrame()); + blink::MobileFriendliness(), web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateRenderDataUpdate( const mojom::FrameRenderDataUpdate& render_data) { - SimulateRenderDataUpdate(render_data, web_contents()->GetMainFrame()); + SimulateRenderDataUpdate(render_data, web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateRenderDataUpdate( @@ -247,7 +248,8 @@ void PageLoadMetricsObserverTester::SimulateResourceDataUseUpdate( const std::vector<mojom::ResourceDataUpdatePtr>& resources) { - SimulateResourceDataUseUpdate(resources, web_contents()->GetMainFrame()); + SimulateResourceDataUseUpdate(resources, + web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateResourceDataUseUpdate( @@ -294,7 +296,7 @@ resource_load_info.load_timing_info.request_start = base::TimeTicks::Now(); metrics_web_contents_observer_->ResourceLoadComplete( - web_contents()->GetMainFrame(), request_id, resource_load_info); + web_contents()->GetPrimaryMainFrame(), request_id, resource_load_info); } void PageLoadMetricsObserverTester::SimulateFrameReceivedUserActivation( @@ -313,7 +315,7 @@ } void PageLoadMetricsObserverTester::SimulateMediaPlayed() { - SimulateMediaPlayed(web_contents()->GetMainFrame()); + SimulateMediaPlayed(web_contents()->GetPrimaryMainFrame()); } void PageLoadMetricsObserverTester::SimulateMediaPlayed( @@ -327,7 +329,8 @@ void PageLoadMetricsObserverTester::SimulateCookieAccess( const content::CookieAccessDetails& details) { metrics_web_contents_observer_->OnCookiesAccessed( - metrics_web_contents_observer_->web_contents()->GetMainFrame(), details); + metrics_web_contents_observer_->web_contents()->GetPrimaryMainFrame(), + details); } void PageLoadMetricsObserverTester::SimulateStorageAccess( @@ -336,8 +339,8 @@ bool blocked_by_policy, StorageType storage_type) { metrics_web_contents_observer_->OnStorageAccessed( - metrics_web_contents_observer_->web_contents()->GetMainFrame(), url, - first_party_url, blocked_by_policy, storage_type); + metrics_web_contents_observer_->web_contents()->GetPrimaryMainFrame(), + url, first_party_url, blocked_by_policy, storage_type); } void PageLoadMetricsObserverTester::SimulateMobileFriendlinessUpdate( @@ -345,7 +348,7 @@ SimulatePageLoadTimingUpdate( mojom::PageLoadTiming(), mojom::FrameMetadata(), /* new_features= */ {}, mojom::FrameRenderDataUpdate(), mojom::CpuTiming(), mojom::InputTiming(), - mobile_friendliness, web_contents()->GetMainFrame()); + mobile_friendliness, web_contents()->GetPrimaryMainFrame()); } const PageLoadMetricsObserverDelegate&
diff --git a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc index e70b7dc5..faa74c4 100644 --- a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc
@@ -88,7 +88,8 @@ if (WithFencedFrames()) { content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For( + web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); ASSERT_TRUE(fenced_frame_root->IsFencedFrameRoot());
diff --git a/components/page_load_metrics/browser/page_load_metrics_forward_observer_unittest.cc b/components/page_load_metrics/browser/page_load_metrics_forward_observer_unittest.cc index b2ce2da..8b6e1da 100644 --- a/components/page_load_metrics/browser/page_load_metrics_forward_observer_unittest.cc +++ b/components/page_load_metrics/browser/page_load_metrics_forward_observer_unittest.cc
@@ -110,7 +110,7 @@ // Add a fenced frame. content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); { auto simulator = content::NavigationSimulator::CreateRendererInitiated(
diff --git a/components/page_load_metrics/browser/page_load_metrics_memory_tracker_unittest.cc b/components/page_load_metrics/browser/page_load_metrics_memory_tracker_unittest.cc index a4f90c64..e7c87ba 100644 --- a/components/page_load_metrics/browser/page_load_metrics_memory_tracker_unittest.cc +++ b/components/page_load_metrics/browser/page_load_metrics_memory_tracker_unittest.cc
@@ -151,7 +151,7 @@ // Returns the final RenderFrameHost after navigation commits. content::RenderFrameHost* NavigateMainFrame(const std::string& url) { - return NavigateFrame(url, web_contents()->GetMainFrame()); + return NavigateFrame(url, web_contents()->GetPrimaryMainFrame()); } // Returns the final RenderFrameHost after navigation commits.
diff --git a/components/page_load_metrics/browser/page_load_tracker_unittest.cc b/components/page_load_metrics/browser/page_load_tracker_unittest.cc index 89e3581..0a3f8a4 100644 --- a/components/page_load_metrics/browser/page_load_tracker_unittest.cc +++ b/components/page_load_metrics/browser/page_load_tracker_unittest.cc
@@ -168,7 +168,7 @@ // Add a fenced frame. content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); { const char kFencedFramesUrl[] = "https://a.test/fenced_frames"; @@ -246,7 +246,7 @@ // Add a fenced frame. content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); { auto simulator = content::NavigationSimulator::CreateRendererInitiated( @@ -318,7 +318,7 @@ // Add a fenced frame. content::RenderFrameHost* fenced_frame_root = - content::RenderFrameHostTester::For(web_contents()->GetMainFrame()) + content::RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame()) ->AppendFencedFrame(); auto simulator = content::NavigationSimulator::CreateRendererInitiated( GURL(kFencedFramesUrl), fenced_frame_root);
diff --git a/components/paint_preview/browser/paint_preview_base_service.cc b/components/paint_preview/browser/paint_preview_base_service.cc index 9d12df9..d607b58a 100644 --- a/components/paint_preview/browser/paint_preview_base_service.cc +++ b/components/paint_preview/browser/paint_preview_base_service.cc
@@ -38,7 +38,7 @@ content::WebContents* web_contents = capture_params.web_contents; content::RenderFrameHost* render_frame_host = capture_params.render_frame_host ? capture_params.render_frame_host - : web_contents->GetMainFrame(); + : web_contents->GetPrimaryMainFrame(); if (policy_ && !policy_->SupportedForContents(web_contents)) { std::move(callback).Run(CaptureStatus::kContentUnsupported, {}); return; @@ -57,7 +57,7 @@ } params.inner.clip_rect = capture_params.clip_rect; params.inner.is_main_frame = - (render_frame_host == web_contents->GetMainFrame()); + (render_frame_host == web_contents->GetPrimaryMainFrame()); params.inner.capture_links = capture_params.capture_links; params.inner.max_capture_size = capture_params.max_per_capture_size; params.inner.max_decoded_image_size_bytes =
diff --git a/components/paint_preview/browser/paint_preview_client_unittest.cc b/components/paint_preview/browser/paint_preview_client_unittest.cc index 2875e69..be5dcad 100644 --- a/components/paint_preview/browser/paint_preview_client_unittest.cc +++ b/components/paint_preview/browser/paint_preview_client_unittest.cc
@@ -137,7 +137,7 @@ void OverrideInterface(MockPaintPreviewRecorder* service) { blink::AssociatedInterfaceProvider* remote_interfaces = - web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces(); + web_contents()->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( mojom::PaintPreviewRecorder::Name_, base::BindRepeating(&MockPaintPreviewRecorder::BindRequest,
diff --git a/components/password_manager/content/browser/content_password_manager_driver_unittest.cc b/components/password_manager/content/browser/content_password_manager_driver_unittest.cc index 68c95a6..8ba8d720 100644 --- a/components/password_manager/content/browser/content_password_manager_driver_unittest.cc +++ b/components/password_manager/content/browser/content_password_manager_driver_unittest.cc
@@ -199,7 +199,7 @@ .WillByDefault(Return(&log_manager_)); blink::AssociatedInterfaceProvider* remote_interfaces = - web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces(); + web_contents()->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( autofill::mojom::PasswordAutofillAgent::Name_, base::BindRepeating(&FakePasswordAutofillAgent::BindPendingReceiver, @@ -286,13 +286,14 @@ autofill::FormData form; autofill::FormData form2 = GetFormWithFrameAndFormMetaData(main_rfh(), form); - EXPECT_EQ(form2.host_frame, - autofill::LocalFrameToken( - web_contents()->GetMainFrame()->GetFrameToken().value())); + EXPECT_EQ( + form2.host_frame, + autofill::LocalFrameToken( + web_contents()->GetPrimaryMainFrame()->GetFrameToken().value())); EXPECT_EQ(form2.url, GURL("https://hostname/path")); EXPECT_EQ(form2.full_url, GURL("https://hostname/path?query#hash")); EXPECT_EQ(form2.main_frame_origin, - web_contents()->GetMainFrame()->GetLastCommittedOrigin()); + web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin()); EXPECT_EQ(form2.main_frame_origin, url::Origin::CreateFromNormalizedTuple("https", "hostname", 443)); } @@ -321,7 +322,7 @@ expected_form.main_frame_origin = url::Origin::CreateFromNormalizedTuple("https", "hostname", 443); expected_form.host_frame = autofill::LocalFrameToken( - web_contents()->GetMainFrame()->GetFrameToken().value()); + web_contents()->GetPrimaryMainFrame()->GetFrameToken().value()); return expected_form; } @@ -428,7 +429,7 @@ EXPECT_EQ(form_in_fenced_frame.main_frame_origin, fenced_frame_root->GetLastCommittedOrigin()); EXPECT_NE(form_in_fenced_frame.main_frame_origin, - web_contents()->GetMainFrame()->GetLastCommittedOrigin()); + web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin()); EXPECT_EQ(form_in_fenced_frame.main_frame_origin, url::Origin::CreateFromNormalizedTuple("https", "hostname", 443)); }
diff --git a/components/password_manager/core/browser/password_autofill_manager.cc b/components/password_manager/core/browser/password_autofill_manager.cc index 8b69baa..6bcfd28a 100644 --- a/components/password_manager/core/browser/password_autofill_manager.cc +++ b/components/password_manager/core/browser/password_autofill_manager.cc
@@ -419,10 +419,11 @@ autofill_client_->GetReopenPopupArgs())); } -void PasswordAutofillManager::DidAcceptSuggestion(const std::u16string& value, - int frontend_id, - const std::string& backend_id, - int position) { +void PasswordAutofillManager::DidAcceptSuggestion( + const std::u16string& value, + int frontend_id, + const autofill::Suggestion::Payload& payload, + int position) { using metrics_util::PasswordDropdownSelectedOption; if (frontend_id == autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY) { password_client_->GeneratePassword(PasswordGenerationType::kAutomatic); @@ -467,7 +468,9 @@ PasswordDropdownSelectedOption::kWebAuthn, password_client_->IsIncognito()); password_client_->GetWebAuthnCredentialsDelegate() - ->SelectWebAuthnCredential(backend_id); + ->SelectWebAuthnCredential(absl::holds_alternative<std::string>(payload) + ? absl::get<std::string>(payload) + : std::string()); } else { metrics_util::LogPasswordDropdownItemSelected( PasswordDropdownSelectedOption::kPassword,
diff --git a/components/password_manager/core/browser/password_autofill_manager.h b/components/password_manager/core/browser/password_autofill_manager.h index c4599c8..fcbae65 100644 --- a/components/password_manager/core/browser/password_autofill_manager.h +++ b/components/password_manager/core/browser/password_autofill_manager.h
@@ -15,6 +15,7 @@ #include "base/types/strong_alias.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/ui/autofill_popup_delegate.h" +#include "components/autofill/core/browser/ui/suggestion.h" #include "components/autofill/core/common/password_form_fill_data.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" @@ -58,7 +59,7 @@ const std::string& backend_id) override; void DidAcceptSuggestion(const std::u16string& value, int frontend_id, - const std::string& backend_id, + const autofill::Suggestion::Payload& payload, int position) override; bool GetDeletionConfirmationText(const std::u16string& value, int frontend_id,
diff --git a/components/password_manager/core/browser/password_autofill_manager_unittest.cc b/components/password_manager/core/browser/password_autofill_manager_unittest.cc index 34291e6..da8b395a 100644 --- a/components/password_manager/core/browser/password_autofill_manager_unittest.cc +++ b/components/password_manager/core/browser/password_autofill_manager_unittest.cc
@@ -1839,7 +1839,7 @@ const std::u16string kDisplayName = u"Nadeshiko Kagamihara"; autofill::Suggestion webauthn_credential(kDisplayName); webauthn_credential.frontend_id = autofill::POPUP_ITEM_ID_WEBAUTHN_CREDENTIAL; - webauthn_credential.backend_id = kId; + webauthn_credential.payload = kId; webauthn_credential.label = kName; ON_CALL(webauthn_credentials_delegate, IsWebAuthnAutofillEnabled) .WillByDefault(Return(true)); @@ -1864,7 +1864,7 @@ autofill::POPUP_ITEM_ID_WEBAUTHN_CREDENTIAL, autofill::POPUP_ITEM_ID_USERNAME_ENTRY, autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY))); - EXPECT_EQ(open_args.suggestions[0].backend_id, kId); + EXPECT_EQ(absl::get<std::string>(open_args.suggestions[0].payload), kId); EXPECT_EQ(open_args.suggestions[0].frontend_id, autofill::POPUP_ITEM_ID_WEBAUTHN_CREDENTIAL); EXPECT_EQ(open_args.suggestions[0].main_text.value, kDisplayName);
diff --git a/components/payments/content/android/journey_logger_android.cc b/components/payments/content/android/journey_logger_android.cc index 44f9eb8..0c71ca2 100644 --- a/components/payments/content/android/journey_logger_android.cc +++ b/components/payments/content/android/journey_logger_android.cc
@@ -197,7 +197,8 @@ content::WebContents::FromJavaWebContents(jweb_contents); DCHECK(web_contents); // Verified in Java before invoking this function. return reinterpret_cast<jlong>(new JourneyLoggerAndroid( - jis_incognito, web_contents->GetMainFrame()->GetPageUkmSourceId())); + jis_incognito, + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId())); } } // namespace payments
diff --git a/components/payments/content/android_payment_app_factory_unittest.cc b/components/payments/content/android_payment_app_factory_unittest.cc index 6732cbe..56fbc531 100644 --- a/components/payments/content/android_payment_app_factory_unittest.cc +++ b/components/payments/content/android_payment_app_factory_unittest.cc
@@ -183,7 +183,7 @@ .WillRepeatedly(testing::Return("com.example.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) @@ -226,7 +226,7 @@ .WillRepeatedly(testing::Return("com.example.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) @@ -266,7 +266,7 @@ .WillRepeatedly(testing::Return("com.twa.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) @@ -302,7 +302,7 @@ .WillRepeatedly(testing::Return("com.example.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) .Times(0); @@ -333,7 +333,7 @@ .WillRepeatedly(testing::Return("com.correct-twa.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) @@ -480,7 +480,7 @@ .WillRepeatedly(testing::Return("com.twa.app")); EXPECT_CALL(delegate_, GetInitiatorRenderFrameHost()) .WillRepeatedly( - testing::Return(delegate_.GetWebContents()->GetMainFrame())); + testing::Return(delegate_.GetWebContents()->GetPrimaryMainFrame())); EXPECT_CALL(delegate_, OnDoneCreatingPaymentApps()); EXPECT_CALL(delegate_, OnPaymentAppCreationError(testing::_, testing::_)) .Times(0);
diff --git a/components/payments/content/android_payment_app_unittest.cc b/components/payments/content/android_payment_app_unittest.cc index 0378ca7..ded1698 100644 --- a/components/payments/content/android_payment_app_unittest.cc +++ b/components/payments/content/android_payment_app_unittest.cc
@@ -54,7 +54,7 @@ GURL("https://top-level-origin.com"), GURL("https://payment-request-origin.com"), "payment-request-id", std::move(description), communication, - web_contents->GetMainFrame()->GetGlobalId()); + web_contents->GetPrimaryMainFrame()->GetGlobalId()); } AndroidPaymentAppTest()
diff --git a/components/payments/content/developer_console_logger.cc b/components/payments/content/developer_console_logger.cc index 3b8974ab..2781b5a3 100644 --- a/components/payments/content/developer_console_logger.cc +++ b/components/payments/content/developer_console_logger.cc
@@ -18,8 +18,8 @@ void DeveloperConsoleLogger::Warn(const std::string& warning_message) const { if (!enabled_) return; - if (web_contents_ && web_contents_->GetMainFrame()) { - web_contents_->GetMainFrame()->AddMessageToConsole( + if (web_contents_ && web_contents_->GetPrimaryMainFrame()) { + web_contents_->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, warning_message); } else { ErrorLogger::Warn(warning_message); @@ -29,8 +29,8 @@ void DeveloperConsoleLogger::Error(const std::string& error_message) const { if (!enabled_) return; - if (web_contents_ && web_contents_->GetMainFrame()) { - web_contents_->GetMainFrame()->AddMessageToConsole( + if (web_contents_ && web_contents_->GetPrimaryMainFrame()) { + web_contents_->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, error_message); } else { ErrorLogger::Error(error_message);
diff --git a/components/payments/content/payment_request_state_unittest.cc b/components/payments/content/payment_request_state_unittest.cc index b499886..77c3033 100644 --- a/components/payments/content/payment_request_state_unittest.cc +++ b/components/payments/content/payment_request_state_unittest.cc
@@ -149,7 +149,7 @@ /*observer=*/nullptr, "en-US"); PaymentAppServiceFactory::SetForTesting(std::move(app_service)); state_ = std::make_unique<PaymentRequestState>( - web_contents_->GetMainFrame(), GURL("https://example.com"), + web_contents_->GetPrimaryMainFrame(), GURL("https://example.com"), GURL("https://example.com/pay"), url::Origin::Create(GURL("https://example.com")), spec_->AsWeakPtr(), weak_ptr_factory_.GetWeakPtr(), "en-US", &test_personal_data_manager_,
diff --git a/components/payments/content/payment_request_web_contents_manager_unittest.cc b/components/payments/content/payment_request_web_contents_manager_unittest.cc index ca92af9..b2a0923a 100644 --- a/components/payments/content/payment_request_web_contents_manager_unittest.cc +++ b/components/payments/content/payment_request_web_contents_manager_unittest.cc
@@ -37,7 +37,7 @@ // PaymentRequest is a DocumentService, whose lifetime is managed by the // RenderFrameHost passed in here. - return new PaymentRequest(web_contents()->GetMainFrame(), + return new PaymentRequest(web_contents()->GetPrimaryMainFrame(), std::move(delegate), std::move(display_manager), std::move(receiver), mode, /*observer_for_testing=*/nullptr);
diff --git a/components/payments/content/secure_payment_confirmation_app_unittest.cc b/components/payments/content/secure_payment_confirmation_app_unittest.cc index 2b0c53a..97a1d9f 100644 --- a/components/payments/content/secure_payment_confirmation_app_unittest.cc +++ b/components/payments/content/secure_payment_confirmation_app_unittest.cc
@@ -56,7 +56,7 @@ MOCK_METHOD1(VerifyChallenge, void(const std::vector<uint8_t>&)); content::RenderFrameHost* GetRenderFrameHost() override { - return web_contents_->GetMainFrame(); + return web_contents_->GetPrimaryMainFrame(); } // Implements an webauthn::InternalAuthenticator method to delegate fields of
diff --git a/components/pdf/browser/pdf_web_contents_helper_browsertest.cc b/components/pdf/browser/pdf_web_contents_helper_browsertest.cc index 02f603b..58e1be4 100644 --- a/components/pdf/browser/pdf_web_contents_helper_browsertest.cc +++ b/components/pdf/browser/pdf_web_contents_helper_browsertest.cc
@@ -53,7 +53,7 @@ // PDFWebContentsHelperClient: content::RenderFrameHost* FindPdfFrame( content::WebContents* contents) override { - return contents->GetMainFrame(); + return contents->GetPrimaryMainFrame(); } void UpdateContentRestrictions(content::WebContents* contents,
diff --git a/components/pdf/renderer/pdf_accessibility_tree.cc b/components/pdf/renderer/pdf_accessibility_tree.cc index c1f00e8..6faecc06 100644 --- a/components/pdf/renderer/pdf_accessibility_tree.cc +++ b/components/pdf/renderer/pdf_accessibility_tree.cc
@@ -7,11 +7,15 @@ #include <algorithm> #include <utility> +#include "base/bind.h" +#include "base/callback.h" #include "base/i18n/break_iterator.h" +#include "base/location.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/notreached.h" #include "base/strings/utf_string_conversion_utils.h" +#include "base/threading/thread_task_runner_handle.h" #include "components/pdf/renderer/pdf_ax_action_target.h" #include "components/strings/grit/components_strings.h" #include "content/public/renderer/render_accessibility.h" @@ -1293,6 +1297,16 @@ } void PdfAccessibilityTree::SetAccessibilityViewportInfo( + chrome_pdf::AccessibilityViewportInfo viewport_info) { + // This call may trigger layout, and ultimately self-deletion; see + // crbug.com/1274376 for details. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&PdfAccessibilityTree::DoSetAccessibilityViewportInfo, + weak_ptr_factory_.GetWeakPtr(), std::move(viewport_info))); +} + +void PdfAccessibilityTree::DoSetAccessibilityViewportInfo( const chrome_pdf::AccessibilityViewportInfo& viewport_info) { zoom_ = viewport_info.zoom; scale_ = viewport_info.scale; @@ -1319,6 +1333,16 @@ } void PdfAccessibilityTree::SetAccessibilityDocInfo( + chrome_pdf::AccessibilityDocInfo doc_info) { + // This call may trigger layout, and ultimately self-deletion; see + // crbug.com/1274376 for details. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&PdfAccessibilityTree::DoSetAccessibilityDocInfo, + weak_ptr_factory_.GetWeakPtr(), std::move(doc_info))); +} + +void PdfAccessibilityTree::DoSetAccessibilityDocInfo( const chrome_pdf::AccessibilityDocInfo& doc_info) { content::RenderAccessibility* render_accessibility = GetRenderAccessibilityIfEnabled(); @@ -1342,6 +1366,21 @@ } void PdfAccessibilityTree::SetAccessibilityPageInfo( + chrome_pdf::AccessibilityPageInfo page_info, + std::vector<chrome_pdf::AccessibilityTextRunInfo> text_runs, + std::vector<chrome_pdf::AccessibilityCharInfo> chars, + chrome_pdf::AccessibilityPageObjects page_objects) { + // This call may trigger layout, and ultimately self-deletion; see + // crbug.com/1274376 for details. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&PdfAccessibilityTree::DoSetAccessibilityPageInfo, + weak_ptr_factory_.GetWeakPtr(), std::move(page_info), + std::move(text_runs), std::move(chars), + std::move(page_objects))); +} + +void PdfAccessibilityTree::DoSetAccessibilityPageInfo( const chrome_pdf::AccessibilityPageInfo& page_info, const std::vector<chrome_pdf::AccessibilityTextRunInfo>& text_runs, const std::vector<chrome_pdf::AccessibilityCharInfo>& chars,
diff --git a/components/pdf/renderer/pdf_accessibility_tree.h b/components/pdf/renderer/pdf_accessibility_tree.h index 18a5e81..9506d33b 100644 --- a/components/pdf/renderer/pdf_accessibility_tree.h +++ b/components/pdf/renderer/pdf_accessibility_tree.h
@@ -69,14 +69,14 @@ // chrome_pdf::PdfAccessibilityDataHandler: void SetAccessibilityViewportInfo( - const chrome_pdf::AccessibilityViewportInfo& viewport_info) override; + chrome_pdf::AccessibilityViewportInfo viewport_info) override; void SetAccessibilityDocInfo( - const chrome_pdf::AccessibilityDocInfo& doc_info) override; + chrome_pdf::AccessibilityDocInfo doc_info) override; void SetAccessibilityPageInfo( - const chrome_pdf::AccessibilityPageInfo& page_info, - const std::vector<chrome_pdf::AccessibilityTextRunInfo>& text_runs, - const std::vector<chrome_pdf::AccessibilityCharInfo>& chars, - const chrome_pdf::AccessibilityPageObjects& page_objects) override; + chrome_pdf::AccessibilityPageInfo page_info, + std::vector<chrome_pdf::AccessibilityTextRunInfo> text_runs, + std::vector<chrome_pdf::AccessibilityCharInfo> chars, + chrome_pdf::AccessibilityPageObjects page_objects) override; void HandleAction(const chrome_pdf::AccessibilityActionData& action_data); absl::optional<AnnotationInfo> GetPdfAnnotationInfoFromAXNode( @@ -118,6 +118,16 @@ // Update the AXTreeData when the selected range changed. void UpdateAXTreeDataFromSelection(); + void DoSetAccessibilityViewportInfo( + const chrome_pdf::AccessibilityViewportInfo& viewport_info); + void DoSetAccessibilityDocInfo( + const chrome_pdf::AccessibilityDocInfo& doc_info); + void DoSetAccessibilityPageInfo( + const chrome_pdf::AccessibilityPageInfo& page_info, + const std::vector<chrome_pdf::AccessibilityTextRunInfo>& text_runs, + const std::vector<chrome_pdf::AccessibilityCharInfo>& chars, + const chrome_pdf::AccessibilityPageObjects& page_objects); + // Given a 0-based page index and 0-based character index within a page, // find the node ID of the associated static text AXNode, and the character // index within that text node. Used to find the start and end of the
diff --git a/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc b/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc index ceab43f..88894ac 100644 --- a/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc +++ b/components/pdf/renderer/pdf_accessibility_tree_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/callback.h" +#include "base/location.h" #include "base/path_service.h" +#include "base/run_loop.h" #include "base/test/scoped_feature_list.h" +#include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/pdf/renderer/pdf_accessibility_tree.h" #include "components/strings/grit/components_strings.h" @@ -103,6 +107,14 @@ chrome_pdf::AccessibilityActionData received_action_data_; }; +// Waits for tasks posted to the thread's task runner to complete. +void WaitForThreadTasks() { + base::RunLoop run_loop; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + run_loop.QuitClosure()); + run_loop.Run(); +} + } // namespace class PdfAccessibilityTreeTest : public content::RenderViewTest { @@ -156,6 +168,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); EXPECT_EQ(ax::mojom::Role::kPdfRoot, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -171,6 +184,7 @@ pdf_accessibility_tree.SetAccessibilityViewportInfo(viewport_info_); pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); + WaitForThreadTasks(); // Disable accessibility while the PDF is loading, make sure this // doesn't crash. @@ -178,6 +192,7 @@ pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); } TEST_F(PdfAccessibilityTreeTest, TestPdfAccessibilityTreeReload) { @@ -201,6 +216,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); ASSERT_TRUE(root_node); @@ -263,6 +279,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -374,6 +391,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -459,6 +477,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -580,6 +599,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -736,6 +756,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -924,6 +945,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -1114,6 +1136,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + /* * Expected tree structure * Document @@ -1320,6 +1344,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); /* * Expected tree structure @@ -1442,6 +1467,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1486,6 +1513,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1521,6 +1550,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1563,6 +1594,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1596,6 +1629,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1643,6 +1678,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1679,6 +1716,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + // In case of invalid data, only the initialized data should be in the tree. ASSERT_EQ(ax::mojom::Role::kUnknown, pdf_accessibility_tree.GetRoot()->GetRole()); @@ -1699,6 +1738,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); std::unique_ptr<ui::AXActionTarget> pdf_action_target = @@ -1761,6 +1801,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); std::unique_ptr<ui::AXActionTarget> pdf_action_target = @@ -1822,6 +1863,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); const std::vector<ui::AXNode*>& page_nodes = root_node->children(); ASSERT_EQ(1u, page_nodes.size()); @@ -1867,6 +1910,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); std::unique_ptr<ui::AXActionTarget> pdf_action_target = @@ -1908,6 +1952,7 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); viewport_info_.zoom = 1.0; viewport_info_.scale = 1.0; @@ -1915,6 +1960,8 @@ viewport_info_.offset = gfx::Point(57, 0); pdf_accessibility_tree.SetAccessibilityViewportInfo(viewport_info_); + WaitForThreadTasks(); + ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); ASSERT_TRUE(root_node); ASSERT_EQ(1u, root_node->children().size()); @@ -1935,6 +1982,7 @@ viewport_info_.zoom = new_zoom; viewport_info_.scale = new_device_scale; pdf_accessibility_tree.SetAccessibilityViewportInfo(viewport_info_); + WaitForThreadTasks(); rect = para_node->data().relative_bounds.bounds; transform = root_node->data().relative_bounds.transform.get(); @@ -1959,6 +2007,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); ASSERT_TRUE(root_node); const std::vector<ui::AXNode*>& page_nodes = root_node->children(); @@ -2053,6 +2103,8 @@ pdf_accessibility_tree.SetAccessibilityDocInfo(doc_info_); pdf_accessibility_tree.SetAccessibilityPageInfo(page_info_, text_runs_, chars_, page_objects_); + WaitForThreadTasks(); + ui::AXNode* root_node = pdf_accessibility_tree.GetRoot(); ASSERT_TRUE(root_node);
diff --git a/components/performance_manager/graph/policies/process_priority_policy_unittest.cc b/components/performance_manager/graph/policies/process_priority_policy_unittest.cc index 444d6df..c5c69e46 100644 --- a/components/performance_manager/graph/policies/process_priority_policy_unittest.cc +++ b/components/performance_manager/graph/policies/process_priority_policy_unittest.cc
@@ -112,7 +112,7 @@ // Set the active contents in the RenderViewHostTestHarness. SetContents(CreateTestWebContents()); - auto* rvh = web_contents()->GetMainFrame()->GetRenderViewHost(); + auto* rvh = web_contents()->GetPrimaryMainFrame()->GetRenderViewHost(); DCHECK(rvh); auto* rph = rvh->GetProcess(); DCHECK(rph);
diff --git a/components/performance_manager/performance_manager_browsertest.cc b/components/performance_manager/performance_manager_browsertest.cc index 31feecd..0f21d74 100644 --- a/components/performance_manager/performance_manager_browsertest.cc +++ b/components/performance_manager/performance_manager_browsertest.cc
@@ -43,7 +43,7 @@ content::WebContents* contents = shell()->web_contents(); ASSERT_EQ(contents, old_contents); ASSERT_EQ(contents->GetLastCommittedURL().possibly_invalid_spec(), kUrl); - content::RenderFrameHost* rfh = contents->GetMainFrame(); + content::RenderFrameHost* rfh = contents->GetPrimaryMainFrame(); ASSERT_TRUE(rfh->IsRenderFrameLive()); base::WeakPtr<FrameNode> frame_node = @@ -152,7 +152,7 @@ embedded_test_server()->GetURL("/fenced_frames/title1.html"); content::RenderFrameHost* fenced_frame_host = fenced_frame_test_helper().CreateFencedFrame( - GetWebContents()->GetMainFrame(), fenced_frame_url); + GetWebContents()->GetPrimaryMainFrame(), fenced_frame_url); // Jump into the graph and make sure |fenced_frame_host| does not have a // parent frame node.
diff --git a/components/performance_manager/performance_manager_tab_helper.cc b/components/performance_manager/performance_manager_tab_helper.cc index a8ab8dc..3be2b58f 100644 --- a/components/performance_manager/performance_manager_tab_helper.cc +++ b/components/performance_manager/performance_manager_tab_helper.cc
@@ -43,7 +43,7 @@ // will be an "original opener". if (content::WebContents* original_opener_wc = web_contents->GetFirstWebContentsInLiveOriginalOpenerChain()) { - opener_rfh = original_opener_wc->GetMainFrame(); + opener_rfh = original_opener_wc->GetPrimaryMainFrame(); } } @@ -86,7 +86,7 @@ // We have an early WebContents creation hook so should see it when there is // only a single frame, and it is not yet created. We sanity check that here. #if DCHECK_IS_ON() - DCHECK(!web_contents->GetMainFrame()->IsRenderFrameLive()); + DCHECK(!web_contents->GetPrimaryMainFrame()->IsRenderFrameLive()); size_t frame_count = 0; web_contents->ForEachRenderFrameHost(base::BindRepeating( [](size_t* frame_count, content::RenderFrameHost* render_frame_host) { @@ -106,7 +106,7 @@ web_contents->IsCurrentlyAudible(), web_contents->GetLastActiveTime(), // TODO(crbug.com/1211368): Support MPArch fully! PageNode::PageState::kActive); - content::RenderFrameHost* main_rfh = web_contents->GetMainFrame(); + content::RenderFrameHost* main_rfh = web_contents->GetPrimaryMainFrame(); DCHECK(main_rfh); page->main_frame_tree_node_id = main_rfh->GetFrameTreeNodeId(); primary_page_ = page.get();
diff --git a/components/performance_manager/performance_manager_tab_helper_unittest.cc b/components/performance_manager/performance_manager_tab_helper_unittest.cc index 6d829aa..b9b42eb 100644 --- a/components/performance_manager/performance_manager_tab_helper_unittest.cc +++ b/components/performance_manager/performance_manager_tab_helper_unittest.cc
@@ -240,7 +240,7 @@ // GetFrameNode() can return nullptr. In this test, it is achieved by using an // empty RenderFrameHost. - auto* empty_frame = web_contents()->GetMainFrame(); + auto* empty_frame = web_contents()->GetPrimaryMainFrame(); DCHECK(empty_frame); auto* empty_frame_node = tab_helper->GetFrameNode(empty_frame); @@ -278,13 +278,13 @@ content::NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(), GURL(kParentUrl)); - auto* first_nav_main_rfh = web_contents()->GetMainFrame(); + auto* first_nav_main_rfh = web_contents()->GetPrimaryMainFrame(); content::LeaveInPendingDeletionState(first_nav_main_rfh); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kCousinFreddyUrl)); - EXPECT_NE(web_contents()->GetMainFrame(), first_nav_main_rfh); + EXPECT_NE(web_contents()->GetPrimaryMainFrame(), first_nav_main_rfh); // Mock observer, this can only be used from the PM sequence. MockPageNodeObserver observer; @@ -325,8 +325,8 @@ // Sanity check to ensure that notification sent to the active main frame are // forwarded. DidUpdateFaviconURL needs to be called twice as the first // favicon change is always ignored. - tab_helper->DidUpdateFaviconURL(web_contents()->GetMainFrame(), {}); - tab_helper->DidUpdateFaviconURL(web_contents()->GetMainFrame(), {}); + tab_helper->DidUpdateFaviconURL(web_contents()->GetPrimaryMainFrame(), {}); + tab_helper->DidUpdateFaviconURL(web_contents()->GetPrimaryMainFrame(), {}); { base::RunLoop run_loop;
diff --git a/components/performance_manager/performance_manager_unittest.cc b/components/performance_manager/performance_manager_unittest.cc index 39ada3e..d65e7bb5 100644 --- a/components/performance_manager/performance_manager_unittest.cc +++ b/components/performance_manager/performance_manager_unittest.cc
@@ -50,7 +50,7 @@ TEST_F(PerformanceManagerTest, NodeAccessors) { auto contents = CreateTestWebContents(); - content::RenderFrameHost* rfh = contents->GetMainFrame(); + content::RenderFrameHost* rfh = contents->GetPrimaryMainFrame(); ASSERT_TRUE(rfh); content::RenderProcessHost* rph = rfh->GetProcess(); ASSERT_TRUE(rph);
diff --git a/components/performance_manager/prerendering_browsertest.cc b/components/performance_manager/prerendering_browsertest.cc index dfaf6aa..4bc4501 100644 --- a/components/performance_manager/prerendering_browsertest.cc +++ b/components/performance_manager/prerendering_browsertest.cc
@@ -131,7 +131,7 @@ // Activate the prerendered document. Test that GetMainFrameNode now returns // its main frame, and the original frame tree is gone. content::RenderFrameDeletedObserver deleted_observer( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); content::test::PrerenderHostObserver prerender_observer(*web_contents(), kPrerenderingUrl); prerender_helper_.NavigatePrimaryPage(kPrerenderingUrl);
diff --git a/components/performance_manager/render_process_host_proxy_browsertest.cc b/components/performance_manager/render_process_host_proxy_browsertest.cc index 5e019d65..0ec8a5a 100644 --- a/components/performance_manager/render_process_host_proxy_browsertest.cc +++ b/components/performance_manager/render_process_host_proxy_browsertest.cc
@@ -44,7 +44,7 @@ // Get the RPH associated with the main frame. content::RenderProcessHost* host = - shell()->web_contents()->GetMainFrame()->GetProcess(); + shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(); // And its associated ProcessNode. auto* render_process_user_data =
diff --git a/components/performance_manager/v8_memory/v8_context_tracker_browsertest.cc b/components/performance_manager/v8_memory/v8_context_tracker_browsertest.cc index 6e62622e..4f27902 100644 --- a/components/performance_manager/v8_memory/v8_context_tracker_browsertest.cc +++ b/components/performance_manager/v8_memory/v8_context_tracker_browsertest.cc
@@ -65,7 +65,7 @@ NavigateAndWaitForConsoleMessage(contents, urla, "a.html loaded")); // Get pointers to the RFHs for each frame. - content::RenderFrameHost* main_rfh = contents->GetMainFrame(); + content::RenderFrameHost* main_rfh = contents->GetPrimaryMainFrame(); content::RenderFrameHost* child_rfh = ChildFrameAt(main_rfh, 0); ASSERT_TRUE(child_rfh); @@ -90,7 +90,7 @@ NavigateAndWaitForConsoleMessage(contents, urla, "b.html loaded")); // Get pointers to the RFHs for each frame. - content::RenderFrameHost* main_rfh = contents->GetMainFrame(); + content::RenderFrameHost* main_rfh = contents->GetPrimaryMainFrame(); content::RenderFrameHost* child_rfh = ChildFrameAt(main_rfh, 0); ASSERT_TRUE(child_rfh); auto frame_node = @@ -119,7 +119,7 @@ ExpectCounts(2, 2, 0, 0); // Get pointers to the RFHs for each frame. - content::RenderFrameHost* rfha = contents->GetMainFrame(); + content::RenderFrameHost* rfha = contents->GetPrimaryMainFrame(); content::RenderFrameHost* rfhb = ChildFrameAt(rfha, 0); // Execute a same document navigation in the child frame. This causes a @@ -143,7 +143,7 @@ ExpectCounts(2, 2, 0, 0); // Get pointers to the RFHs for each frame. - content::RenderFrameHost* rfha = contents->GetMainFrame(); + content::RenderFrameHost* rfha = contents->GetPrimaryMainFrame(); // Keep a pointer to the window associated with the child iframe, but // unload it.
diff --git a/components/permissions/contexts/geolocation_permission_context_unittest.cc b/components/permissions/contexts/geolocation_permission_context_unittest.cc index b434616..309c4aea5 100644 --- a/components/permissions/contexts/geolocation_permission_context_unittest.cc +++ b/components/permissions/contexts/geolocation_permission_context_unittest.cc
@@ -209,8 +209,8 @@ PermissionRequestID GeolocationPermissionContextTests::RequestID( int request_id) { return PermissionRequestID( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(request_id)); } @@ -218,8 +218,8 @@ int tab, int request_id) { return PermissionRequestID( - extra_tabs_[tab]->GetMainFrame()->GetProcess()->GetID(), - extra_tabs_[tab]->GetMainFrame()->GetRoutingID(), + extra_tabs_[tab]->GetPrimaryMainFrame()->GetProcess()->GetID(), + extra_tabs_[tab]->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(request_id)); } @@ -276,7 +276,7 @@ bool allowed) { CheckPermissionMessageSentInternal( static_cast<MockRenderProcessHost*>( - extra_tabs_[tab]->GetMainFrame()->GetProcess()), + extra_tabs_[tab]->GetPrimaryMainFrame()->GetProcess()), request_id, allowed); } @@ -305,7 +305,7 @@ ContentSetting expected_content_setting) { auto* content_settings = content_settings::PageSpecificContentSettings::GetForFrame( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); expected_content_setting == CONTENT_SETTING_BLOCK ? content_settings->IsContentBlocked(ContentSettingsType::GEOLOCATION)
diff --git a/components/permissions/contexts/midi_sysex_permission_context_unittest.cc b/components/permissions/contexts/midi_sysex_permission_context_unittest.cc index 900680f..e9113d86 100644 --- a/components/permissions/contexts/midi_sysex_permission_context_unittest.cc +++ b/components/permissions/contexts/midi_sysex_permission_context_unittest.cc
@@ -76,8 +76,8 @@ content::WebContentsTester::For(web_contents())->NavigateAndCommit(url); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); permission_context.RequestPermission( id, url, true,
diff --git a/components/permissions/contexts/nfc_permission_context_unittest.cc b/components/permissions/contexts/nfc_permission_context_unittest.cc index b8383c50..5e9f92d 100644 --- a/components/permissions/contexts/nfc_permission_context_unittest.cc +++ b/components/permissions/contexts/nfc_permission_context_unittest.cc
@@ -83,8 +83,8 @@ PermissionRequestID NfcPermissionContextTests::RequestID(int request_id) { return PermissionRequestID( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId(request_id)); }
diff --git a/components/permissions/permission_context_base_unittest.cc b/components/permissions/permission_context_base_unittest.cc index 733b4ae2..e8e69ce 100644 --- a/components/permissions/permission_context_base_unittest.cc +++ b/components/permissions/permission_context_base_unittest.cc
@@ -228,8 +228,8 @@ base::HistogramTester histograms; const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.SetRespondPermissionCallback(base::BindOnce( &PermissionContextBaseTests::RespondToPermission, @@ -328,8 +328,8 @@ TestPermissionContext permission_context(browser_context(), content_settings_type); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.SetRespondPermissionCallback( @@ -381,8 +381,8 @@ TestPermissionContext permission_context(browser_context(), content_settings_type); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.SetRespondPermissionCallback( @@ -421,8 +421,8 @@ browser_context(), ContentSettingsType::GEOLOCATION); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(i + 1)); permission_context.SetRespondPermissionCallback( @@ -496,8 +496,8 @@ ContentSettingsType::MIDI_SYSEX); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(i + 1)); permission_context.SetRespondPermissionCallback( base::BindOnce(&PermissionContextBaseTests::RespondToPermission, @@ -558,8 +558,8 @@ std::string()); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.RequestPermission( id, url, true /* user_gesture */, @@ -583,8 +583,8 @@ SetUpUrl(url); const PermissionRequestID id( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.SetRespondPermissionCallback( base::BindOnce(&PermissionContextBaseTests::RespondToPermission, @@ -666,12 +666,12 @@ SetUpUrl(url); const PermissionRequestID id1( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(1)); const PermissionRequestID id2( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID(), + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId(2)); // Request a permission without setting the callback to DecidePermission. @@ -711,7 +711,7 @@ virtual_url); PermissionResult result = permission_context.GetPermissionStatus( - web_contents()->GetMainFrame(), virtual_url, virtual_url); + web_contents()->GetPrimaryMainFrame(), virtual_url, virtual_url); EXPECT_EQ(result.content_setting, want_response); EXPECT_EQ(result.source, want_source); }
diff --git a/components/permissions/permission_manager_unittest.cc b/components/permissions/permission_manager_unittest.cc index 3d3e4905..ea7cd30 100644 --- a/components/permissions/permission_manager_unittest.cc +++ b/components/permissions/permission_manager_unittest.cc
@@ -690,7 +690,8 @@ PermissionResult result = GetPermissionManager()->GetPermissionStatusForCurrentDocument( - ContentSettingsType::GEOLOCATION, web_contents()->GetMainFrame()); + ContentSettingsType::GEOLOCATION, + web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(CONTENT_SETTING_BLOCK, result.content_setting); EXPECT_EQ(PermissionStatusSource::INSECURE_ORIGIN, result.source); @@ -699,7 +700,7 @@ NavigateAndCommit(secure_frame); result = GetPermissionManager()->GetPermissionStatusForCurrentDocument( - ContentSettingsType::GEOLOCATION, web_contents()->GetMainFrame()); + ContentSettingsType::GEOLOCATION, web_contents()->GetPrimaryMainFrame()); EXPECT_EQ(CONTENT_SETTING_ASK, result.content_setting); EXPECT_EQ(PermissionStatusSource::UNSPECIFIED, result.source);
diff --git a/components/permissions/permission_request_manager.cc b/components/permissions/permission_request_manager.cc index 2ec2a6b..55344b2 100644 --- a/components/permissions/permission_request_manager.cc +++ b/components/permissions/permission_request_manager.cc
@@ -217,7 +217,7 @@ // any other renderer-side nav initiations?). Double-check this for // correct behavior on interstitials -- we probably want to basically queue // any request for which GetVisibleURL != GetLastCommittedURL. - CHECK_EQ(source_frame->GetMainFrame(), web_contents()->GetMainFrame()); + CHECK_EQ(source_frame->GetMainFrame(), web_contents()->GetPrimaryMainFrame()); const GURL main_frame_origin = PermissionUtil::GetLastCommittedOriginAsURL(source_frame->GetMainFrame()); bool is_main_frame = @@ -477,7 +477,7 @@ GURL PermissionRequestManager::GetEmbeddingOrigin() const { return PermissionUtil::GetLastCommittedOriginAsURL( - web_contents()->GetMainFrame()); + web_contents()->GetPrimaryMainFrame()); } void PermissionRequestManager::Accept() { @@ -1070,7 +1070,7 @@ } void PermissionRequestManager::LogWarningToConsole(const char* message) { - web_contents()->GetMainFrame()->AddMessageToConsole( + web_contents()->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); }
diff --git a/components/permissions/permission_request_manager_unittest.cc b/components/permissions/permission_request_manager_unittest.cc index f9bb25b1..d7d928d 100644 --- a/components/permissions/permission_request_manager_unittest.cc +++ b/components/permissions/permission_request_manager_unittest.cc
@@ -124,7 +124,7 @@ std::unique_ptr<MockPermissionRequest> request = std::make_unique<MockPermissionRequest>( type, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), request.get()); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), request.get()); WaitForBubbleToBeShown(); if (should_be_seen) { EXPECT_TRUE(prompt_factory_->RequestTypeSeen(type)); @@ -175,7 +175,7 @@ } TEST_P(PermissionRequestManagerTest, SingleRequest) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -186,7 +186,7 @@ } TEST_P(PermissionRequestManagerTest, SequentialRequests) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -194,7 +194,7 @@ EXPECT_TRUE(request1_.granted()); EXPECT_FALSE(prompt_factory_->is_visible()); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); Accept(); @@ -203,9 +203,9 @@ } TEST_P(PermissionRequestManagerTest, ForgetRequestsOnPageNavigation) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_other_domain_); WaitForBubbleToBeShown(); @@ -224,24 +224,24 @@ TEST_P(PermissionRequestManagerTest, RequestsDontNeedUserGesture) { WaitForFrameLoad(); WaitForBubbleToBeShown(); - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_other_domain_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(prompt_factory_->is_visible()); } TEST_P(PermissionRequestManagerTest, RequestsNotSupported) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); Accept(); EXPECT_TRUE(request1_.granted()); manager_->set_web_contents_supports_permission_requests(false); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); EXPECT_TRUE(request2_.cancelled()); } @@ -255,8 +255,8 @@ if (GetParam()) return; - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -278,9 +278,9 @@ return; // Test new permissions order, requests shouldn't be grouped. - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -309,13 +309,13 @@ if (!GetParam()) return; - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); WaitForBubbleToBeShown(); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -341,8 +341,8 @@ // Only mic/camera requests from the same origin should be grouped. TEST_P(PermissionRequestManagerTest, MicCameraGrouped) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -356,9 +356,9 @@ // If mic/camera requests come from different origins, they should not be // grouped. TEST_P(PermissionRequestManagerTest, MicCameraDifferentOrigins) { - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_mic_other_domain_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -368,8 +368,8 @@ #if !BUILDFLAG(IS_ANDROID) // Only camera/ptz requests from the same origin should be grouped. TEST_P(PermissionRequestManagerTest, CameraPtzGrouped) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_ptz_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -383,9 +383,9 @@ TEST_P(PermissionRequestManagerTest, CameraPtzDifferentOrigins) { // If camera/ptz requests come from different origins, they should not be // grouped. - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_camera_other_domain_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_ptz_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -394,9 +394,9 @@ // Only mic/camera/ptz requests from the same origin should be grouped. TEST_P(PermissionRequestManagerTest, MicCameraPtzGrouped) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_ptz_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -411,10 +411,10 @@ // If mic/camera/ptz requests come from different origins, they should not be // grouped. TEST_P(PermissionRequestManagerTest, MicCameraPtzDifferentOrigins) { - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_mic_other_domain_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_ptz_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_); WaitForBubbleToBeShown(); // Requests should be split into two groups and each one will contain less @@ -431,9 +431,9 @@ // Tests mix of grouped media requests and non-groupable request. TEST_P(PermissionRequestManagerTest, MixOfMediaAndNotMediaRequests) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); WaitForBubbleToBeShown(); // Requests should be split into two groups and each one will contain less @@ -454,8 +454,8 @@ //////////////////////////////////////////////////////////////////////////////// TEST_P(PermissionRequestManagerTest, TwoRequestsTabSwitch) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request_mic_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -480,7 +480,7 @@ TEST_P(PermissionRequestManagerTest, PermissionRequestWhileTabSwitchedAway) { MockTabSwitchAway(); - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); EXPECT_FALSE(prompt_factory_->is_visible()); @@ -494,8 +494,8 @@ //////////////////////////////////////////////////////////////////////////////// TEST_P(PermissionRequestManagerTest, SameRequestRejected) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); EXPECT_FALSE(request1_.finished()); WaitForBubbleToBeShown(); @@ -508,17 +508,19 @@ } TEST_P(PermissionRequestManagerTest, DuplicateRequest) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_); auto dupe_request = request1_.CreateDuplicateRequest(); - manager_->AddRequest(web_contents()->GetMainFrame(), dupe_request.get()); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), + dupe_request.get()); EXPECT_FALSE(dupe_request->finished()); EXPECT_FALSE(request1_.finished()); auto dupe_request2 = request2_.CreateDuplicateRequest(); - manager_->AddRequest(web_contents()->GetMainFrame(), dupe_request2.get()); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), + dupe_request2.get()); EXPECT_FALSE(dupe_request2->finished()); EXPECT_FALSE(request2_.finished()); @@ -548,7 +550,7 @@ //////////////////////////////////////////////////////////////////////////////// TEST_P(PermissionRequestManagerTest, MainFrameNoRequestIFrameRequest) { - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_same_domain_); WaitForBubbleToBeShown(); WaitForFrameLoad(); @@ -559,8 +561,8 @@ } TEST_P(PermissionRequestManagerTest, MainFrameAndIFrameRequestSameDomain) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_same_domain_); WaitForFrameLoad(); WaitForBubbleToBeShown(); @@ -589,8 +591,8 @@ } TEST_P(PermissionRequestManagerTest, MainFrameAndIFrameRequestOtherDomain) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_other_domain_); WaitForFrameLoad(); WaitForBubbleToBeShown(); @@ -615,11 +617,11 @@ } TEST_P(PermissionRequestManagerTest, IFrameRequestWhenMainRequestVisible) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_same_domain_); WaitForFrameLoad(); ASSERT_EQ(prompt_factory_->request_count(), 1); @@ -644,11 +646,11 @@ TEST_P(PermissionRequestManagerTest, IFrameRequestOtherDomainWhenMainRequestVisible) { - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); - manager_->AddRequest(web_contents()->GetMainFrame(), + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &iframe_request_other_domain_); WaitForFrameLoad(); Closing(); @@ -678,7 +680,7 @@ TEST_P(PermissionRequestManagerTest, UMAForSimpleDeniedBubbleAlternatePath) { base::HistogramTester histograms; - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); // No need to test UMA for showing prompts again, they were tested in // UMAForSimpleAcceptedBubble. @@ -693,7 +695,7 @@ TEST_P(PermissionRequestManagerTest, UMAForTabSwitching) { base::HistogramTester histograms; - manager_->AddRequest(web_contents()->GetMainFrame(), &request1_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_); WaitForBubbleToBeShown(); histograms.ExpectUniqueSample(PermissionUmaUtil::kPermissionsPromptShown, static_cast<base::HistogramBase::Sample>( @@ -801,7 +803,7 @@ manager_, PermissionUiSelector::QuietUiReason::kEnabledInPrefs, false /* async */); - manager_->AddRequest(web_contents()->GetMainFrame(), &request_camera_); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_); WaitForBubbleToBeShown(); ASSERT_TRUE(prompt_factory_->is_visible()); @@ -831,7 +833,7 @@ MockPermissionRequest request(RequestType::kNotifications, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -851,7 +853,7 @@ manager_, QuietUiReason::kEnabledInPrefs, true); MockPermissionRequest request1(RequestType::kNotifications, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request1); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1); WaitForBubbleToBeShown(); EXPECT_TRUE(manager_->ShouldCurrentRequestUseQuietUI()); Accept(); @@ -861,7 +863,7 @@ manager_->clear_permission_ui_selector_for_testing(); MockNotificationPermissionUiSelector::CreateForManager( manager_, PermissionUiSelector::Decision::UseNormalUi(), true); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2); WaitForBubbleToBeShown(); EXPECT_FALSE(manager_->ShouldCurrentRequestUseQuietUI()); Accept(); @@ -923,7 +925,7 @@ MockPermissionRequest request(RequestType::kNotifications, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -980,7 +982,7 @@ MockPermissionRequest request(RequestType::kNotifications, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible()); @@ -1008,7 +1010,7 @@ for (const auto& test : kTests) { MockPermissionRequest request(test.request_type, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request); WaitForBubbleToBeShown(); EXPECT_EQ(test.should_request_use_quiet_ui, manager_->ShouldCurrentRequestUseQuietUI()); @@ -1020,7 +1022,7 @@ // Now the RequestType::kCameraStream should show a quiet UI as well MockPermissionRequest request2(RequestType::kCameraStream, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request2); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2); WaitForBubbleToBeShown(); EXPECT_TRUE(manager_->ShouldCurrentRequestUseQuietUI()); Accept(); @@ -1034,7 +1036,7 @@ MockPermissionRequest request(RequestType::kNotifications, PermissionRequestGestureType::GESTURE); - manager_->AddRequest(web_contents()->GetMainFrame(), &request); + manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request); WaitForBubbleToBeShown(); EXPECT_TRUE(prompt_factory_->is_visible());
diff --git a/components/permissions/test/test_permissions_client.cc b/components/permissions/test/test_permissions_client.cc index 65247d77..03ba8f79f 100644 --- a/components/permissions/test/test_permissions_client.cc +++ b/components/permissions/test/test_permissions_client.cc
@@ -79,7 +79,7 @@ GetUkmSourceIdCallback callback) { if (web_contents) { ukm::SourceId source_id = - web_contents->GetMainFrame()->GetPageUkmSourceId(); + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId(); std::move(callback).Run(source_id); } else { std::move(callback).Run(absl::nullopt);
diff --git a/components/policy/core/common/policy_loader_common.cc b/components/policy/core/common/policy_loader_common.cc index 38ecdb3c..7e7edcc 100644 --- a/components/policy/core/common/policy_loader_common.cc +++ b/components/policy/core/common/policy_loader_common.cc
@@ -88,8 +88,8 @@ continue; // Only allow custom update urls in enterprise environments. - if (!base::LowerCaseEqualsASCII(entry.substr(pos + 1), - kChromeWebstoreUpdateURL)) { + if (!base::EqualsCaseInsensitiveASCII(entry.substr(pos + 1), + kChromeWebstoreUpdateURL)) { policy_list_value->GetListDeprecated()[i] = base::Value(kBlockedExtensionPrefix + entry); has_invalid_policies = true; @@ -131,8 +131,8 @@ continue; } std::string* update_url = entry.second.FindStringKey(kUpdateUrl); - if (!update_url || - base::LowerCaseEqualsASCII(*update_url, kChromeWebstoreUpdateURL)) { + if (!update_url || base::EqualsCaseInsensitiveASCII( + *update_url, kChromeWebstoreUpdateURL)) { continue; }
diff --git a/components/renderer_context_menu/context_menu_content_type.cc b/components/renderer_context_menu/context_menu_content_type.cc index 08a4604..e48fcf2 100644 --- a/components/renderer_context_menu/context_menu_content_type.cc +++ b/components/renderer_context_menu/context_menu_content_type.cc
@@ -159,6 +159,10 @@ return params_.input_field_type == blink::mojom::ContextMenuDataInputFieldType::kPassword; + case ITEM_GROUP_AUTOFILL: + return params_.input_field_type != + blink::mojom::ContextMenuDataInputFieldType::kNone; + default: NOTREACHED(); return false;
diff --git a/components/renderer_context_menu/context_menu_content_type.h b/components/renderer_context_menu/context_menu_content_type.h index cfd3c45..45a3c1f 100644 --- a/components/renderer_context_menu/context_menu_content_type.h +++ b/components/renderer_context_menu/context_menu_content_type.h
@@ -49,7 +49,8 @@ ITEM_GROUP_DEVTOOLS_UNPACKED_EXT, ITEM_GROUP_PRINT_PREVIEW, ITEM_GROUP_PASSWORD, - ITEM_GROUP_EXISTING_LINK_TO_TEXT + ITEM_GROUP_EXISTING_LINK_TO_TEXT, + ITEM_GROUP_AUTOFILL }; // Returns if |group| is enabled.
diff --git a/components/renderer_context_menu/render_view_context_menu_base.cc b/components/renderer_context_menu/render_view_context_menu_base.cc index a3ba440..92bf0cec 100644 --- a/components/renderer_context_menu/render_view_context_menu_base.cc +++ b/components/renderer_context_menu/render_view_context_menu_base.cc
@@ -322,7 +322,7 @@ } RenderViewHost* RenderViewContextMenuBase::GetRenderViewHost() const { - return source_web_contents_->GetMainFrame()->GetRenderViewHost(); + return source_web_contents_->GetPrimaryMainFrame()->GetRenderViewHost(); } WebContents* RenderViewContextMenuBase::GetWebContents() const {
diff --git a/components/safe_browsing/content/browser/base_ui_manager.cc b/components/safe_browsing/content/browser/base_ui_manager.cc index f7959ec3..bee0584 100644 --- a/components/safe_browsing/content/browser/base_ui_manager.cc +++ b/components/safe_browsing/content/browser/base_ui_manager.cc
@@ -315,7 +315,7 @@ outermost_contents, unsafe_url, resource)); base::WeakPtr<content::NavigationHandle> error_page_navigation_handle = outermost_contents->GetController().LoadPostCommitErrorPage( - outermost_contents->GetMainFrame(), unsafe_url, + outermost_contents->GetPrimaryMainFrame(), unsafe_url, blocking_page->GetHTMLContents(), net::ERR_BLOCKED_BY_CLIENT); if (error_page_navigation_handle) { blocking_page->CreatedPostCommitErrorPageNavigation(
diff --git a/components/safe_browsing/content/browser/client_side_detection_host.cc b/components/safe_browsing/content/browser/client_side_detection_host.cc index c42cf0d..f930de1e 100644 --- a/components/safe_browsing/content/browser/client_side_detection_host.cc +++ b/components/safe_browsing/content/browser/client_side_detection_host.cc
@@ -442,7 +442,7 @@ bool should_classify) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (should_classify) { - content::RenderFrameHost* rfh = web_contents()->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents()->GetPrimaryMainFrame(); phishing_detector_.reset(); rfh->GetRemoteAssociatedInterfaces()->GetInterface(&phishing_detector_); @@ -569,7 +569,7 @@ DCHECK(web_contents()); if (ui_manager_.get()) { const content::GlobalRenderFrameHostId primary_main_frame_id = - web_contents()->GetMainFrame()->GetGlobalId(); + web_contents()->GetPrimaryMainFrame()->GetGlobalId(); security_interstitials::UnsafeResource resource; resource.url = phishing_url;
diff --git a/components/safe_browsing/content/browser/password_protection/password_protection_request_content.cc b/components/safe_browsing/content/browser/password_protection/password_protection_request_content.cc index a5faf91..b5b35ad 100644 --- a/components/safe_browsing/content/browser/password_protection/password_protection_request_content.cc +++ b/components/safe_browsing/content/browser/password_protection/password_protection_request_content.cc
@@ -127,7 +127,7 @@ } void PasswordProtectionRequestContent::GetDomFeatures() { - content::RenderFrameHost* rfh = web_contents_->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents_->GetPrimaryMainFrame(); PasswordProtectionService* service = static_cast<PasswordProtectionService*>(password_protection_service()); service->GetPhishingDetector(rfh->GetRemoteInterfaces(), &phishing_detector_);
diff --git a/components/safe_browsing/content/browser/safe_browsing_navigation_observer.cc b/components/safe_browsing/content/browser/safe_browsing_navigation_observer.cc index 422a2e7..87dd58c 100644 --- a/components/safe_browsing/content/browser/safe_browsing_navigation_observer.cc +++ b/components/safe_browsing/content/browser/safe_browsing_navigation_observer.cc
@@ -322,7 +322,7 @@ // frame. nav_event->source_url = SafeBrowsingNavigationObserverManager::ClearURLRef( navigation_handle->GetWebContents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetLastCommittedURL()); } else { // If there was a URL previously committed in the current RenderFrameHost,
diff --git a/components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.cc b/components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.cc index df4b0699..88ed4b4a 100644 --- a/components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.cc +++ b/components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.cc
@@ -687,9 +687,10 @@ nav_event->initiator_outermost_main_frame_id = source_render_frame_host->GetOutermostMainFrame()->GetGlobalId(); } - nav_event->outermost_main_frame_id = target_web_contents->GetMainFrame() - ->GetOutermostMainFrame() - ->GetGlobalId(); + nav_event->outermost_main_frame_id = + target_web_contents->GetPrimaryMainFrame() + ->GetOutermostMainFrame() + ->GetGlobalId(); } nav_event->source_tab_id =
diff --git a/components/safe_browsing/content/browser/safe_browsing_navigation_observer_unittest.cc b/components/safe_browsing/content/browser/safe_browsing_navigation_observer_unittest.cc index ae9d1500..04f0d36e 100644 --- a/components/safe_browsing/content/browser/safe_browsing_navigation_observer_unittest.cc +++ b/components/safe_browsing/content/browser/safe_browsing_navigation_observer_unittest.cc
@@ -375,7 +375,7 @@ TEST_F(SBNavigationObserverTest, ServerRedirect) { auto navigation = content::NavigationSimulator::CreateRendererInitiated( - GURL("http://foo/3"), web_contents()->GetMainFrame()); + GURL("http://foo/3"), web_contents()->GetPrimaryMainFrame()); auto* nav_list = navigation_event_list(); SessionID tab_id = sessions::SessionTabHelper::IdForTab(web_contents()); @@ -446,8 +446,10 @@ base::Time::FromDoubleT(now.ToDoubleT() + 60.0 * 60.0); // Invalid GURL url_0("http://foo/0"); GURL url_1("http://foo/1"); - content::MockNavigationHandle handle_0(url_0, web_contents()->GetMainFrame()); - content::MockNavigationHandle handle_1(url_1, web_contents()->GetMainFrame()); + content::MockNavigationHandle handle_0(url_0, + web_contents()->GetPrimaryMainFrame()); + content::MockNavigationHandle handle_1(url_1, + web_contents()->GetPrimaryMainFrame()); navigation_event_list()->RecordNavigationEvent( CreateNavigationEventUniquePtr(url_0, in_an_hour)); navigation_event_list()->RecordNavigationEvent( @@ -875,9 +877,12 @@ base::Time one_minute_ago = base::Time::FromDoubleT(now.ToDoubleT() - 60.0); base::Time two_minute_ago = base::Time::FromDoubleT(now.ToDoubleT() - 120.0); GURL url("http://foo/0"); - content::MockNavigationHandle handle_0(url, web_contents()->GetMainFrame()); - content::MockNavigationHandle handle_1(url, web_contents()->GetMainFrame()); - content::MockNavigationHandle handle_2(url, web_contents()->GetMainFrame()); + content::MockNavigationHandle handle_0(url, + web_contents()->GetPrimaryMainFrame()); + content::MockNavigationHandle handle_1(url, + web_contents()->GetPrimaryMainFrame()); + content::MockNavigationHandle handle_2(url, + web_contents()->GetPrimaryMainFrame()); navigation_event_list()->RecordPendingNavigationEvent( &handle_0, CreateNavigationEventUniquePtr(url, one_minute_ago)); navigation_event_list()->RecordPendingNavigationEvent(
diff --git a/components/safe_browsing/content/browser/threat_details.cc b/components/safe_browsing/content/browser/threat_details.cc index 7b1bfd0e..0d18b38 100644 --- a/components/safe_browsing/content/browser/threat_details.cc +++ b/components/safe_browsing/content/browser/threat_details.cc
@@ -635,8 +635,9 @@ // OnReceivedThreatDOMDetails will be called when the renderer replies. // TODO(mattm): In theory, if the user proceeds through the warning DOM // detail collection could be started once the page loads. - web_contents_->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - &ThreatDetails::RequestThreatDOMDetails, GetWeakPtr())); + web_contents_->GetPrimaryMainFrame()->ForEachRenderFrameHost( + base::BindRepeating(&ThreatDetails::RequestThreatDOMDetails, + GetWeakPtr())); } } @@ -865,7 +866,7 @@ // We would have cancelled a prerender if it was blocked, so we can use the // primary main frame here. referrer_chain_provider_->IdentifyReferrerChainByRenderFrameHost( - web_contents_->GetMainFrame(), kThreatDetailsUserGestureLimit, + web_contents_->GetPrimaryMainFrame(), kThreatDetailsUserGestureLimit, report_->mutable_referrer_chain()); }
diff --git a/components/safe_browsing/content/browser/triggers/ad_sampler_trigger.cc b/components/safe_browsing/content/browser/triggers/ad_sampler_trigger.cc index e2df179b..d328b55 100644 --- a/components/safe_browsing/content/browser/triggers/ad_sampler_trigger.cc +++ b/components/safe_browsing/content/browser/triggers/ad_sampler_trigger.cc
@@ -134,7 +134,7 @@ TriggerManager::GetSBErrorDisplayOptions(*prefs_, web_contents()); const content::GlobalRenderFrameHostId primary_main_frame_id = - web_contents()->GetMainFrame()->GetGlobalId(); + web_contents()->GetPrimaryMainFrame()->GetGlobalId(); security_interstitials::UnsafeResource resource; resource.threat_type = SB_THREAT_TYPE_AD_SAMPLE; resource.url = web_contents()->GetURL();
diff --git a/components/safe_browsing/content/browser/triggers/ad_sampler_trigger_unittest.cc b/components/safe_browsing/content/browser/triggers/ad_sampler_trigger_unittest.cc index 34ef850..54b90de5 100644 --- a/components/safe_browsing/content/browser/triggers/ad_sampler_trigger_unittest.cc +++ b/components/safe_browsing/content/browser/triggers/ad_sampler_trigger_unittest.cc
@@ -68,7 +68,7 @@ // Returns the final RenderFrameHost after navigation commits. RenderFrameHost* NavigateMainFrame(const std::string& url) { - return NavigateFrame(url, web_contents()->GetMainFrame()); + return NavigateFrame(url, web_contents()->GetPrimaryMainFrame()); } // Returns the final RenderFrameHost after navigation commits.
diff --git a/components/safe_browsing/content/browser/triggers/suspicious_site_trigger_unittest.cc b/components/safe_browsing/content/browser/triggers/suspicious_site_trigger_unittest.cc index 11f2091..5261da0 100644 --- a/components/safe_browsing/content/browser/triggers/suspicious_site_trigger_unittest.cc +++ b/components/safe_browsing/content/browser/triggers/suspicious_site_trigger_unittest.cc
@@ -78,7 +78,7 @@ // Returns the final RenderFrameHost after navigation commits. RenderFrameHost* NavigateMainFrame(const std::string& url) { - return NavigateFrame(url, web_contents()->GetMainFrame()); + return NavigateFrame(url, web_contents()->GetPrimaryMainFrame()); } // Returns the final RenderFrameHost after navigation commits.
diff --git a/components/safe_browsing/content/browser/ui_manager_unittest.cc b/components/safe_browsing/content/browser/ui_manager_unittest.cc index 589ac92b..5f9c2c7a 100644 --- a/components/safe_browsing/content/browser/ui_manager_unittest.cc +++ b/components/safe_browsing/content/browser/ui_manager_unittest.cc
@@ -235,7 +235,7 @@ const char* url, bool is_subresource) { const content::GlobalRenderFrameHostId primary_main_frame_id = - web_contents()->GetMainFrame()->GetGlobalId(); + web_contents()->GetPrimaryMainFrame()->GetGlobalId(); security_interstitials::UnsafeResource resource; resource.url = GURL(url); resource.is_subresource = is_subresource;
diff --git a/components/security_interstitials/content/ssl_error_handler.cc b/components/security_interstitials/content/ssl_error_handler.cc index ebb61d3..dd59a36d 100644 --- a/components/security_interstitials/content/ssl_error_handler.cc +++ b/components/security_interstitials/content/ssl_error_handler.cc
@@ -126,7 +126,7 @@ void NavigationEntryCommitted( const content::LoadCommittedDetails& /* load_details */) override { - GetWebContents().GetMainFrame()->AddMessageToConsole( + GetWebContents().GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kInfo, base::StringPrintf( "Redirecting navigation %s -> %s because the server presented a "
diff --git a/components/security_interstitials/content/stateful_ssl_host_state_delegate.cc b/components/security_interstitials/content/stateful_ssl_host_state_delegate.cc index 45162b5d..be2729f 100644 --- a/components/security_interstitials/content/stateful_ssl_host_state_delegate.cc +++ b/components/security_interstitials/content/stateful_ssl_host_state_delegate.cc
@@ -226,7 +226,7 @@ DCHECK(web_contents); content::StoragePartition* storage_partition = browser_context_->GetStoragePartition( - web_contents->GetMainFrame()->GetSiteInstance(), + web_contents->GetPrimaryMainFrame()->GetSiteInstance(), false /* can_create */); if (!storage_partition || storage_partition != browser_context_->GetDefaultStoragePartition()) { @@ -292,7 +292,7 @@ content::StoragePartition* storage_partition = browser_context_->GetStoragePartition( - web_contents->GetMainFrame()->GetSiteInstance(), + web_contents->GetPrimaryMainFrame()->GetSiteInstance(), false /* can_create */); if (!storage_partition || storage_partition != browser_context_->GetDefaultStoragePartition()) { @@ -373,7 +373,7 @@ content::StoragePartition* storage_partition = browser_context_->GetStoragePartition( - web_contents->GetMainFrame()->GetSiteInstance(), + web_contents->GetPrimaryMainFrame()->GetSiteInstance(), /*can_create=*/false); bool is_nondefault_storage = !storage_partition || @@ -386,7 +386,7 @@ content::WebContents* web_contents) { content::StoragePartition* storage_partition = browser_context_->GetStoragePartition( - web_contents->GetMainFrame()->GetSiteInstance(), + web_contents->GetPrimaryMainFrame()->GetSiteInstance(), /*can_create=*/false); bool is_nondefault_storage = !storage_partition || @@ -541,7 +541,7 @@ content::WebContents* web_contents) { content::StoragePartition* storage_partition = browser_context_->GetStoragePartition( - web_contents->GetMainFrame()->GetSiteInstance(), + web_contents->GetPrimaryMainFrame()->GetSiteInstance(), false /* can_create */); if (!storage_partition || storage_partition != browser_context_->GetDefaultStoragePartition()) {
diff --git a/components/segmentation_platform/public/features.cc b/components/segmentation_platform/public/features.cc index 9cc0195..453f0e33 100644 --- a/components/segmentation_platform/public/features.cc +++ b/components/segmentation_platform/public/features.cc
@@ -4,6 +4,8 @@ #include "components/segmentation_platform/public/features.h" +#include "build/build_config.h" + namespace segmentation_platform::features { const base::Feature kSegmentationPlatformFeature{ @@ -23,8 +25,14 @@ base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kSegmentationPlatformFeedSegmentFeature{ - "SegmentationPlatformFeedSegmentFeature", - base::FEATURE_DISABLED_BY_DEFAULT}; + "SegmentationPlatformFeedSegmentFeature", +#if BUILDFLAG(IS_ANDROID) + base::FEATURE_ENABLED_BY_DEFAULT +}; +#else + base::FEATURE_DISABLED_BY_DEFAULT +}; +#endif const base::Feature kContextualPageActionsWithPriceTracking{ "ContextualPageActionsWithPriceTracking",
diff --git a/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc b/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc index 218a72e0..4749b13c 100644 --- a/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc +++ b/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc
@@ -209,7 +209,7 @@ content::RenderViewHostTestHarness::SetUp(); content::WebContents* web_contents = RenderViewHostTestHarness::web_contents(); - CreateAgentForHost(web_contents->GetMainFrame()); + CreateAgentForHost(web_contents->GetPrimaryMainFrame()); // Initialize the ruleset dealer. Allowlisted URLs must also match a // disallowed rule in order to work correctly. @@ -340,7 +340,8 @@ bool ads_blocked_in_content_settings() { auto* content_settings = content_settings::PageSpecificContentSettings::GetForFrame( - content::RenderViewHostTestHarness::web_contents()->GetMainFrame()); + content::RenderViewHostTestHarness::web_contents() + ->GetPrimaryMainFrame()); return content_settings->IsContentBlocked(ContentSettingsType::ADS); }
diff --git a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle_unittest.cc b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle_unittest.cc index 36e52fbb..463c5b23 100644 --- a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle_unittest.cc +++ b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle_unittest.cc
@@ -923,7 +923,7 @@ SimulateStartAndExpectProceed(url); navigation_simulator()->SetReferrer(blink::mojom::Referrer::New( RenderViewHostTestHarness::web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetLastCommittedURL(), network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin)); SimulateCommitAndExpectProceed();
diff --git a/components/translate/content/browser/content_translate_driver.cc b/components/translate/content/browser/content_translate_driver.cc index bc2fb0b..6ab691091 100644 --- a/components/translate/content/browser/content_translate_driver.cc +++ b/components/translate/content/browser/content_translate_driver.cc
@@ -164,7 +164,7 @@ } ukm::SourceId ContentTranslateDriver::GetUkmSourceId() { - return web_contents()->GetMainFrame()->GetPageUkmSourceId(); + return web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId(); } bool ContentTranslateDriver::HasCurrentPage() {
diff --git a/components/translate/content/browser/per_frame_content_translate_driver.cc b/components/translate/content/browser/per_frame_content_translate_driver.cc index 694c7567..fd7537b 100644 --- a/components/translate/content/browser/per_frame_content_translate_driver.cc +++ b/components/translate/content/browser/per_frame_content_translate_driver.cc
@@ -151,9 +151,10 @@ stats_.Clear(); translate_seq_no_ = IncrementSeqNo(translate_seq_no_); - web_contents()->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - &PerFrameContentTranslateDriver::TranslateFrame, base::Unretained(this), - translate_script, source_lang, target_lang, translate_seq_no_)); + web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHost( + base::BindRepeating(&PerFrameContentTranslateDriver::TranslateFrame, + base::Unretained(this), translate_script, source_lang, + target_lang, translate_seq_no_)); } void PerFrameContentTranslateDriver::TranslateFrame( @@ -189,8 +190,9 @@ stats_.Clear(); translate_seq_no_ = IncrementSeqNo(translate_seq_no_); - web_contents()->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - &PerFrameContentTranslateDriver::RevertFrame, base::Unretained(this))); + web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHost( + base::BindRepeating(&PerFrameContentTranslateDriver::RevertFrame, + base::Unretained(this))); } void PerFrameContentTranslateDriver::RevertFrame( @@ -355,8 +357,10 @@ // Kick off language detection by first requesting web language details. details_ = LanguageDetectionDetails(); mojo::AssociatedRemote<mojom::TranslateAgent> frame_agent; - web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces()->GetInterface( - &frame_agent); + web_contents() + ->GetPrimaryMainFrame() + ->GetRemoteAssociatedInterfaces() + ->GetInterface(&frame_agent); mojom::TranslateAgent* frame_agent_ptr = frame_agent.get(); frame_agent_ptr->GetWebLanguageDetectionDetails(base::BindOnce( &PerFrameContentTranslateDriver::OnWebLanguageDetectionDetails,
diff --git a/components/ukm/android/ukm_recorder.cc b/components/ukm/android/ukm_recorder.cc index fe8517a..d630e85d 100644 --- a/components/ukm/android/ukm_recorder.cc +++ b/components/ukm/android/ukm_recorder.cc
@@ -21,7 +21,7 @@ content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); const ukm::SourceId source_id = - web_contents->GetMainFrame()->GetPageUkmSourceId(); + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId(); const std::string event_name(ConvertJavaStringToUTF8(env, j_event_name)); ukm::UkmEntryBuilder builder(source_id, event_name); builder.SetMetric(ConvertJavaStringToUTF8(env, j_metric_name), true); @@ -38,7 +38,7 @@ content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); const ukm::SourceId source_id = - web_contents->GetMainFrame()->GetPageUkmSourceId(); + web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId(); const std::string event_name(ConvertJavaStringToUTF8(env, j_event_name)); ukm::UkmEntryBuilder builder(source_id, event_name); builder.SetMetric(ConvertJavaStringToUTF8(env, j_metric_name),
diff --git a/components/ukm/content/source_url_recorder_browsertest.cc b/components/ukm/content/source_url_recorder_browsertest.cc index ea94d91b..2e20fa2b 100644 --- a/components/ukm/content/source_url_recorder_browsertest.cc +++ b/components/ukm/content/source_url_recorder_browsertest.cc
@@ -59,7 +59,7 @@ GURL GetAssociatedURLForWebContentsDocument() { const ukm::UkmSource* src = test_ukm_recorder_->GetSourceForSourceId( - shell()->web_contents()->GetMainFrame()->GetPageUkmSourceId()); + shell()->web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); return src ? src->url() : GURL(); }
diff --git a/components/ukm/content/source_url_recorder_test.cc b/components/ukm/content/source_url_recorder_test.cc index fd1cbe7..066d33bc 100644 --- a/components/ukm/content/source_url_recorder_test.cc +++ b/components/ukm/content/source_url_recorder_test.cc
@@ -27,7 +27,7 @@ GURL GetAssociatedURLForWebContentsDocument() { const ukm::UkmSource* src = test_ukm_recorder_.GetSourceForSourceId( - web_contents()->GetMainFrame()->GetPageUkmSourceId()); + web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId()); return src ? src->url() : GURL(); }
diff --git a/components/url_param_filter/content/cross_otr_observer.cc b/components/url_param_filter/content/cross_otr_observer.cc index d825693..049c010 100644 --- a/components/url_param_filter/content/cross_otr_observer.cc +++ b/components/url_param_filter/content/cross_otr_observer.cc
@@ -7,7 +7,9 @@ #include <memory> #include "base/metrics/histogram_functions.h" +#include "base/no_destructor.h" #include "base/strings/string_util.h" +#include "components/url_param_filter/core/url_param_classifications_loader.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/reload_type.h" @@ -28,11 +30,6 @@ } } // anonymous namespace -constexpr char kCrossOtrResponseCodeMetricName[] = - "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental"; -constexpr char kCrossOtrRefreshCountMetricName[] = - "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental"; - void CrossOtrObserver::MaybeCreateForWebContents( content::WebContents* web_contents, bool privacy_sensitivity_is_cross_otr, @@ -54,7 +51,7 @@ CrossOtrObserver::~CrossOtrObserver() = default; -bool CrossOtrObserver::IsCrossOtrState() { +bool CrossOtrObserver::IsCrossOtrState() const { return protecting_navigations_; } @@ -95,13 +92,16 @@ // Metrics will not be collected for non intervened navigation chains and // navigations occurring prior to params filtering. if (headers && did_filter_params_) { - base::UmaHistogramSparse( - kCrossOtrResponseCodeMetricName, + WriteResponseMetric( net::HttpUtil::MapStatusCodeForHistogram(headers->response_code())); } - } else if (navigation_handle->GetReloadType() != content::ReloadType::NONE) { + return; + } + if (navigation_handle->GetReloadType() != content::ReloadType::NONE) { refresh_count_++; - } else if (navigation_handle->HasCommitted() && !protecting_navigations_) { + return; + } + if (navigation_handle->HasCommitted() && !protecting_navigations_) { Detach(); // DO NOT add code past this point. `this` is destroyed. } @@ -125,8 +125,7 @@ // navigations occurring prior to params filtering. if (protecting_navigations_ && headers && did_filter_params_ && !IsInternalRedirect(headers)) { - base::UmaHistogramSparse( - kCrossOtrResponseCodeMetricName, + WriteResponseMetric( net::HttpUtil::MapStatusCodeForHistogram(headers->response_code())); } } @@ -150,8 +149,7 @@ // Metrics will not be collected for non intervened navigation chains and // navigations occurring prior to params filtering. if (did_filter_params_) { - base::UmaHistogramCounts100(kCrossOtrRefreshCountMetricName, - refresh_count_); + WriteRefreshMetric(refresh_count_); } web_contents()->RemoveUserData(CrossOtrObserver::UserDataKey()); // DO NOT add code past this point. `this` is destroyed. @@ -161,8 +159,42 @@ return weak_factory_.GetWeakPtr(); } -void CrossOtrObserver::SetDidFilterParams(bool value) { +void CrossOtrObserver::SetDidFilterParams( + bool value, + ClassificationExperimentStatus experiment_status) { did_filter_params_ = value; + // If we have already seen experimental params, treat all metrics as coming + // after an experimental param classification. In other words, we consider all + // response codes/refresh counts after an experimental param has been stripped + // as being influenced by that experimental parameter removal. + if (experiment_status_ != ClassificationExperimentStatus::EXPERIMENTAL) { + experiment_status_ = experiment_status; + } +} + +void CrossOtrObserver::WriteRefreshMetric(int refresh_count) { + // If we used experimental classifications, write the experimental metric in + // addition to the standard one for additional segmentation (default vs + // experimental). + if (experiment_status_ == ClassificationExperimentStatus::EXPERIMENTAL) { + base::UmaHistogramCounts100( + "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental", + refresh_count); + } + base::UmaHistogramCounts100("Navigation.CrossOtr.ContextMenu.RefreshCount", + refresh_count); +} +void CrossOtrObserver::WriteResponseMetric(int response_code) { + // If we used experimental classifications, write the experimental metric in + // addition to the standard one for additional segmentation (default vs + // experimental). + if (experiment_status_ == ClassificationExperimentStatus::EXPERIMENTAL) { + base::UmaHistogramSparse( + "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental", + response_code); + } + base::UmaHistogramSparse("Navigation.CrossOtr.ContextMenu.ResponseCode", + response_code); } WEB_CONTENTS_USER_DATA_KEY_IMPL(CrossOtrObserver);
diff --git a/components/url_param_filter/content/cross_otr_observer.h b/components/url_param_filter/content/cross_otr_observer.h index 39227c8..6585cc8 100644 --- a/components/url_param_filter/content/cross_otr_observer.h +++ b/components/url_param_filter/content/cross_otr_observer.h
@@ -6,6 +6,7 @@ #define COMPONENTS_URL_PARAM_FILTER_CONTENT_CROSS_OTR_OBSERVER_H_ #include "base/memory/weak_ptr.h" +#include "components/url_param_filter/core/url_param_classifications_loader.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "ui/base/page_transition_types.h" @@ -21,6 +22,9 @@ // regardless of cause, detaches. Note that for our purposes, navigation above // refers to top-level, main frame navigations only; we do not consider e.g., // subframe loads. +// +// Changes made to the logic in this observer should also be made on the ios +// equivalent CrossOtrTabHelper at components/url_param_filter/ios. class CrossOtrObserver : public content::WebContentsObserver, public content::WebContentsUserData<CrossOtrObserver> { public: @@ -32,7 +36,7 @@ bool is_cross_otr, bool started_from_context_menu, ui::PageTransition transition); - bool IsCrossOtrState(); + bool IsCrossOtrState() const; // content::WebContentsObserver: void DidStartNavigation( content::NavigationHandle* navigation_handle) override; @@ -51,8 +55,10 @@ base::WeakPtr<CrossOtrObserver> GetWeakPtr(); // Inform the observer that params were filtered, which means metrics should - // be written. - void SetDidFilterParams(bool value); + // be written. `experiment_status` indicates whether the parameters stripped + // were based on experimental classifications. + void SetDidFilterParams(bool value, + ClassificationExperimentStatus experiment_status); private: explicit CrossOtrObserver(content::WebContents* web_contents); @@ -60,6 +66,12 @@ friend class content::WebContentsUserData<CrossOtrObserver>; // Flushes metrics and removes the observer from the WebContents. void Detach(); + + // Writes response code metric(s) to monitor for potential breakge. + void WriteResponseMetric(int response_code); + + // Writes refresh count metric(s) to monitor for potential breakage. + void WriteRefreshMetric(int refresh_count); // Drives state machine logic; we write the cross-OTR response code metric // only for the first navigation, which is that which would have parameters // filtered. @@ -74,6 +86,8 @@ // client redirect. bool protecting_navigations_ = true; bool did_filter_params_ = false; + ClassificationExperimentStatus experiment_status_ = + ClassificationExperimentStatus::NON_EXPERIMENTAL; WEB_CONTENTS_USER_DATA_KEY_DECL(); base::WeakPtrFactory<CrossOtrObserver> weak_factory_;
diff --git a/components/url_param_filter/content/cross_otr_observer_unittest.cc b/components/url_param_filter/content/cross_otr_observer_unittest.cc index aca1e08..c92e2f10 100644 --- a/components/url_param_filter/content/cross_otr_observer_unittest.cc +++ b/components/url_param_filter/content/cross_otr_observer_unittest.cc
@@ -4,6 +4,7 @@ #include "components/url_param_filter/content/cross_otr_observer.h" +#include "components/url_param_filter/core/url_param_classifications_loader.h" #include "content/public/browser/reload_type.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" @@ -19,64 +20,57 @@ namespace url_param_filter { -constexpr char kResponseCodeMetricName[] = +constexpr char kExperimentalResponseCodeMetricName[] = "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental"; -constexpr char kCrossOtrRefreshCountMetricName[] = +constexpr char kResponseCodeMetricName[] = + "Navigation.CrossOtr.ContextMenu.ResponseCode"; +constexpr char kExperimentalCrossOtrRefreshCountMetricName[] = "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental"; +constexpr char kCrossOtrRefreshCountMetricName[] = + "Navigation.CrossOtr.ContextMenu.RefreshCount"; class CrossOtrObserverTest : public content::RenderViewHostTestHarness { public: CrossOtrObserverTest() = default; - - std::unique_ptr<content::MockNavigationHandle> CreateMockNavigationHandle() { - return std::make_unique<NiceMock<content::MockNavigationHandle>>( - GURL("https://example.com/"), main_rfh()); - } }; TEST_F(CrossOtrObserverTest, NotContextMenuInitiated) { CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/web_contents(), /*is_cross_otr=*/false, - /*started_from_context_menu=*/false, - /*transition=*/ui::PAGE_TRANSITION_LINK); + web_contents(), /*is_cross_otr=*/false, + /*started_from_context_menu=*/false, ui::PAGE_TRANSITION_LINK); ASSERT_EQ(CrossOtrObserver::FromWebContents(web_contents()), nullptr); } TEST_F(CrossOtrObserverTest, DefaultSensitivity) { CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/web_contents(), /*is_cross_otr=*/false, - /*started_from_context_menu=*/false, - /*transition=*/ui::PAGE_TRANSITION_LINK); + web_contents(), /*is_cross_otr=*/false, + /*started_from_context_menu=*/false, ui::PAGE_TRANSITION_LINK); ASSERT_EQ(CrossOtrObserver::FromWebContents(web_contents()), nullptr); } TEST_F(CrossOtrObserverTest, BookmarkLink) { CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/web_contents(), /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_AUTO_BOOKMARK); + web_contents(), /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_AUTO_BOOKMARK); ASSERT_EQ(CrossOtrObserver::FromWebContents(web_contents()), nullptr); } TEST_F(CrossOtrObserverTest, CreateKey) { content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); ASSERT_NE(CrossOtrObserver::FromWebContents(contents), nullptr); } TEST_F(CrossOtrObserverTest, DuplicateCreateKey) { content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); ASSERT_NE(CrossOtrObserver::FromWebContents(contents), nullptr); } @@ -84,13 +78,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); @@ -117,13 +111,107 @@ kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(307), 2); } +TEST_F(CrossOtrObserverTest, HandleRedirectsExperimentalMetrics) { + base::HistogramTester histogram_tester; + content::WebContents* contents = web_contents(); + CrossOtrObserver::MaybeCreateForWebContents( + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); + CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); + + // Simulate params filtering, making it okay to collect metrics. + observer->SetDidFilterParams(true, + ClassificationExperimentStatus::EXPERIMENTAL); + + ASSERT_NE(observer, nullptr); + + std::vector<const std::string> redirect_sequence{ + "HTTP/1.1 302 Moved Temporarily", + "HTTP/1.1 307 Temporary Redirect", // 2 'external' 307 redirects + "HTTP/1.1 307 Temporary Redirect", + "HTTP/1.1 307 Internal Redirect" // 1 internal 307 redirect, is omitted + }; + for (auto redirect_header : redirect_sequence) { + std::unique_ptr<content::MockNavigationHandle> handle = + std::make_unique<NiceMock<content::MockNavigationHandle>>(contents); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>(redirect_header); + handle->set_response_headers(response); + observer->DidRedirectNavigation(handle.get()); + } + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 3); + histogram_tester.ExpectBucketCount( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(302), + 1); + histogram_tester.ExpectBucketCount( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(307), + 2); + histogram_tester.ExpectTotalCount(kExperimentalResponseCodeMetricName, 3); + histogram_tester.ExpectBucketCount( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(302), 1); + histogram_tester.ExpectBucketCount( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(307), 2); +} +TEST_F(CrossOtrObserverTest, + HandleRedirectsExperimentalAndNonExperimentalMetrics) { + base::HistogramTester histogram_tester; + content::WebContents* contents = web_contents(); + CrossOtrObserver::MaybeCreateForWebContents( + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); + CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); + + // Simulate params filtering, making it okay to collect metrics. + // The `ClassificationExperimentStatus::EXPERIMENTAL` should take precedence, + // since we consider an experimental metric filtered anywhere in the + // navigation to mean the results after are contingent on that parameter's + // removal. + observer->SetDidFilterParams(true, + ClassificationExperimentStatus::EXPERIMENTAL); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); + + ASSERT_NE(observer, nullptr); + + std::vector<const std::string> redirect_sequence{ + "HTTP/1.1 302 Moved Temporarily", + "HTTP/1.1 307 Temporary Redirect", // 2 'external' 307 redirects + "HTTP/1.1 307 Temporary Redirect", + "HTTP/1.1 307 Internal Redirect" // 1 internal 307 redirect, is omitted + }; + for (auto redirect_header : redirect_sequence) { + std::unique_ptr<content::MockNavigationHandle> handle = + std::make_unique<NiceMock<content::MockNavigationHandle>>(contents); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>(redirect_header); + handle->set_response_headers(response); + observer->DidRedirectNavigation(handle.get()); + } + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 3); + histogram_tester.ExpectBucketCount( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(302), + 1); + histogram_tester.ExpectBucketCount( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(307), + 2); + histogram_tester.ExpectTotalCount(kExperimentalResponseCodeMetricName, 3); + histogram_tester.ExpectBucketCount( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(302), 1); + histogram_tester.ExpectBucketCount( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(307), 2); +} TEST_F(CrossOtrObserverTest, HandleRedirectsNoParamsFiltering) { base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -143,13 +231,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -167,13 +255,53 @@ kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), 1); } +TEST_F(CrossOtrObserverTest, + FinishedNavigationNonExperimentalThenExperimental) { + base::HistogramTester histogram_tester; + content::WebContents* contents = web_contents(); + CrossOtrObserver::MaybeCreateForWebContents( + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); + CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); + + // Simulate params filtering, making it okay to collect metrics. + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); + + ASSERT_NE(observer, nullptr); + std::unique_ptr<content::MockNavigationHandle> handle = + std::make_unique<NiceMock<content::MockNavigationHandle>>(contents); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + handle->set_response_headers(response); + observer->DidStartNavigation(handle.get()); + observer->DidFinishNavigation(handle.get()); + + observer->SetDidFilterParams(true, + ClassificationExperimentStatus::EXPERIMENTAL); + observer->DidFinishNavigation(handle.get()); + + ASSERT_TRUE(observer->IsCrossOtrState()); + // We first filtered params with non-experimental params, then filtered an + // experimental param. Both metrics should be written, with responses showing + // in the normal metric and only the experimental result in the experimental + // metric. + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 2); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 2); + histogram_tester.ExpectTotalCount(kExperimentalResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(200), 1); +} TEST_F(CrossOtrObserverTest, FinishedNavigationNoParamsFiltering) { base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -195,13 +323,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -215,13 +343,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -241,13 +369,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -271,13 +399,54 @@ kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), 1); } +TEST_F(CrossOtrObserverTest, RefreshedAfterNavigationExperimental) { + base::HistogramTester histogram_tester; + content::WebContents* contents = web_contents(); + CrossOtrObserver::MaybeCreateForWebContents( + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); + CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); + + // Simulate params filtering, making it okay to collect metrics. + observer->SetDidFilterParams(true, + ClassificationExperimentStatus::EXPERIMENTAL); + + ASSERT_NE(observer, nullptr); + std::unique_ptr<content::MockNavigationHandle> handle = + std::make_unique<NiceMock<content::MockNavigationHandle>>(contents); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + handle->set_response_headers(response); + observer->DidStartNavigation(handle.get()); + observer->DidFinishNavigation(handle.get()); + + handle->set_reload_type(content::ReloadType::NORMAL); + observer->DidStartNavigation(handle.get()); + observer->DidFinishNavigation(handle.get()); + observer->WebContentsDestroyed(); + + histogram_tester.ExpectTotalCount(kExperimentalCrossOtrRefreshCountMetricName, + 1); + ASSERT_EQ( + histogram_tester.GetTotalSum(kExperimentalCrossOtrRefreshCountMetricName), + 1); + // An experimental classification was used, so both metrics should be written. + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 1); + histogram_tester.ExpectTotalCount(kExperimentalResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kExperimentalResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(200), 1); +} TEST_F(CrossOtrObserverTest, RefreshedAfterNavigationNoParamsFiltering) { base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); @@ -306,13 +475,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -357,9 +526,8 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -403,13 +571,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -451,13 +619,13 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); // Simulate params filtering, making it okay to collect metrics. - observer->SetDidFilterParams(true); + observer->SetDidFilterParams( + true, ClassificationExperimentStatus::NON_EXPERIMENTAL); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -494,9 +662,8 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -533,9 +700,8 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle = @@ -566,9 +732,8 @@ base::HistogramTester histogram_tester; content::WebContents* contents = web_contents(); CrossOtrObserver::MaybeCreateForWebContents( - /*web_contents=*/contents, /*is_cross_otr=*/true, - /*started_from_context_menu=*/true, - /*transition=*/ui::PAGE_TRANSITION_LINK); + contents, /*is_cross_otr=*/true, + /*started_from_context_menu=*/true, ui::PAGE_TRANSITION_LINK); CrossOtrObserver* observer = CrossOtrObserver::FromWebContents(contents); ASSERT_NE(observer, nullptr); std::unique_ptr<content::MockNavigationHandle> handle =
diff --git a/components/url_param_filter/content/url_param_filter_throttle.cc b/components/url_param_filter/content/url_param_filter_throttle.cc index e96dadea..104645b 100644 --- a/components/url_param_filter/content/url_param_filter_throttle.cc +++ b/components/url_param_filter/content/url_param_filter_throttle.cc
@@ -10,6 +10,7 @@ #include "base/metrics/histogram_functions.h" #include "components/url_param_filter/content/cross_otr_observer.h" #include "components/url_param_filter/core/features.h" +#include "components/url_param_filter/core/url_param_classifications_loader.h" #include "components/url_param_filter/core/url_param_filterer.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/redirect_info.h" @@ -17,12 +18,19 @@ namespace url_param_filter { namespace { - // Write metrics about results of param filtering. void WriteMetrics(FilterResult result) { - base::UmaHistogramCounts100( - "Navigation.UrlParamFilter.FilteredParamCountExperimental", - result.filtered_param_count); + // When experimental classifications are used, write a metric indicating this. + // This allows validation of experimental results as being due to the + // experiment vs filtering that would happen regardless. + if (result.experimental_status == + ClassificationExperimentStatus::EXPERIMENTAL) { + base::UmaHistogramCounts100( + "Navigation.UrlParamFilter.FilteredParamCountExperimental", + result.filtered_param_count); + } + base::UmaHistogramCounts100("Navigation.UrlParamFilter.FilteredParamCount", + result.filtered_param_count); } } // anonymous namespace @@ -80,7 +88,7 @@ } if (observer_ && result.filtered_param_count) { - observer_->SetDidFilterParams(true); + observer_->SetDidFilterParams(true, result.experimental_status); } last_hop_initiator_ = request->url; } @@ -101,7 +109,7 @@ } if (observer_ && result.filtered_param_count) { - observer_->SetDidFilterParams(true); + observer_->SetDidFilterParams(true, result.experimental_status); } // Future redirects should use the redirect's domain as the navigation
diff --git a/components/url_param_filter/content/url_param_filter_throttle_unittest.cc b/components/url_param_filter/content/url_param_filter_throttle_unittest.cc index e71ab8b..5b45ed25 100644 --- a/components/url_param_filter/content/url_param_filter_throttle_unittest.cc +++ b/components/url_param_filter/content/url_param_filter_throttle_unittest.cc
@@ -20,7 +20,7 @@ namespace { constexpr static const char kHistogramName[] = - "Navigation.UrlParamFilter.FilteredParamCountExperimental"; + "Navigation.UrlParamFilter.FilteredParamCount"; } // namespace // Tests the UrlParamFilterThrottle, which is currently a very thin wrapper
diff --git a/components/url_param_filter/core/url_param_classifications_loader.cc b/components/url_param_filter/core/url_param_classifications_loader.cc index 0ea49c0..4f833214 100644 --- a/components/url_param_filter/core/url_param_classifications_loader.cc +++ b/components/url_param_filter/core/url_param_classifications_loader.cc
@@ -19,6 +19,19 @@ namespace url_param_filter { namespace { +constexpr char DEFAULT_TAG[] = "default"; + +bool HasExperimentTag(const FilterClassification& classification, + const std::string& tag) { + // We expect this list to almost never exceed 2 items, making a loop + // acceptable. + for (auto i : classification.experiment_tags()) { + if (i == tag) { + return true; + } + } + return false; +} void AppendParams(ClassificationMap& map, const FilterClassification& classification, @@ -28,7 +41,8 @@ // We retain whether the classification was experimental, however, to write // a separate metric when those classifications are used. map[classification.site()][use_case][param.name()] = - classification.has_experiment_identifier() + !classification.experiment_tags().empty() && + !HasExperimentTag(classification, DEFAULT_TAG) ? ClassificationExperimentStatus::EXPERIMENTAL : ClassificationExperimentStatus::NON_EXPERIMENTAL; } @@ -37,8 +51,8 @@ void ProcessClassification(ClassificationMap& map, const FilterClassification& classification, std::string experiment_identifier) { - if (classification.has_experiment_identifier() && - experiment_identifier != classification.experiment_identifier()) { + if (!experiment_identifier.empty() && + !HasExperimentTag(classification, experiment_identifier)) { return; } if (classification.use_cases_size() > 0) { @@ -64,8 +78,8 @@ for (auto i : classifications.classifications()) { if (i.site_role() == role) { // When retrieving classifications from the feature, we do not allow - // additional experiment overrides; we instead use the default "". - DCHECK(!i.has_experiment_identifier()); + // additional experiment overrides. + DCHECK(i.experiment_tags().empty()); ProcessClassification(map, i, ""); } } @@ -83,6 +97,11 @@ ClassificationMap map; std::string experiment_identifier = base::GetFieldTrialParamValueByFeature( features::kIncognitoParamFilterEnabled, "experiment_identifier"); + // If there is no experiment identifier passed via the feature, then use the + // classifications that are marked `default`. + if (experiment_identifier.empty()) { + experiment_identifier = DEFAULT_TAG; + } for (const FilterClassification& classification : classifications.value()) { ProcessClassification(map, classification, experiment_identifier); }
diff --git a/components/url_param_filter/core/url_param_classifications_loader.h b/components/url_param_filter/core/url_param_classifications_loader.h index 2fc4ed3c..d696019 100644 --- a/components/url_param_filter/core/url_param_classifications_loader.h +++ b/components/url_param_filter/core/url_param_classifications_loader.h
@@ -55,7 +55,7 @@ ClassificationsLoader(); ~ClassificationsLoader(); - // Creates a mapping from a site to it's `role` classifications by retrieving + // Creates a mapping from a site to its `role` classifications by retrieving // classifications from either the Component Updater or the feature flag. // If classifications from both are provided, then the feature flag // classifications take precedence.
diff --git a/components/url_param_filter/core/url_param_classifications_loader_unittest.cc b/components/url_param_filter/core/url_param_classifications_loader_unittest.cc index 5a9852e..2c7adebb 100644 --- a/components/url_param_filter/core/url_param_classifications_loader_unittest.cc +++ b/components/url_param_filter/core/url_param_classifications_loader_unittest.cc
@@ -193,7 +193,9 @@ scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIncognitoParamFilterEnabled, params); - // Create proto with both Source + Destination Classifications + // Create proto with both Source + Destination Classifications, with the + // default experiment tag. Because we apply a non-default tag, these should + // not be present. FilterClassifications classifications = MakeClassificationsProtoFromMap( {{kSourceSite, {"plzblock1", "plzblock2"}}}, {{kDestinationSite, {"plzblock3", "plzblock4"}}}); @@ -228,32 +230,22 @@ SetComponentFileContents(classifications.SerializeAsString()); loader()->ReadClassifications(test_file_contents()); - EXPECT_THAT( - loader()->GetDestinationClassifications(), - UnorderedElementsAre( - Pair(Eq(kDestinationSite), - UnorderedElementsAre(Pair( - FilterClassification::USE_CASE_UNKNOWN, - UnorderedElementsAre( - Pair("plzblock3", - ClassificationExperimentStatus::NON_EXPERIMENTAL), - Pair("plzblock4", - ClassificationExperimentStatus::NON_EXPERIMENTAL), - Pair("plzblock5", - ClassificationExperimentStatus::EXPERIMENTAL))))))); - EXPECT_THAT( - loader()->GetSourceClassifications(), - UnorderedElementsAre( - Pair(Eq(kSourceSite), - UnorderedElementsAre(Pair( - FilterClassification::USE_CASE_UNKNOWN, - UnorderedElementsAre( - Pair("plzblock1", - ClassificationExperimentStatus::NON_EXPERIMENTAL), - Pair("plzblock2", - ClassificationExperimentStatus::NON_EXPERIMENTAL), - Pair("plzblock7", - ClassificationExperimentStatus::EXPERIMENTAL))))))); + EXPECT_THAT(loader()->GetDestinationClassifications(), + UnorderedElementsAre(Pair( + Eq(kDestinationSite), + UnorderedElementsAre(Pair( + FilterClassification::USE_CASE_UNKNOWN, + UnorderedElementsAre(Pair( + "plzblock5", + ClassificationExperimentStatus::EXPERIMENTAL))))))); + EXPECT_THAT(loader()->GetSourceClassifications(), + UnorderedElementsAre(Pair( + Eq(kSourceSite), + UnorderedElementsAre(Pair( + FilterClassification::USE_CASE_UNKNOWN, + UnorderedElementsAre(Pair( + "plzblock7", + ClassificationExperimentStatus::EXPERIMENTAL))))))); } TEST_F(UrlParamClassificationsLoaderTest,
diff --git a/components/url_param_filter/core/url_param_filter_classification.proto b/components/url_param_filter/core/url_param_filter_classification.proto index 2bf3d622..e931663 100644 --- a/components/url_param_filter/core/url_param_filter_classification.proto +++ b/components/url_param_filter/core/url_param_filter_classification.proto
@@ -27,7 +27,7 @@ optional SiteRole site_role = 2; // required repeated FilterParameter parameters = 3; repeated UseCase use_cases = 4 [packed = true]; - optional string experiment_identifier = 5; + repeated string experiment_tags = 5; } message FilterClassifications {
diff --git a/components/url_param_filter/core/url_param_filter_test_helper.cc b/components/url_param_filter/core/url_param_filter_test_helper.cc index a58bae5..fa17d43 100644 --- a/components/url_param_filter/core/url_param_filter_test_helper.cc +++ b/components/url_param_filter/core/url_param_filter_test_helper.cc
@@ -12,6 +12,7 @@ namespace url_param_filter { namespace { +constexpr char DEFAULT_TAG[] = "default"; std::map<std::string, std::map<FilterClassification::UseCase, std::vector<std::string>>> ConvertToDefaultUseCases( @@ -58,7 +59,8 @@ std::vector<std::string>>>& source_params, const std::map<std::string, std::map<FilterClassification::UseCase, - std::vector<std::string>>>& destination_params) { + std::vector<std::string>>>& destination_params, + const std::vector<std::string>& experiment_tags) { url_param_filter::FilterClassifications classifications; for (auto i : CreateClassificationMapForTesting( source_params, url_param_filter::FilterClassification_SiteRole:: @@ -66,6 +68,9 @@ for (auto j : i.second) { url_param_filter::FilterClassification classification; classification.set_site(i.first); + for (auto i : experiment_tags) { + classification.add_experiment_tags(i); + } classification.set_site_role( url_param_filter::FilterClassification::SOURCE); if (j.first != FilterClassification::USE_CASE_UNKNOWN) { @@ -85,6 +90,9 @@ for (auto j : i.second) { url_param_filter::FilterClassification classification; classification.set_site(i.first); + for (auto i : experiment_tags) { + classification.add_experiment_tags(i); + } classification.set_site_role( url_param_filter::FilterClassification::DESTINATION); if (j.first != FilterClassification::USE_CASE_UNKNOWN) { @@ -103,10 +111,11 @@ std::string CreateSerializedUrlParamFilterClassificationForTesting( const std::map<std::string, std::vector<std::string>>& source_params, - const std::map<std::string, std::vector<std::string>>& destination_params) { + const std::map<std::string, std::vector<std::string>>& destination_params, + const std::vector<std::string>& experiment_tags) { return CreateSerializedUrlParamFilterClassificationForTesting( ConvertToDefaultUseCases(source_params), - ConvertToDefaultUseCases(destination_params)); + ConvertToDefaultUseCases(destination_params), experiment_tags); } std::string CreateBase64EncodedFilterParamClassificationForTesting( @@ -119,7 +128,7 @@ std::string compressed; compression::GzipCompress( CreateSerializedUrlParamFilterClassificationForTesting( - source_params, destination_params), + source_params, destination_params, {}), &compressed); std::string out; base::Base64Encode(compressed, &out); @@ -132,7 +141,7 @@ std::string compressed; compression::GzipCompress( CreateSerializedUrlParamFilterClassificationForTesting( - source_params, destination_params), + source_params, destination_params, {}), &compressed); std::string out; base::Base64Encode(compressed, &out); @@ -151,14 +160,14 @@ for (const auto& [use_case, params] : param_map) { AddClassification(classifications.add_classifications(), site, FilterClassification_SiteRole_SOURCE, params, - {use_case}, ""); + {use_case}, {DEFAULT_TAG}); } } for (const auto& [site, param_map] : dest_map) { for (const auto& [use_case, params] : param_map) { AddClassification(classifications.add_classifications(), site, FilterClassification_SiteRole_DESTINATION, params, - {use_case}, ""); + {use_case}, {DEFAULT_TAG}); } } return classifications; @@ -172,12 +181,12 @@ for (const auto& [site, params] : source_map) { AddClassification(classifications.add_classifications(), site, FilterClassification_SiteRole_SOURCE, params, use_cases, - ""); + {}); } for (const auto& [site, params] : dest_map) { AddClassification(classifications.add_classifications(), site, FilterClassification_SiteRole_DESTINATION, params, - use_cases, ""); + use_cases, {}); } return classifications; } @@ -186,7 +195,7 @@ const std::string& site, FilterClassification_SiteRole role, const std::vector<std::string>& params) { - return MakeFilterClassification(site, role, params, {}, ""); + return MakeFilterClassification(site, role, params, {}, DEFAULT_TAG); } FilterClassification MakeFilterClassification( @@ -194,7 +203,7 @@ FilterClassification_SiteRole role, const std::vector<std::string>& params, const std::vector<FilterClassification::UseCase>& use_cases) { - return MakeFilterClassification(site, role, params, use_cases, ""); + return MakeFilterClassification(site, role, params, use_cases, DEFAULT_TAG); } FilterClassification MakeFilterClassification( @@ -204,7 +213,8 @@ const std::vector<FilterClassification::UseCase>& use_cases, const std::string& experiment_identifier) { FilterClassification fc; - AddClassification(&fc, site, role, params, use_cases, experiment_identifier); + AddClassification(&fc, site, role, params, use_cases, + {experiment_identifier}); return fc; } @@ -214,13 +224,17 @@ FilterClassification_SiteRole role, const std::vector<std::string>& params, const std::vector<FilterClassification::UseCase>& use_cases, - const std::string& experiment_identifier) { + const std::vector<std::string>& experiment_tags) { classification->set_site(site); classification->set_site_role(role); // The proto distinguishes between empty and not set; for the purposes of this // test helper, we avoid empty being considered an experiment. - if (!experiment_identifier.empty()) { - classification->set_experiment_identifier(experiment_identifier); + if (!experiment_tags.empty()) { + for (auto i : experiment_tags) { + classification->add_experiment_tags(i); + } + } else { + classification->add_experiment_tags(DEFAULT_TAG); } for (const FilterClassification::UseCase& use_case : use_cases) { classification->add_use_cases(use_case);
diff --git a/components/url_param_filter/core/url_param_filter_test_helper.h b/components/url_param_filter/core/url_param_filter_test_helper.h index a4828f6..97bc294 100644 --- a/components/url_param_filter/core/url_param_filter_test_helper.h +++ b/components/url_param_filter/core/url_param_filter_test_helper.h
@@ -42,13 +42,15 @@ std::vector<std::string>>>& source_params, const std::map<std::string, std::map<FilterClassification::UseCase, - std::vector<std::string>>>& destination_params); + std::vector<std::string>>>& destination_params, + const std::vector<std::string>& experiment_tags); // Equivalent to the other overload, but uses empty use case lists for all // parameters. std::string CreateSerializedUrlParamFilterClassificationForTesting( const std::map<std::string, std::vector<std::string>>& source_params, - const std::map<std::string, std::vector<std::string>>& destination_params); + const std::map<std::string, std::vector<std::string>>& destination_params, + const std::vector<std::string>& experiment_tags); // Create a base64 representation of the URL param filter classifications // proto. Used for initialization of the feature params in tests. @@ -112,6 +114,6 @@ FilterClassification_SiteRole role, const std::vector<std::string>& params, const std::vector<FilterClassification::UseCase>& use_cases, - const std::string& experiment_identifier); + const std::vector<std::string>& experiment_tags); } // namespace url_param_filter #endif // COMPONENTS_URL_PARAM_FILTER_CORE_URL_PARAM_FILTER_TEST_HELPER_H_
diff --git a/components/url_param_filter/ios/BUILD.gn b/components/url_param_filter/ios/BUILD.gn new file mode 100644 index 0000000..063acaa --- /dev/null +++ b/components/url_param_filter/ios/BUILD.gn
@@ -0,0 +1,37 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +source_set("ios") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "cross_otr_tab_helper.h", + "cross_otr_tab_helper.mm", + ] + deps = [ + "//base", + "//components/url_param_filter/core", + "//ios/web/public:public", + "//ios/web/public:web_state_observer", + "//ios/web/public/navigation:navigation", + "//ui/base:base", + ] +} + +source_set("unit_tests") { + testonly = true + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ "cross_otr_tab_helper_unittest.mm" ] + deps = [ + ":ios", + "//base/test:test_support", + "//components/url_param_filter/core:core", + "//components/url_param_filter/core:test_support", + "//components/url_param_filter/core:url_param_filter_classification_proto", + "//ios/web/public/test", + "//ios/web/public/test:test_fixture", + "//ios/web/public/test/fakes:fakes", + "//testing/gtest", + "//ui/base", + "//url", + ] +}
diff --git a/components/url_param_filter/ios/DEPS b/components/url_param_filter/ios/DEPS new file mode 100644 index 0000000..65222662 --- /dev/null +++ b/components/url_param_filter/ios/DEPS
@@ -0,0 +1,5 @@ +include_rules = [ + "+ios/web/public", + "+ios/web/public/test", + "+components/url_param_filter/core", +]
diff --git a/components/url_param_filter/ios/cross_otr_tab_helper.h b/components/url_param_filter/ios/cross_otr_tab_helper.h new file mode 100644 index 0000000..c154d41e --- /dev/null +++ b/components/url_param_filter/ios/cross_otr_tab_helper.h
@@ -0,0 +1,74 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_URL_PARAM_FILTER_IOS_CROSS_OTR_TAB_HELPER_H_ +#define COMPONENTS_URL_PARAM_FILTER_IOS_CROSS_OTR_TAB_HELPER_H_ + +#include "ios/web/public/navigation/navigation_context.h" +#include "ios/web/public/web_state.h" +#include "ios/web/public/web_state_observer.h" +#include "ios/web/public/web_state_user_data.h" +#include "ui/base/page_transition_types.h" + +namespace web { +class WebState; +class NavigationContext; +} // namespace web + +namespace url_param_filter { + +// This class is created to measure the effect of experimentally filtering +// URLs. It is only attached to WebStates created via an "Open In Incognito" +// press. +// +// The state-machine logic measuring refreshes in class should be kept in sync +// with the CrossOtrObserver at components/url_param_filter/content/ which +// performs similar observations. +class CrossOtrTabHelper : public web::WebStateObserver, + public web::WebStateUserData<CrossOtrTabHelper> { + public: + ~CrossOtrTabHelper() override; + + // Attaches the observer in cases where it should do so; leaves `web_state` + // unchanged otherwise. + static void CreateForWebState(web::WebState* web_state); + + // web::WebStateObserver: + void DidStartNavigation(web::WebState* web_state, + web::NavigationContext* navigation_context) override; + void DidFinishNavigation(web::WebState* web_state, + web::NavigationContext* navigation_context) override; + void WebStateDestroyed(web::WebState* web_state) override; + + // Returns whether this observer is in Cross-OTR state, used for testing. + bool GetCrossOtrStateForTesting() const; + + private: + CrossOtrTabHelper(web::WebState* web_state); + friend class WebStateUserData<CrossOtrTabHelper>; + + // Flushes metrics and removes the observer from the WebState. + void Detach(web::WebState* web_state); + + // Drives state machine logic; we write the cross-OTR response code metric + // only for the first navigation, which is that which would have parameters + // filtered. + bool observed_response_ = false; + + // Tracks refreshes observed, which could point to an issue with param + // filtering causing unexpected behavior for the user. + int refresh_count_ = 0; + + // Whether top-level navigations should have filtering applied. Starts true + // then switches to false once a navigation completes and then either: + // user interaction is observed or a new navigation starts that is not a + // client redirect. + bool protecting_navigations_ = true; + + WEB_STATE_USER_DATA_KEY_DECL(); +}; + +} // namespace url_param_filter + +#endif // COMPONENTS_URL_PARAM_FILTER_IOS_CROSS_OTR_TAB_HELPER_H_
diff --git a/components/url_param_filter/ios/cross_otr_tab_helper.mm b/components/url_param_filter/ios/cross_otr_tab_helper.mm new file mode 100644 index 0000000..aad6c29 --- /dev/null +++ b/components/url_param_filter/ios/cross_otr_tab_helper.mm
@@ -0,0 +1,126 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/url_param_filter/ios/cross_otr_tab_helper.h" + +#include "base/feature_list.h" +#include "base/metrics/histogram_functions.h" +#include "components/url_param_filter/core/features.h" +#include "ios/web/public/browser_state.h" +#include "ios/web/public/navigation/navigation_context.h" +#include "ios/web/public/web_state.h" +#include "ios/web/public/web_state_observer.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" +#include "ui/base/page_transition_types.h" + +namespace url_param_filter { + +namespace { + +constexpr char kCrossOtrRefreshCountMetricName[] = + "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental"; +constexpr char kCrossOtrResponseCodeMetricName[] = + "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental"; + +// Returns true if the web_state corresponds to one where a user enters +// incognito by long-pressing on an embedded link and selecting "Open In +// Incognito". +bool IsOpenInIncognito(web::WebState* web_state, + web::NavigationContext* navigation_context) { + // "Open In Incognito" that creates an OTR browser state causes a TYPED + // transition. + return navigation_context->HasUserGesture() && + ui::PageTransitionCoreTypeIs(navigation_context->GetPageTransition(), + ui::PAGE_TRANSITION_TYPED); +} +} // namespace + +// static +void CrossOtrTabHelper::CreateForWebState(web::WebState* web_state) { + DCHECK(web_state); + WebStateUserData<CrossOtrTabHelper>::CreateForWebState(web_state); +} + +CrossOtrTabHelper::CrossOtrTabHelper(web::WebState* web_state) { + DCHECK(web_state); + web_state->AddObserver(this); +} + +CrossOtrTabHelper::~CrossOtrTabHelper() = default; + +void CrossOtrTabHelper::DidStartNavigation( + web::WebState* web_state, + web::NavigationContext* navigation_context) { + if (!observed_response_) { + protecting_navigations_ = IsOpenInIncognito(web_state, navigation_context); + return; + } + + if (!(navigation_context->GetPageTransition() & + ui::PAGE_TRANSITION_CLIENT_REDIRECT) || + navigation_context->HasUserGesture()) { + // If a navigation that isn't a client redirect occurs, or a user-activated + // navigation occurs we stop protecting navigations. + protecting_navigations_ = false; + } +} + +void CrossOtrTabHelper::DidFinishNavigation( + web::WebState* web_state, + web::NavigationContext* navigation_context) { + // web::NavigationContext doesn't expose whether or not it's a main frame + // navigation. + if (navigation_context->IsSameDocument()) { + // We only are concerned with non-same doc navigations. + return; + } + // We only want the first navigation, including client redirects occurring + // without having observed user activation, to be counted; after that, no + // response codes should be tracked. The observer is left in place to track + // refreshes on the first page. + if (protecting_navigations_) { + observed_response_ = true; + const net::HttpResponseHeaders* headers = + navigation_context->GetResponseHeaders(); + // TODO(https://crbug.com/1324194) See comment two about restricting metric + // collection here. + if (headers) { + base::UmaHistogramSparse( + kCrossOtrResponseCodeMetricName, + net::HttpUtil::MapStatusCodeForHistogram(headers->response_code())); + } + return; + } + if (ui::PageTransitionCoreTypeIs(navigation_context->GetPageTransition(), + ui::PAGE_TRANSITION_RELOAD)) { + refresh_count_++; + return; + } + if (navigation_context->HasCommitted() && !protecting_navigations_) { + Detach(web_state); + // DO NOT add code past this point. `this` is destroyed. + } +} + +void CrossOtrTabHelper::WebStateDestroyed(web::WebState* web_state) { + Detach(web_state); + // DO NOT add code past this point. `this` is destroyed. +} + +bool CrossOtrTabHelper::GetCrossOtrStateForTesting() const { + return protecting_navigations_; +} + +void CrossOtrTabHelper::Detach(web::WebState* web_state) { + // TODO(https://crbug.com/1324194) See comment two about restricting metric + // collection here. + base::UmaHistogramCounts100(kCrossOtrRefreshCountMetricName, refresh_count_); + web_state->RemoveObserver(this); + web_state->RemoveUserData(CrossOtrTabHelper::UserDataKey()); +} + +WEB_STATE_USER_DATA_KEY_IMPL(CrossOtrTabHelper) + +} // namespace url_param_filter
diff --git a/components/url_param_filter/ios/cross_otr_tab_helper_unittest.mm b/components/url_param_filter/ios/cross_otr_tab_helper_unittest.mm new file mode 100644 index 0000000..1f35ff9 --- /dev/null +++ b/components/url_param_filter/ios/cross_otr_tab_helper_unittest.mm
@@ -0,0 +1,270 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/url_param_filter/ios/cross_otr_tab_helper.h" + +#include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" +#include "ios/web/public/test/fakes/fake_browser_state.h" +#include "ios/web/public/test/fakes/fake_navigation_context.h" +#include "ios/web/public/test/fakes/fake_web_state.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/platform_test.h" + +namespace web { +class FakeNavigationContext; +class FakeBrowserState; +} // namespace web + +namespace url_param_filter { + +constexpr char kResponseCodeMetricName[] = + "Navigation.CrossOtr.ContextMenu.ResponseCodeExperimental"; +constexpr char kCrossOtrRefreshCountMetricName[] = + "Navigation.CrossOtr.ContextMenu.RefreshCountExperimental"; + +class CrossOtrTabHelperTest : public PlatformTest { + public: + CrossOtrTabHelperTest() : PlatformTest() { + // Create new OTR web_state to navigate to. + std::unique_ptr<web::FakeWebState> unique_web_state = + std::make_unique<web::FakeWebState>(); + web::FakeBrowserState browser_state; + browser_state.SetOffTheRecord(true); + unique_web_state->SetBrowserState(&browser_state); + web_state_ = unique_web_state.get(); + + // Initialize observer with this web_state. + CrossOtrTabHelper::CreateForWebState(web_state_); + observer_ = CrossOtrTabHelper::FromWebState(web_state_); + + // Create Cross OTR navigation which... + // (1) navigates into OTR + context_.SetWebState(std::move(unique_web_state)); + // (2) transitions into OTR from "Open In Incognito" + context_.SetPageTransition(ui::PAGE_TRANSITION_TYPED); + // (3) is a user-initiated navigation + context_.SetHasUserGesture(true); + } + + protected: + web::FakeWebState* web_state() { return web_state_; }; + CrossOtrTabHelper* observer() { return observer_; }; + web::FakeNavigationContext* context() { return &context_; }; + + private: + base::test::ScopedFeatureList features_; + web::FakeWebState* web_state_; + CrossOtrTabHelper* observer_; + web::FakeNavigationContext context_; +}; + +TEST_F(CrossOtrTabHelperTest, ObserverAttached) { + auto web_state = std::make_unique<web::FakeWebState>(); + CrossOtrTabHelper::CreateForWebState(web_state.get()); + // The observer should have been attached. + ASSERT_NE(CrossOtrTabHelper::FromWebState(web_state.get()), nullptr); +} + +TEST_F(CrossOtrTabHelperTest, CreateKey) { + auto web_state = std::make_unique<web::FakeWebState>(); + CrossOtrTabHelper::CreateForWebState(web_state.get()); + // The observer should have been attached. + ASSERT_NE(CrossOtrTabHelper::FromWebState(web_state.get()), nullptr); +} +TEST_F(CrossOtrTabHelperTest, DuplicateCreateKey) { + auto web_state = std::make_unique<web::FakeWebState>(); + CrossOtrTabHelper::CreateForWebState(web_state.get()); + CrossOtrTabHelper::CreateForWebState(web_state.get()); + // The observer should have been attached. + ASSERT_NE(CrossOtrTabHelper::FromWebState(web_state.get()), nullptr); +} + +TEST_F(CrossOtrTabHelperTest, TransitionsWithNonTypedLink_NotCrossOtr) { + // Create new non-OTR web_state to navigate to. + std::unique_ptr<web::FakeWebState> unique_web_state = + std::make_unique<web::FakeWebState>(); + web::FakeBrowserState browser_state; + browser_state.SetOffTheRecord(true); + unique_web_state->SetBrowserState(&browser_state); + web::FakeWebState* web_state = unique_web_state.get(); + + // Initialize observer with this web_state. + CrossOtrTabHelper::CreateForWebState(web_state); + CrossOtrTabHelper* observer = CrossOtrTabHelper::FromWebState(web_state); + ASSERT_NE(observer, nullptr); + + // Create navigation context. + web::FakeNavigationContext context; + context.SetWebState(std::move(unique_web_state)); + context.SetPageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK); + context.SetHasUserGesture(true); + + // We don't enter cross-OTR state since we didn't navigate to OTR via "Open In + // Incognito". + observer->DidStartNavigation(web_state, &context); + EXPECT_FALSE(observer->GetCrossOtrStateForTesting()); +} + +TEST_F(CrossOtrTabHelperTest, NonUserInitiatedNavigation_NotCrossOtr) { + // Create new non-OTR web_state to navigate to. + std::unique_ptr<web::FakeWebState> unique_web_state = + std::make_unique<web::FakeWebState>(); + web::FakeBrowserState browser_state; + browser_state.SetOffTheRecord(true); + unique_web_state->SetBrowserState(&browser_state); + web::FakeWebState* web_state = unique_web_state.get(); + + // Initialize observer with this web_state. + CrossOtrTabHelper::CreateForWebState(web_state); + CrossOtrTabHelper* observer = CrossOtrTabHelper::FromWebState(web_state); + ASSERT_NE(observer, nullptr); + + // Create navigation context. + web::FakeNavigationContext context; + context.SetWebState(std::move(unique_web_state)); + context.SetPageTransition(ui::PAGE_TRANSITION_TYPED); + context.SetHasUserGesture(false); + + // We don't enter cross-OTR state since we didn't navigate to OTR via + // user-initiated press. + observer->DidStartNavigation(web_state, &context); + EXPECT_FALSE(observer->GetCrossOtrStateForTesting()); +} + +TEST_F(CrossOtrTabHelperTest, FinishedNavigation) { + base::HistogramTester histogram_tester; + ASSERT_NE(observer(), nullptr); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + context()->SetResponseHeaders(response); + + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + ASSERT_TRUE(observer()->GetCrossOtrStateForTesting()); + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 1); +} + +TEST_F(CrossOtrTabHelperTest, BadNavigationResponse) { + base::HistogramTester histogram_tester; + ASSERT_NE(observer(), nullptr); + context()->SetResponseHeaders(nullptr); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 0); + // The observer should not cease observation after first load, regardless of + // whether the headers include a response code. We still want to see + // the refresh count. + ASSERT_NE(CrossOtrTabHelper::FromWebState(web_state()), nullptr); +} +TEST_F(CrossOtrTabHelperTest, RefreshedAfterNavigation) { + base::HistogramTester histogram_tester; + ASSERT_NE(observer(), nullptr); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + context()->SetResponseHeaders(response); + + // Perform the initial navigation. + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + // Simulate a reload. + context()->SetPageTransition(ui::PAGE_TRANSITION_RELOAD); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + observer()->WebStateDestroyed(web_state()); + + histogram_tester.ExpectTotalCount(kCrossOtrRefreshCountMetricName, 1); + ASSERT_EQ(histogram_tester.GetTotalSum(kCrossOtrRefreshCountMetricName), 1); + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 1); +} +TEST_F(CrossOtrTabHelperTest, UncommittedNavigationWithRefresh) { + base::HistogramTester histogram_tester; + ASSERT_NE(observer(), nullptr); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + context()->SetResponseHeaders(response); + + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + ASSERT_TRUE(observer()->GetCrossOtrStateForTesting()); + + // Finish a non-reload navigation, but one that isn't committed (so no + // actual navigation away from the monitored page) + context()->SetPageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK); + context()->SetIsSameDocument(false); + context()->SetHasCommitted(false); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + // We just observed another navigation not due to a client redirect, so + // should no longer be in the cross-OTR state. + ASSERT_FALSE(observer()->GetCrossOtrStateForTesting()); + + // After that uncommitted navigation, trigger a refresh, then destroy. + context()->SetPageTransition(ui::PAGE_TRANSITION_RELOAD); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + observer()->WebStateDestroyed(web_state()); + + // We had 1 relevant refresh. + histogram_tester.ExpectTotalCount(kCrossOtrRefreshCountMetricName, 1); + ASSERT_EQ(histogram_tester.GetTotalSum(kCrossOtrRefreshCountMetricName), 1); + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 1); +} +TEST_F(CrossOtrTabHelperTest, MultipleRefreshesAfterNavigation) { + base::HistogramTester histogram_tester; + ASSERT_NE(observer(), nullptr); + + scoped_refptr<net::HttpResponseHeaders> response = + base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK"); + context()->SetResponseHeaders(response); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + // Reload twice and ensure the count is persisted. + context()->SetPageTransition(ui::PAGE_TRANSITION_RELOAD); + observer()->DidStartNavigation(web_state(), context()); + // With the refresh navigation started, we are no longer in cross-OTR mode. + ASSERT_FALSE(observer()->GetCrossOtrStateForTesting()); + observer()->DidFinishNavigation(web_state(), context()); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + // Navigating away means no more observer. + context()->SetPageTransition(ui::PAGE_TRANSITION_LINK); + context()->SetIsSameDocument(false); + context()->SetHasCommitted(true); + observer()->DidStartNavigation(web_state(), context()); + observer()->DidFinishNavigation(web_state(), context()); + + ASSERT_EQ(CrossOtrTabHelper::FromWebState(web_state()), nullptr); + + histogram_tester.ExpectTotalCount(kCrossOtrRefreshCountMetricName, 1); + ASSERT_EQ(histogram_tester.GetTotalSum(kCrossOtrRefreshCountMetricName), 2); + histogram_tester.ExpectTotalCount(kResponseCodeMetricName, 1); + histogram_tester.ExpectUniqueSample( + kResponseCodeMetricName, net::HttpUtil::MapStatusCodeForHistogram(200), + 1); +} + +} // namespace url_param_filter
diff --git a/components/user_notes/browser/frame_user_note_changes_unittest.cc b/components/user_notes/browser/frame_user_note_changes_unittest.cc index 32a921ff..5fabf4e8 100644 --- a/components/user_notes/browser/frame_user_note_changes_unittest.cc +++ b/components/user_notes/browser/frame_user_note_changes_unittest.cc
@@ -93,8 +93,8 @@ std::vector<base::UnguessableToken> removed; auto mock_changes = std::make_unique<MockFrameUserNoteChanges>( - note_service_->GetSafeRef(), web_contents_list_[0]->GetMainFrame(), added, - modified, removed); + note_service_->GetSafeRef(), web_contents_list_[0]->GetPrimaryMainFrame(), + added, modified, removed); EXPECT_CALL(*mock_changes, MakeNoteInstance(_, _)) .Times(2) @@ -126,8 +126,8 @@ std::vector<base::UnguessableToken> removed; auto mock_changes = std::make_unique<MockFrameUserNoteChanges>( - note_service_->GetSafeRef(), web_contents_list_[0]->GetMainFrame(), added, - modified, removed); + note_service_->GetSafeRef(), web_contents_list_[0]->GetPrimaryMainFrame(), + added, modified, removed); EXPECT_CALL(*mock_changes, MakeNoteInstance(_, _)).Times(0); @@ -158,8 +158,8 @@ std::vector<base::UnguessableToken> removed({note_ids_[0], note_ids_[2]}); auto mock_changes = std::make_unique<MockFrameUserNoteChanges>( - note_service_->GetSafeRef(), web_contents_list_[0]->GetMainFrame(), added, - modified, removed); + note_service_->GetSafeRef(), web_contents_list_[0]->GetPrimaryMainFrame(), + added, modified, removed); EXPECT_CALL(*mock_changes, MakeNoteInstance(_, _)).Times(0);
diff --git a/components/user_notes/browser/user_note_base_test.cc b/components/user_notes/browser/user_note_base_test.cc index f926d56f..5a83fda9 100644 --- a/components/user_notes/browser/user_note_base_test.cc +++ b/components/user_notes/browser/user_note_base_test.cc
@@ -64,7 +64,7 @@ UserNoteManager* UserNoteBaseTest::ConfigureNewManager() { // Create a test frame and navigate it to a unique URL. std::unique_ptr<content::WebContents> wc = CreateTestWebContents(); - content::RenderFrameHostTester::For(wc->GetMainFrame()) + content::RenderFrameHostTester::For(wc->GetPrimaryMainFrame()) ->InitializeRenderFrameIfNeeded(); content::NavigationSimulator::NavigateAndCommitFromBrowser( wc.get(),
diff --git a/components/user_notes/browser/user_note_utils_unittest.cc b/components/user_notes/browser/user_note_utils_unittest.cc index 0c3c6fd..fcaf180 100644 --- a/components/user_notes/browser/user_note_utils_unittest.cc +++ b/components/user_notes/browser/user_note_utils_unittest.cc
@@ -285,7 +285,7 @@ // Create a test frame and navigate it to the specified URL. std::unique_ptr<content::WebContents> wc = CreateTestWebContents(); - content::RenderFrameHostTester::For(wc->GetMainFrame()) + content::RenderFrameHostTester::For(wc->GetPrimaryMainFrame()) ->InitializeRenderFrameIfNeeded(); content::NavigationSimulator::NavigateAndCommitFromBrowser( wc.get(), GURL(frame_config.url)); @@ -313,8 +313,8 @@ } } - frame_to_config_.emplace(wc->GetMainFrame(), frame_config); - config_to_frame_.emplace(frame_config, wc->GetMainFrame()); + frame_to_config_.emplace(wc->GetPrimaryMainFrame(), frame_config); + config_to_frame_.emplace(frame_config, wc->GetPrimaryMainFrame()); web_contents_list_.emplace_back(std::move(wc)); }
diff --git a/components/viz/common/resources/transferable_resource.h b/components/viz/common/resources/transferable_resource.h index 4f07426..6d4d7ec 100644 --- a/components/viz/common/resources/transferable_resource.h +++ b/components/viz/common/resources/transferable_resource.h
@@ -38,9 +38,6 @@ // other words, the resource will be returned only when gpu commands are // completed. kGpuCommandsCompleted, - // Commands submitted (release fence) - a resource will be returned after - // gpu service submitted commands to the gpu and provide the fence. - kReleaseFence, }; TransferableResource();
diff --git a/components/viz/service/display/display_resource_provider.cc b/components/viz/service/display/display_resource_provider.cc index 6f80ebf..766002c 100644 --- a/components/viz/service/display/display_resource_provider.cc +++ b/components/viz/service/display/display_resource_provider.cc
@@ -8,7 +8,6 @@ #include <string> #include "base/atomic_sequence_num.h" -#include "base/notreached.h" #include "base/numerics/safe_math.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" @@ -307,9 +306,9 @@ } } -bool DisplayResourceProvider::ResourceFenceHasPassed( +bool DisplayResourceProvider::ReadLockFenceHasPassed( const ChildResource* resource) { - return !resource->resource_fence || resource->resource_fence->HasPassed(); + return !resource->read_lock_fence || resource->read_lock_fence->HasPassed(); } DisplayResourceProvider::CanDeleteNowResult @@ -323,7 +322,7 @@ // Defer this resource deletion. return CanDeleteNowResult::kNo; - } else if (!ResourceFenceHasPassed(&resource)) { + } else if (!ReadLockFenceHasPassed(&resource)) { // TODO(dcastagna): see if it's possible to use this logic for // the branch above too, where the resource is locked or still exported. // We can't postpone the deletion, so we'll have to lose it.
diff --git a/components/viz/service/display/display_resource_provider.h b/components/viz/service/display/display_resource_provider.h index be07f99..5d89762 100644 --- a/components/viz/service/display/display_resource_provider.h +++ b/components/viz/service/display/display_resource_provider.h
@@ -162,16 +162,10 @@ // Sets the current read fence. If a resource is locked for read // and has read fences enabled, the resource will not allow writes - // until this fence has passed. This is used if a client uses - // TransferableResource::SynchronizationType::kGpuCommandsCompleted. - void SetGpuCommandsCompletedFence(ResourceFence* fence) { - current_gpu_commands_completed_fence_ = fence; + // until this fence has passed. + void SetReadLockFence(ResourceFence* fence) { + current_read_lock_fence_ = fence; } - // Sets the current release fence. If a client uses - // TransferableResource::SynchronizationType::kReleaseFence, resources must be - // returned only after a release fence is stored in this resource fence. - // Returned only when gpu commands and the gpu fence are submitted. - void SetReleaseFence(ResourceFence* fence) { current_release_fence_ = fence; } // Creates accounting for a child. Returns a child ID. surface_id is used to // associate resources to the surface they belong to. This is used for @@ -339,14 +333,12 @@ // mapped for use in the display compositor. base::UnguessableToken shared_bitmap_tracing_guid; - // A fence used for returning resources after the display compositor has - // completed accessing the resources it received from a client. This can - // either be a read lock or a release fence. If the |transferable| has - // synchronization type set as kGpuCommandsCompleted, the resource can be - // returned after ResourceFence::HasPassed is true. If the |transferable| - // has the synchronization type set as kReleaseFence, the resource can be - // returned after the fence has a release fence set. - scoped_refptr<ResourceFence> resource_fence; + // A fence used for accessing a gpu resource for reading, that ensures any + // writing done to the resource has been completed. This is implemented and + // used to implement transferring ownership of the resource from the client + // to the service, and in the GL drawing code before reading from the + // texture. + scoped_refptr<ResourceFence> read_lock_fence; // SkiaRenderer specific details about this resource. Added to ChildResource // to avoid map lookups further down the pipeline. @@ -379,7 +371,10 @@ ChildResource* TryGetResource(ResourceId id); void TryReleaseResource(ResourceId id, ChildResource* resource); - bool ResourceFenceHasPassed(const ChildResource* resource); + // Binds the given GL resource to a texture target for sampling using the + // specified filter for both minification and magnification. Returns the + // texture target used. The resource must be locked for reading. + bool ReadLockFenceHasPassed(const ChildResource* resource); void DeleteAndReturnUnusedResourcesToChild( ChildMap::iterator child_it, @@ -409,8 +404,7 @@ ChildMap children_; base::flat_map<int, std::vector<ResourceId>> batched_returning_resources_; - scoped_refptr<ResourceFence> current_gpu_commands_completed_fence_; - scoped_refptr<ResourceFence> current_release_fence_; + scoped_refptr<ResourceFence> current_read_lock_fence_; // Keep track of whether deleted resources should be batched up or returned // immediately. int batch_return_resources_lock_count_ = 0;
diff --git a/components/viz/service/display/display_resource_provider_skia.cc b/components/viz/service/display/display_resource_provider_skia.cc index 6e4ea305..fcd0506f 100644 --- a/components/viz/service/display/display_resource_provider_skia.cc +++ b/components/viz/service/display/display_resource_provider_skia.cc
@@ -84,13 +84,6 @@ continue; } - if (resource.transferable.synchronization_type == - TransferableResource::SynchronizationType::kReleaseFence) { - // The resource might have never been used. - if (resource.resource_fence) - resource.release_fence = resource.resource_fence->GetGpuFenceHandle(); - } - const bool is_lost = can_delete == CanDeleteNowResult::kYesButLoseResource; to_return.emplace_back(child_id, resource.sync_token(), @@ -174,20 +167,12 @@ } resource.locked_for_external_use = true; - switch (resource.transferable.synchronization_type) { - case TransferableResource::SynchronizationType::kGpuCommandsCompleted: - resource.resource_fence = - resource_provider_->current_gpu_commands_completed_fence_; - break; - case TransferableResource::SynchronizationType::kReleaseFence: - resource.resource_fence = resource_provider_->current_release_fence_; - break; - default: - break; + if (resource.transferable.synchronization_type == + TransferableResource::SynchronizationType::kGpuCommandsCompleted) { + if (resource_provider_->current_read_lock_fence_.get()) + resource_provider_->current_read_lock_fence_->Set(); + resource.read_lock_fence = resource_provider_->current_read_lock_fence_; } - - if (resource.resource_fence) - resource.resource_fence->Set(); } DCHECK(base::Contains(resources_, std::make_pair(id, &resource)));
diff --git a/components/viz/service/display/display_resource_provider_skia_unittest.cc b/components/viz/service/display/display_resource_provider_skia_unittest.cc index 18f208a..6a1486cd 100644 --- a/components/viz/service/display/display_resource_provider_skia_unittest.cc +++ b/components/viz/service/display/display_resource_provider_skia_unittest.cc
@@ -17,12 +17,10 @@ #include "base/callback_helpers.h" #include "base/check.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_refptr.h" #include "build/build_config.h" #include "components/viz/client/client_resource_provider.h" #include "components/viz/common/resources/release_callback.h" #include "components/viz/common/resources/returned_resource.h" -#include "components/viz/common/resources/transferable_resource.h" #include "components/viz/test/test_context_provider.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -31,7 +29,6 @@ #include "third_party/khronos/GLES2/gl2ext.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/gpu_fence_handle.h" using testing::_; using testing::ByMove; @@ -299,218 +296,138 @@ child_resource_provider_->RemoveImportedResource(id1); } -class TestGpuCommandsCompletedFence : public ResourceFence { +class TestFence : public ResourceFence { public: - TestGpuCommandsCompletedFence() = default; + TestFence() = default; // ResourceFence implementation. void Set() override {} bool HasPassed() override { return passed; } - gfx::GpuFenceHandle GetGpuFenceHandle() override { - NOTREACHED(); - return gfx::GpuFenceHandle(); - } bool passed = false; private: - ~TestGpuCommandsCompletedFence() override = default; -}; - -class TestReleaseFence : public ResourceFence { - public: - TestReleaseFence() = default; - - // ResourceFence implementation. - void Set() override {} - bool HasPassed() override { return release_fence_.has_value(); } - gfx::GpuFenceHandle GetGpuFenceHandle() override { - return HasPassed() ? release_fence_->Clone() : gfx::GpuFenceHandle(); - } - - void SetReleaseFence(gfx::GpuFenceHandle release_fence) { - release_fence_ = std::move(release_fence); - } - - private: - ~TestReleaseFence() override = default; - - absl::optional<gfx::GpuFenceHandle> release_fence_; + ~TestFence() override = default; }; TEST_F(DisplayResourceProviderSkiaTest, - ResourceFenceStopsReturnToChildOrDelete) { - const std::vector<TransferableResource::SynchronizationType> - kSynchronizationTypes = { - TransferableResource::SynchronizationType::kGpuCommandsCompleted, - TransferableResource::SynchronizationType::kReleaseFence}; - for (auto sync_type : kSynchronizationTypes) { - MockReleaseCallback release; - TransferableResource tran1 = CreateResource(RGBA_8888); - tran1.synchronization_type = sync_type; - ResourceId id1 = child_resource_provider_->ImportResource( - tran1, base::BindOnce(&MockReleaseCallback::Released, - base::Unretained(&release))); + ReadLockFenceStopsReturnToChildOrDelete) { + MockReleaseCallback release; + TransferableResource tran1 = CreateResource(RGBA_8888); + tran1.synchronization_type = + TransferableResource::SynchronizationType::kGpuCommandsCompleted; + ResourceId id1 = child_resource_provider_->ImportResource( + tran1, base::BindOnce(&MockReleaseCallback::Released, + base::Unretained(&release))); - std::vector<ReturnedResource> returned_to_child; - int child_id = resource_provider_->CreateChild( - GetReturnCallback(&returned_to_child), SurfaceId()); + std::vector<ReturnedResource> returned_to_child; + int child_id = resource_provider_->CreateChild( + GetReturnCallback(&returned_to_child), SurfaceId()); - // Transfer some resources to the parent. - std::vector<TransferableResource> list; - child_resource_provider_->PrepareSendToParent( - {id1}, &list, - static_cast<RasterContextProvider*>(child_context_provider_.get())); - ASSERT_EQ(1u, list.size()); - EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id1)); - EXPECT_EQ(list[0].synchronization_type, sync_type); + // Transfer some resources to the parent. + std::vector<TransferableResource> list; + child_resource_provider_->PrepareSendToParent( + {id1}, &list, + static_cast<RasterContextProvider*>(child_context_provider_.get())); + ASSERT_EQ(1u, list.size()); + EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id1)); + EXPECT_EQ(list[0].synchronization_type, + TransferableResource::SynchronizationType::kGpuCommandsCompleted); - resource_provider_->ReceiveFromChild(child_id, list); + resource_provider_->ReceiveFromChild(child_id, list); - // In DisplayResourceProvider's namespace, use the mapped resource id. - std::unordered_map<ResourceId, ResourceId, ResourceIdHasher> resource_map = - resource_provider_->GetChildToParentMap(child_id); + // In DisplayResourceProvider's namespace, use the mapped resource id. + std::unordered_map<ResourceId, ResourceId, ResourceIdHasher> resource_map = + resource_provider_->GetChildToParentMap(child_id); - scoped_refptr<ResourceFence> fence; - TestGpuCommandsCompletedFence* gpu_commands_completed_fence = nullptr; - TestReleaseFence* release_fence = nullptr; - if (sync_type == - TransferableResource::SynchronizationType::kGpuCommandsCompleted) { - fence = base::MakeRefCounted<TestGpuCommandsCompletedFence>(); - gpu_commands_completed_fence = - static_cast<TestGpuCommandsCompletedFence*>(fence.get()); - resource_provider_->SetGpuCommandsCompletedFence(fence.get()); - } else { - ASSERT_EQ(TransferableResource::SynchronizationType::kReleaseFence, - sync_type); - fence = base::MakeRefCounted<TestReleaseFence>(); - release_fence = static_cast<TestReleaseFence*>(fence.get()); - resource_provider_->SetReleaseFence(fence.get()); - } - - { - ResourceId parent_id = resource_map[list.front().id]; - lock_set_->LockResource(parent_id, /*maybe_concurrent_reads=*/true, - /*is_video_plane=*/false); - lock_set_->UnlockResources(GenSyncToken()); - } - - resource_provider_->DeclareUsedResourcesFromChild(child_id, - ResourceIdSet()); - EXPECT_EQ(0u, returned_to_child.size()); - - resource_provider_->DeclareUsedResourcesFromChild(child_id, - ResourceIdSet()); - EXPECT_EQ(0u, returned_to_child.size()); - - if (gpu_commands_completed_fence) { - gpu_commands_completed_fence->passed = true; - } else { - gfx::GpuFenceHandle fake_handle; - // Making a fake fence fd doesn't work on android. The test just crashes. -#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) - fake_handle.owned_fd.reset({1}); -#endif - release_fence->SetReleaseFence(std::move(fake_handle)); - } - - resource_provider_->DeclareUsedResourcesFromChild(child_id, - ResourceIdSet()); - EXPECT_EQ(1u, returned_to_child.size()); - -#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) - if (release_fence) - EXPECT_FALSE(returned_to_child.begin()->release_fence.is_null()); - else - EXPECT_TRUE(returned_to_child.begin()->release_fence.is_null()); -#endif - - child_resource_provider_->ReceiveReturnsFromParent( - std::move(returned_to_child)); - EXPECT_CALL(release, Released(_, _)); - child_resource_provider_->RemoveImportedResource(id1); + scoped_refptr<TestFence> fence(new TestFence); + resource_provider_->SetReadLockFence(fence.get()); + { + ResourceId parent_id = resource_map[list.front().id]; + lock_set_->LockResource(parent_id, /*maybe_concurrent_reads=*/true, + /*is_video_plane=*/false); + lock_set_->UnlockResources(GenSyncToken()); } + resource_provider_->DeclareUsedResourcesFromChild(child_id, ResourceIdSet()); + EXPECT_EQ(0u, returned_to_child.size()); + + resource_provider_->DeclareUsedResourcesFromChild(child_id, ResourceIdSet()); + EXPECT_EQ(0u, returned_to_child.size()); + fence->passed = true; + + resource_provider_->DeclareUsedResourcesFromChild(child_id, ResourceIdSet()); + EXPECT_EQ(1u, returned_to_child.size()); + + child_resource_provider_->ReceiveReturnsFromParent( + std::move(returned_to_child)); + EXPECT_CALL(release, Released(_, _)); + child_resource_provider_->RemoveImportedResource(id1); } -TEST_F(DisplayResourceProviderSkiaTest, ResourceFenceDestroyChild) { - const std::vector<TransferableResource::SynchronizationType> - kSynchronizationTypes = { - TransferableResource::SynchronizationType::kGpuCommandsCompleted, - TransferableResource::SynchronizationType::kReleaseFence}; - for (auto sync_type : kSynchronizationTypes) { - MockReleaseCallback release; +TEST_F(DisplayResourceProviderSkiaTest, ReadLockFenceDestroyChild) { + MockReleaseCallback release; - TransferableResource tran1 = CreateResource(RGBA_8888); - tran1.synchronization_type = sync_type; - ResourceId id1 = child_resource_provider_->ImportResource( - tran1, base::BindOnce(&MockReleaseCallback::Released, - base::Unretained(&release))); + TransferableResource tran1 = CreateResource(RGBA_8888); + tran1.synchronization_type = + TransferableResource::SynchronizationType::kGpuCommandsCompleted; + ResourceId id1 = child_resource_provider_->ImportResource( + tran1, base::BindOnce(&MockReleaseCallback::Released, + base::Unretained(&release))); - TransferableResource tran2 = CreateResource(RGBA_8888); - ASSERT_EQ(tran2.synchronization_type, - TransferableResource::SynchronizationType::kSyncToken); - ResourceId id2 = child_resource_provider_->ImportResource( - tran2, base::BindOnce(&MockReleaseCallback::Released, - base::Unretained(&release))); + TransferableResource tran2 = CreateResource(RGBA_8888); + ASSERT_EQ(tran2.synchronization_type, + TransferableResource::SynchronizationType::kSyncToken); + ResourceId id2 = child_resource_provider_->ImportResource( + tran2, base::BindOnce(&MockReleaseCallback::Released, + base::Unretained(&release))); - std::vector<ReturnedResource> returned_to_child; - int child_id = resource_provider_->CreateChild( - GetReturnCallback(&returned_to_child), SurfaceId()); + std::vector<ReturnedResource> returned_to_child; + int child_id = resource_provider_->CreateChild( + GetReturnCallback(&returned_to_child), SurfaceId()); - // Transfer resources to the parent. - std::vector<TransferableResource> list; - child_resource_provider_->PrepareSendToParent( - {id1, id2}, &list, - static_cast<RasterContextProvider*>(child_context_provider_.get())); - ASSERT_EQ(2u, list.size()); - EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id1)); - EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id2)); + // Transfer resources to the parent. + std::vector<TransferableResource> list; + child_resource_provider_->PrepareSendToParent( + {id1, id2}, &list, + static_cast<RasterContextProvider*>(child_context_provider_.get())); + ASSERT_EQ(2u, list.size()); + EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id1)); + EXPECT_TRUE(child_resource_provider_->InUseByConsumer(id2)); - resource_provider_->ReceiveFromChild(child_id, list); + resource_provider_->ReceiveFromChild(child_id, list); - // In DisplayResourceProvider's namespace, use the mapped resource id. - std::unordered_map<ResourceId, ResourceId, ResourceIdHasher> resource_map = - resource_provider_->GetChildToParentMap(child_id); + // In DisplayResourceProvider's namespace, use the mapped resource id. + std::unordered_map<ResourceId, ResourceId, ResourceIdHasher> resource_map = + resource_provider_->GetChildToParentMap(child_id); - scoped_refptr<ResourceFence> fence; - if (sync_type == - TransferableResource::SynchronizationType::kGpuCommandsCompleted) { - fence = base::MakeRefCounted<TestGpuCommandsCompletedFence>(); - resource_provider_->SetGpuCommandsCompletedFence(fence.get()); - } else { - ASSERT_EQ(TransferableResource::SynchronizationType::kReleaseFence, - sync_type); - fence = base::MakeRefCounted<TestReleaseFence>(); - resource_provider_->SetReleaseFence(fence.get()); + scoped_refptr<TestFence> fence(new TestFence); + resource_provider_->SetReadLockFence(fence.get()); + { + for (auto& resource : list) { + ResourceId parent_id = resource_map[resource.id]; + lock_set_->LockResource(parent_id, /*maybe_concurrent_reads=*/true, + /*is_video_plane=*/false); } - - { - for (auto& resource : list) { - ResourceId parent_id = resource_map[resource.id]; - lock_set_->LockResource(parent_id, /*maybe_concurrent_reads=*/true, - /*is_video_plane=*/false); - } - lock_set_->UnlockResources(GenSyncToken()); - } - EXPECT_EQ(0u, returned_to_child.size()); - - EXPECT_EQ(2u, resource_provider_->num_resources()); - - resource_provider_->DestroyChild(child_id); - - EXPECT_EQ(0u, resource_provider_->num_resources()); - EXPECT_EQ(2u, returned_to_child.size()); - - // id1 should be lost and id2 should not. - EXPECT_EQ(returned_to_child[0].lost, returned_to_child[0].id == id1); - EXPECT_EQ(returned_to_child[1].lost, returned_to_child[1].id == id1); - - child_resource_provider_->ReceiveReturnsFromParent( - std::move(returned_to_child)); - EXPECT_CALL(release, Released(_, _)).Times(2); - child_resource_provider_->RemoveImportedResource(id1); - child_resource_provider_->RemoveImportedResource(id2); + lock_set_->UnlockResources(GenSyncToken()); } + EXPECT_EQ(0u, returned_to_child.size()); + + EXPECT_EQ(2u, resource_provider_->num_resources()); + + resource_provider_->DestroyChild(child_id); + + EXPECT_EQ(0u, resource_provider_->num_resources()); + EXPECT_EQ(2u, returned_to_child.size()); + + // id1 should be lost and id2 should not. + EXPECT_EQ(returned_to_child[0].lost, returned_to_child[0].id == id1); + EXPECT_EQ(returned_to_child[1].lost, returned_to_child[1].id == id1); + + child_resource_provider_->ReceiveReturnsFromParent( + std::move(returned_to_child)); + EXPECT_CALL(release, Released(_, _)).Times(2); + child_resource_provider_->RemoveImportedResource(id1); + child_resource_provider_->RemoveImportedResource(id2); } // Test that ScopedBatchReturnResources batching works.
diff --git a/components/viz/service/display/resource_fence.h b/components/viz/service/display/resource_fence.h index 59e1101..dc4153e 100644 --- a/components/viz/service/display/resource_fence.h +++ b/components/viz/service/display/resource_fence.h
@@ -7,8 +7,6 @@ #include "base/memory/ref_counted.h" -#include "ui/gfx/gpu_fence_handle.h" - namespace viz { // An abstract interface used to ensure reading from resources passed between @@ -18,16 +16,8 @@ ResourceFence(const ResourceFence&) = delete; ResourceFence& operator=(const ResourceFence&) = delete; - // Notifies the fence is needed. virtual void Set() = 0; - // Tells if the fence is ready. virtual bool HasPassed() = 0; - // A release fence which availability depends on the type of resource fence - // (managed by DisplayResourceProvider and - // TransferableResource::synchronization_type). The client must ensure that - // HasPassed is true before trying to access the release fence handle. - // Otherwise, it's not guaranteed that the fence handle is valid. - virtual gfx::GpuFenceHandle GetGpuFenceHandle() = 0; protected: friend class base::RefCountedThreadSafe<ResourceFence>;
diff --git a/components/viz/service/display/skia_output_surface.h b/components/viz/service/display/skia_output_surface.h index a6557e3..2378966 100644 --- a/components/viz/service/display/skia_output_surface.h +++ b/components/viz/service/display/skia_output_surface.h
@@ -17,7 +17,6 @@ #include "components/viz/service/display/overlay_processor_interface.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkYUVAInfo.h" -#include "ui/gfx/gpu_fence_handle.h" #if BUILDFLAG(IS_WIN) #include "components/viz/service/display/dc_layer_overlay.h" @@ -130,13 +129,8 @@ // play the DDL back on GPU thread on a cached SkSurface. // Optionally the caller may specify |on_finished| callback to be called after // the GPU has finished processing all submitted commands. The callback may be - // called on a different thread. The caller may also specify - // |return_release_fence_cb| callback to be called after all commands are - // submitted. The callback will return the release fence which will be - // signaled once the submitted commands are processed. - virtual void EndPaint(base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> - return_release_fence_cb) = 0; + // called on a different thread. + virtual void EndPaint(base::OnceClosure on_finished) = 0; // Make a promise SkImage from a render pass id. The render pass has been // painted with BeginPaintRenderPass and FinishPaintRenderPass. The format
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index b3f8d00..fbd06e7 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -701,30 +701,22 @@ sk_sp<SkImage> sk_image_; }; -// A read lock based fence that is signaled after gpu commands are completed -// meaning the resource has been read. -class SkiaRenderer::FrameResourceGpuCommandsCompletedFence - : public ResourceFence { +class SkiaRenderer::FrameResourceFence : public ResourceFence { public: - FrameResourceGpuCommandsCompletedFence() = default; - FrameResourceGpuCommandsCompletedFence( - const FrameResourceGpuCommandsCompletedFence&) = delete; - FrameResourceGpuCommandsCompletedFence& operator=( - const FrameResourceGpuCommandsCompletedFence&) = delete; + FrameResourceFence() = default; + + FrameResourceFence(const FrameResourceFence&) = delete; + FrameResourceFence& operator=(const FrameResourceFence&) = delete; // ResourceFence implementation. void Set() override { set_ = true; } bool HasPassed() override { return event_.IsSignaled(); } - gfx::GpuFenceHandle GetGpuFenceHandle() override { - NOTREACHED(); - return gfx::GpuFenceHandle(); - } bool WasSet() { return set_; } void Signal() { event_.Signal(); } private: - ~FrameResourceGpuCommandsCompletedFence() override = default; + ~FrameResourceFence() override = default; // Accessed only from compositor thread. bool set_ = false; @@ -732,41 +724,6 @@ base::WaitableEvent event_; }; -// FrameResourceFence that gets a ReleaseFence which is later set to returned -// resources. -class SkiaRenderer::FrameResourceReleaseFence : public ResourceFence { - public: - FrameResourceReleaseFence() = default; - FrameResourceReleaseFence(const FrameResourceReleaseFence&) = delete; - FrameResourceReleaseFence& operator=(const FrameResourceReleaseFence&) = - delete; - - // ResourceFence implementation: - void Set() override { set_ = true; } - // If the fence handle has been set, |this| has passed aka the callback has - // been called. - bool HasPassed() override { return release_fence_.has_value(); } - gfx::GpuFenceHandle GetGpuFenceHandle() override { - return HasPassed() ? release_fence_.value().Clone() : gfx::GpuFenceHandle(); - } - - bool WasSet() { return set_; } - void SetReleaseFenceCallback(gfx::GpuFenceHandle release_fence) { - release_fence_ = std::move(release_fence); - } - - private: - ~FrameResourceReleaseFence() override = default; - - // Accessed only from compositor thread. - bool set_ = false; - - // This is made optional so that the value is set after - // SetReleaseFenceCallback is called. Otherwise, there is no way to know if - // the fence has been set and a null handle is a "valid" handle. - absl::optional<gfx::GpuFenceHandle> release_fence_; -}; - SkiaRenderer::SkiaRenderer(const RendererSettings* settings, const DebugRendererSettings* debug_settings, OutputSurface* output_surface, @@ -783,17 +740,9 @@ DCHECK(skia_output_surface_); lock_set_for_external_use_.emplace(resource_provider, skia_output_surface_); - // There can be different synchronization types requested for different - // resources. Some of them may require SyncToken, others - ReadLockFence, and - // others may need ReleaseFence. SyncTokens are set when the output surface - // is flushed and external resources are released. However, other resources - // require additional setup, which helps to handle that. - current_gpu_commands_completed_fence_ = - base::MakeRefCounted<FrameResourceGpuCommandsCompletedFence>(); - current_release_fence_ = base::MakeRefCounted<FrameResourceReleaseFence>(); - this->resource_provider()->SetGpuCommandsCompletedFence( - current_gpu_commands_completed_fence_.get()); - this->resource_provider()->SetReleaseFence(current_release_fence_.get()); + current_frame_resource_fence_ = base::MakeRefCounted<FrameResourceFence>(); + this->resource_provider()->SetReadLockFence( + current_frame_resource_fence_.get()); #if OS_ANDROID use_real_color_space_for_stream_video_ = @@ -810,8 +759,7 @@ void SkiaRenderer::BeginDrawingFrame() { TRACE_EVENT0("viz", "SkiaRenderer::BeginDrawingFrame"); - DCHECK(!current_gpu_commands_completed_fence_->WasSet()); - DCHECK(!current_release_fence_->WasSet()); + DCHECK(!current_frame_resource_fence_->WasSet()); } void SkiaRenderer::FinishDrawingFrame() { @@ -2467,8 +2415,7 @@ } void SkiaRenderer::ScheduleOverlays() { - DCHECK(!current_gpu_commands_completed_fence_->WasSet()); - DCHECK(!current_release_fence_->WasSet()); + DCHECK(!current_frame_resource_fence_->WasSet()); // Always add an empty set of locks to be used in either SwapBuffersSkipped() // or SwapBuffersComplete(). @@ -2580,8 +2527,7 @@ NOTREACHED(); #endif // BUILDFLAG(IS_ANDROID) - DCHECK(!current_gpu_commands_completed_fence_->WasSet()); - DCHECK(!current_release_fence_->WasSet()); + DCHECK(!current_frame_resource_fence_->WasSet()); skia_output_surface_->ScheduleOverlays( std::move(current_frame()->overlay_list), std::move(sync_tokens)); @@ -2926,7 +2872,16 @@ if (is_root_render_pass && UsingSkiaForDelegatedInk()) DrawDelegatedInkTrail(); - EndPaint(/*failed=*/false); + base::OnceClosure on_finished_callback; + // Signal |current_frame_resource_fence_| when the root render pass is + // finished. + if (current_frame_resource_fence_->WasSet()) { + on_finished_callback = base::BindOnce( + &FrameResourceFence::Signal, std::move(current_frame_resource_fence_)); + current_frame_resource_fence_ = base::MakeRefCounted<FrameResourceFence>(); + resource_provider()->SetReadLockFence(current_frame_resource_fence_.get()); + } + skia_output_surface_->EndPaint(std::move(on_finished_callback)); // Defer flushing drawing task for root render pass, to avoid extra // MakeCurrent() call. It is expensive on GL. @@ -3234,7 +3189,7 @@ if (!content_image) { DLOG(ERROR) << "MakePromiseSkImageFromRenderPass() in " "PrepareRenderPassOverlay() failed."; - EndPaint(/*failed=*/true); + skia_output_surface_->EndPaint(base::NullCallback()); return; } @@ -3254,7 +3209,14 @@ current_canvas_ = nullptr; - EndPaint(/*failed=*/false); + base::OnceClosure on_finished_callback; + if (current_frame_resource_fence_->WasSet()) { + on_finished_callback = base::BindOnce( + &FrameResourceFence::Signal, std::move(current_frame_resource_fence_)); + current_frame_resource_fence_ = base::MakeRefCounted<FrameResourceFence>(); + resource_provider()->SetReadLockFence(current_frame_resource_fence_.get()); + } + skia_output_surface_->EndPaint(std::move(on_finished_callback)); // Adjust |bounds_rect| to contain the whole buffer and at the right location. overlay->bounds_rect.set_origin(gfx::PointF(filter_bounds.origin())); @@ -3262,39 +3224,6 @@ } #endif // BUILDFLAG(IS_APPLE) || defined(USE_OZONE) -void SkiaRenderer::EndPaint(bool failed) { - base::OnceClosure on_finished_callback; - base::OnceCallback<void(gfx::GpuFenceHandle)> on_return_release_fence_cb; - // If SkiaRenderer has not failed, prepare callbacks and pass them to - // SkiaOutputSurface. - if (!failed) { - // Signal |current_frame_resource_fence_| when the root render pass is - // finished. - if (current_gpu_commands_completed_fence_->WasSet()) { - on_finished_callback = - base::BindOnce(&FrameResourceGpuCommandsCompletedFence::Signal, - std::move(current_gpu_commands_completed_fence_)); - current_gpu_commands_completed_fence_ = - base::MakeRefCounted<FrameResourceGpuCommandsCompletedFence>(); - resource_provider()->SetGpuCommandsCompletedFence( - current_gpu_commands_completed_fence_.get()); - } - - // Return a release fence to the |current_release_fence_| - // when the root render pass is finished. - if (current_release_fence_->WasSet()) { - on_return_release_fence_cb = - base::BindOnce(&FrameResourceReleaseFence::SetReleaseFenceCallback, - std::move(current_release_fence_)); - current_release_fence_ = - base::MakeRefCounted<FrameResourceReleaseFence>(); - resource_provider()->SetReleaseFence(current_release_fence_.get()); - } - } - skia_output_surface_->EndPaint(std::move(on_finished_callback), - std::move(on_return_release_fence_cb)); -} - bool SkiaRenderer::IsRenderPassResourceAllocated( const AggregatedRenderPassId& render_pass_id) const { auto it = render_pass_backings_.find(render_pass_id);
diff --git a/components/viz/service/display/skia_renderer.h b/components/viz/service/display/skia_renderer.h index 7922aee..c7bceb8 100644 --- a/components/viz/service/display/skia_renderer.h +++ b/components/viz/service/display/skia_renderer.h
@@ -264,11 +264,6 @@ OverlayProcessorInterface::PlatformOverlayCandidate* overlay); #endif - // Sets up callbacks for frame resource fences and passes them to - // SkiaOutputSurface by calling EndPaint on that. If |failed|, - // SkiaOutputSurface::EndPaint will be called with null callbacks. - void EndPaint(bool failed); - DisplayResourceProviderSkia* resource_provider() { return static_cast<DisplayResourceProviderSkia*>(resource_provider_); } @@ -293,12 +288,8 @@ raw_ptr<SkCanvas> root_canvas_ = nullptr; raw_ptr<SkCanvas> current_canvas_ = nullptr; raw_ptr<SkSurface> current_surface_ = nullptr; - - class FrameResourceGpuCommandsCompletedFence; - scoped_refptr<FrameResourceGpuCommandsCompletedFence> - current_gpu_commands_completed_fence_; - class FrameResourceReleaseFence; - scoped_refptr<FrameResourceReleaseFence> current_release_fence_; + class FrameResourceFence; + scoped_refptr<FrameResourceFence> current_frame_resource_fence_; bool disable_picture_quad_image_filtering_ = false; bool is_scissor_enabled_ = false;
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 74fd2601..33311cb 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -624,9 +624,7 @@ return current_paint_->recorder()->getCanvas(); } -void SkiaOutputSurfaceImpl::EndPaint( - base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb) { +void SkiaOutputSurfaceImpl::EndPaint(base::OnceClosure on_finished) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(current_paint_); auto ddl = current_paint_->recorder()->detach(); @@ -651,8 +649,7 @@ &SkiaOutputSurfaceImplOnGpu::FinishPaintCurrentFrame, base::Unretained(impl_on_gpu_.get()), std::move(ddl), std::move(overdraw_ddl), std::move(images_in_current_paint_), - resource_sync_tokens_, std::move(on_finished), - std::move(return_release_fence_cb), draw_rectangle_); + resource_sync_tokens_, std::move(on_finished), draw_rectangle_); EnqueueGpuTask(std::move(task), std::move(resource_sync_tokens_), /*make_current=*/true, /*need_framebuffer=*/true); draw_rectangle_.reset(); @@ -661,8 +658,7 @@ &SkiaOutputSurfaceImplOnGpu::FinishPaintRenderPass, base::Unretained(impl_on_gpu_.get()), current_paint_->mailbox(), std::move(ddl), std::move(images_in_current_paint_), - resource_sync_tokens_, std::move(on_finished), - std::move(return_release_fence_cb)); + resource_sync_tokens_, std::move(on_finished)); EnqueueGpuTask(std::move(task), std::move(resource_sync_tokens_), /*make_current=*/true, /*need_framebuffer=*/false); }
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 685a700..e0dc4826 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -117,9 +117,7 @@ sk_sp<SkColorSpace> color_space, bool is_overlay, const gpu::Mailbox& mailbox) override; - void EndPaint(base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> - return_release_fence_cb) override; + void EndPaint(base::OnceClosure on_finished) override; void MakePromiseSkImage(ImageContext* image_context) override; sk_sp<SkImage> MakePromiseSkImageFromRenderPass( const AggregatedRenderPassId& id,
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index 71b1628d2..713a175 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -12,7 +12,6 @@ #include "base/callback_helpers.h" #include "base/debug/crash_logging.h" #include "base/memory/raw_ptr.h" -#include "base/notreached.h" #include "base/task/bind_post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/memory_dump_manager.h" @@ -39,7 +38,6 @@ #include "components/viz/service/display_embedder/skia_output_surface_dependency.h" #include "components/viz/service/display_embedder/skia_render_copy_results.h" #include "gpu/command_buffer/common/swap_buffers_complete_params.h" -#include "gpu/command_buffer/service/external_semaphore.h" #include "gpu/command_buffer/service/gr_shader_cache.h" #include "gpu/command_buffer/service/memory_tracking.h" #include "gpu/command_buffer/service/scheduler.h" @@ -70,14 +68,10 @@ #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/gpu_fence_handle.h" -#include "ui/gl/gl_fence.h" #include "ui/gl/gl_surface.h" #if BUILDFLAG(ENABLE_VULKAN) #include "components/viz/service/display_embedder/skia_output_device_vulkan.h" -#include "gpu/vulkan/vulkan_device_queue.h" -#include "gpu/vulkan/vulkan_function_pointers.h" -#include "gpu/vulkan/vulkan_implementation.h" #include "gpu/vulkan/vulkan_util.h" #if BUILDFLAG(IS_ANDROID) #include "components/viz/service/display_embedder/skia_output_device_vulkan_secondary_cb.h" @@ -404,7 +398,6 @@ std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb, absl::optional<gfx::Rect> draw_rectangle) { TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::FinishPaintCurrentFrame"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); @@ -487,24 +480,7 @@ end_semaphores.insert(end_semaphores.end(), end_paint_semaphores.begin(), end_paint_semaphores.end()); -#if BUILDFLAG(ENABLE_VULKAN) - // Semaphores for release fences for vulkan should be created before flush. - if (!return_release_fence_cb.is_null() && is_using_vulkan()) { - const bool result = CreateAndStoreExternalSemaphoreVulkan(end_semaphores); - // A release fence will be created on submit as some platforms may use - // VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT handle types for their - // external semaphore. That handle type has COPY transference. Vulkan spec - // says that semaphore has to be signaled, or have an associated semaphore - // signal operation pending execution. Thus, delay importing the handle - // and creating the fence until commands are submitted. - pending_release_fence_cbs_.emplace_back( - result ? end_semaphores.back() : GrBackendSemaphore(), - std::move(return_release_fence_cb)); - } -#endif - const bool end_semaphores_empty = end_semaphores.empty(); - auto result = scoped_output_device_paint_->Flush(vulkan_context_provider_, std::move(end_semaphores), std::move(on_finished)); @@ -515,22 +491,6 @@ FailedSkiaFlush("output_sk_surface()->flush() failed."); return; } - - gfx::GpuFenceHandle release_fence; - if (!return_release_fence_cb.is_null() && is_using_gl()) { - DCHECK(release_fence.is_null()); - release_fence = CreateReleaseFenceForGL(); - } - - if (!return_release_fence_cb.is_null() && is_using_dawn()) - NOTIMPLEMENTED() << "Release fences with dawn are not supported."; - - if (!return_release_fence_cb.is_null()) { - // Returning fences for Vulkan is delayed. See the comment above. - DCHECK(!is_using_vulkan()); - PostTaskToClientThread(base::BindOnce(std::move(return_release_fence_cb), - std::move(release_fence))); - } } } @@ -575,8 +535,7 @@ sk_sp<SkDeferredDisplayList> ddl, std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, - base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb) { + base::OnceClosure on_finished) { TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::FinishPaintRenderPass"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(ddl); @@ -627,22 +586,6 @@ backing_representation->SetCleared(); destroy_after_swap_.emplace_back(std::move(ddl)); -#if BUILDFLAG(ENABLE_VULKAN) - // Semaphores for release fences for vulkan should be created before flush. - if (!return_release_fence_cb.is_null() && is_using_vulkan()) { - const bool result = CreateAndStoreExternalSemaphoreVulkan(end_semaphores); - // A release fence will be created on submit as some platforms may use - // VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT handle types for their - // external semaphore. That handle type has COPY transference. Vulkan spec - // says that semaphore has to be signaled, or have an associated semaphore - // signal operation pending execution. Thus, delay importing the handle - // and creating the fence until commands are submitted. - pending_release_fence_cbs_.emplace_back( - result ? end_semaphores.back() : GrBackendSemaphore(), - std::move(return_release_fence_cb)); - } -#endif - GrFlushInfo flush_info = { .fNumSemaphores = end_semaphores.size(), .fSignalSemaphores = end_semaphores.data(), @@ -651,7 +594,6 @@ &flush_info); if (on_finished) gpu::AddCleanupTaskForSkiaFlush(std::move(on_finished), &flush_info); - auto result = surface->flush(flush_info); if (result != GrSemaphoresSubmitted::kYes && !(begin_semaphores.empty() && end_semaphores.empty())) { @@ -659,24 +601,6 @@ FailedSkiaFlush("offscreen.surface()->flush() failed."); return; } - - // If GL is used, create the release fence after flush. - gfx::GpuFenceHandle release_fence; - if (!return_release_fence_cb.is_null() && is_using_gl()) { - DCHECK(release_fence.is_null()); - release_fence = CreateReleaseFenceForGL(); - } - - if (!return_release_fence_cb.is_null() && is_using_dawn()) - NOTIMPLEMENTED() << "Release fences with dawn are not supported."; - - if (!return_release_fence_cb.is_null()) { - // Returning fences for Vulkan is delayed. See the comment above. - DCHECK(!is_using_vulkan()); - PostTaskToClientThread(base::BindOnce(std::move(return_release_fence_cb), - std::move(release_fence))); - } - bool sync_cpu = gpu::ShouldVulkanSyncCpuForSkiaSubmit(vulkan_context_provider_); if (sync_cpu) { @@ -1864,20 +1788,6 @@ promise_image_access_helper_.EndAccess(); scoped_output_device_paint_.reset(); -#if BUILDFLAG(ENABLE_VULKAN) - while (!pending_release_fence_cbs_.empty()) { - auto& item = pending_release_fence_cbs_.front(); - auto release_fence = CreateReleaseFenceForVulkan(item.first); - if (release_fence.is_null()) - LOG(ERROR) << "Unable to create a release fence for Vulkan."; - PostTaskToClientThread( - base::BindOnce(std::move(item.second), std::move(release_fence))); - pending_release_fence_cbs_.pop_front(); - } -#else - DCHECK(pending_release_fence_cbs_.empty()); -#endif - if (frame) { if (waiting_for_full_damage_) { // If we're using partial swap, we need to check whether the sub-buffer @@ -2099,56 +2009,4 @@ output_device_->DiscardBackbuffer(); } -#if BUILDFLAG(ENABLE_VULKAN) -gfx::GpuFenceHandle SkiaOutputSurfaceImplOnGpu::CreateReleaseFenceForVulkan( - const GrBackendSemaphore& semaphore) { - DCHECK(is_using_vulkan()); - - if (semaphore.vkSemaphore() == VK_NULL_HANDLE) - return {}; - - auto* implementation = vulkan_context_provider_->GetVulkanImplementation(); - VkDevice device = - vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice(); - - auto handle = - implementation->GetSemaphoreHandle(device, semaphore.vkSemaphore()); - if (!handle.is_valid()) { - vkDestroySemaphore(device, semaphore.vkSemaphore(), - /*pAllocator=*/nullptr); - LOG(ERROR) << "Failed to create a release fence for Vulkan."; - return {}; - } - return std::move(handle).ToGpuFenceHandle(); -} - -bool SkiaOutputSurfaceImplOnGpu::CreateAndStoreExternalSemaphoreVulkan( - std::vector<GrBackendSemaphore>& end_semaphores) { - DCHECK(is_using_vulkan()); - - auto* implementation = vulkan_context_provider_->GetVulkanImplementation(); - VkDevice device = - vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice(); - - VkSemaphore semaphore = implementation->CreateExternalSemaphore(device); - if (semaphore == VK_NULL_HANDLE) { - LOG(ERROR) - << "Creation of an external semaphore for a release fence failed."; - return false; - } - - end_semaphores.emplace_back(); - end_semaphores.back().initVulkan(semaphore); - return true; -} -#endif - -gfx::GpuFenceHandle SkiaOutputSurfaceImplOnGpu::CreateReleaseFenceForGL() { - if (gl::GLFence::IsGpuFenceSupported()) { - auto fence = gl::GLFence::CreateForGpuFence(); - return fence->GetGpuFence()->GetGpuFenceHandle().Clone(); - } - return {}; -} - } // namespace viz
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h index 47b069b..0be8048a 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
@@ -5,7 +5,6 @@ #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_ON_GPU_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_ON_GPU_H_ -#include <deque> #include <map> #include <memory> #include <utility> @@ -42,7 +41,6 @@ #include "third_party/skia/include/core/SkPromiseImageTexture.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSemaphore.h" -#include "ui/gfx/gpu_fence_handle.h" namespace gfx { namespace mojom { @@ -139,14 +137,12 @@ const gfx::ColorSpace& color_space, float device_scale_factor, gfx::OverlayTransform transform); - void FinishPaintCurrentFrame( - sk_sp<SkDeferredDisplayList> ddl, - sk_sp<SkDeferredDisplayList> overdraw_ddl, - std::vector<ImageContextImpl*> image_contexts, - std::vector<gpu::SyncToken> sync_tokens, - base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb, - absl::optional<gfx::Rect> draw_rectangle); + void FinishPaintCurrentFrame(sk_sp<SkDeferredDisplayList> ddl, + sk_sp<SkDeferredDisplayList> overdraw_ddl, + std::vector<ImageContextImpl*> image_contexts, + std::vector<gpu::SyncToken> sync_tokens, + base::OnceClosure on_finished, + absl::optional<gfx::Rect> draw_rectangle); void ScheduleOutputSurfaceAsOverlay( const OverlayProcessorInterface::OutputSurfaceOverlayPlane& output_surface_plane); @@ -161,13 +157,11 @@ void SwapBuffersSkipped(); void EnsureBackbuffer(); void DiscardBackbuffer(); - void FinishPaintRenderPass( - const gpu::Mailbox& mailbox, - sk_sp<SkDeferredDisplayList> ddl, - std::vector<ImageContextImpl*> image_contexts, - std::vector<gpu::SyncToken> sync_tokens, - base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb); + void FinishPaintRenderPass(const gpu::Mailbox& mailbox, + sk_sp<SkDeferredDisplayList> ddl, + std::vector<ImageContextImpl*> image_contexts, + std::vector<gpu::SyncToken> sync_tokens, + base::OnceClosure on_finished); // Deletes resources for RenderPasses in |ids|. Also takes ownership of // |images_contexts| and destroys them on GPU thread. void RemoveRenderPassResource( @@ -302,8 +296,6 @@ gpu_preferences_.gr_context_type == gpu::GrContextType::kDawn; } - bool is_using_gl() const { return !is_using_vulkan() && !is_using_dawn(); } - // Helper for `CopyOutput()` method, handles the RGBA format. void CopyOutputRGBA(SkSurface* surface, copy_output::RenderPassGeometry geometry, @@ -385,19 +377,6 @@ void ReleaseAsyncReadResultHelpers(); -#if BUILDFLAG(ENABLE_VULKAN) - // Creates a release fence. The semaphore is an external semaphore created - // by CreateAndStoreExternalSemaphoreVulkan(). May destroy VkSemaphore that - // the |semaphore| stores if creation of a release fence fails. In this case, - // invalid fence handle is returned. - gfx::GpuFenceHandle CreateReleaseFenceForVulkan( - const GrBackendSemaphore& semaphore); - // Returns true if succeess. - bool CreateAndStoreExternalSemaphoreVulkan( - std::vector<GrBackendSemaphore>& end_semaphores); -#endif - gfx::GpuFenceHandle CreateReleaseFenceForGL(); - class ReleaseCurrent { public: ReleaseCurrent(scoped_refptr<gl::GLSurface> gl_surface, @@ -500,13 +479,6 @@ // Tracking for ongoing AsyncReadResults. base::flat_set<AsyncReadResultHelper*> async_read_result_helpers_; - // Pending release fence callbacks. These callbacks can be delayed if Vulkan - // external semaphore type has copy transference, which means importing - // semaphores has to be delayed until submission. - std::deque<std::pair<GrBackendSemaphore, - base::OnceCallback<void(gfx::GpuFenceHandle)>>> - pending_release_fence_cbs_; - THREAD_CHECKER(thread_checker_); base::WeakPtr<SkiaOutputSurfaceImplOnGpu> weak_ptr_;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc b/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc index 8d69440..a44fbb46 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/bind.h" -#include "base/callback_forward.h" #include "base/callback_helpers.h" #include "base/run_loop.h" #include "cc/test/fake_output_surface_client.h" @@ -24,7 +23,6 @@ #include "gpu/command_buffer/service/service_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/gpu_fence_handle.h" #include "ui/gl/gl_implementation.h" namespace viz { @@ -47,10 +45,8 @@ void SetUpSkiaOutputSurfaceImpl(); // Paints and submits root RenderPass with a solid color rect of |size|. - gpu::SyncToken PaintRootRenderPass( - const gfx::Rect& output_rect, - base::OnceClosure closure, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence); + gpu::SyncToken PaintRootRenderPass(const gfx::Rect& output_rect, + base::OnceClosure closure); void CheckSyncTokenOnGpuThread(const gpu::SyncToken& sync_token); void CopyRequestCallbackOnGpuThread(const gfx::Rect& output_rect, @@ -91,15 +87,13 @@ gpu::SyncToken SkiaOutputSurfaceImplTest::PaintRootRenderPass( const gfx::Rect& rect, - base::OnceClosure closure, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence) { + base::OnceClosure closure) { SkPaint paint; paint.setColor(kOutputColor); SkCanvas* root_canvas = output_surface_->BeginPaintCurrentFrame(); root_canvas->drawRect( SkRect::MakeXYWH(rect.x(), rect.y(), rect.height(), rect.width()), paint); - output_surface_->EndPaint(std::move(closure), - std::move(return_release_fence)); + output_surface_->EndPaint(std::move(closure)); return output_surface_->Flush(); } @@ -148,14 +142,9 @@ bool on_finished_called = false; base::OnceClosure on_finished = base::BindOnce([](bool* result) { *result = true; }, &on_finished_called); - bool on_return_release_fence_called = false; - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb = - base::BindOnce( - [](bool* result, gfx::GpuFenceHandle handle) { *result = true; }, - &on_return_release_fence_called); - gpu::SyncToken sync_token = PaintRootRenderPass( - output_rect, std::move(on_finished), std::move(return_release_fence_cb)); + gpu::SyncToken sync_token = + PaintRootRenderPass(output_rect, std::move(on_finished)); EXPECT_TRUE(sync_token.HasData()); // Copy the output @@ -187,10 +176,6 @@ output_surface_->ScheduleGpuTaskForTesting(std::move(closure), {sync_token}); BlockMainThread(); EXPECT_TRUE(on_finished_called); - - // Let the cb to come back. - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(on_return_release_fence_called); } // Draws two frames and calls Reshape() between the two frames changing the @@ -204,8 +189,7 @@ // Draw something, it's not important what. base::RunLoop run_loop; - PaintRootRenderPass(kSurfaceRect, run_loop.QuitClosure(), - base::DoNothing()); + PaintRootRenderPass(kSurfaceRect, run_loop.QuitClosure()); OutputSurfaceFrame frame; frame.size = kSurfaceRect.size(); @@ -247,7 +231,7 @@ geometry.sampling_bounds = output_rect; geometry.readback_offset = gfx::Vector2d(0, 0); - PaintRootRenderPass(kSurfaceRect, base::DoNothing(), base::DoNothing()); + PaintRootRenderPass(kSurfaceRect, base::DoNothing()); output_surface_->CopyOutput(AggregatedRenderPassId{0}, geometry, color_space, std::move(request), gpu::Mailbox()); output_surface_->SwapBuffersSkipped(kSurfaceRect); @@ -288,7 +272,7 @@ geometry.sampling_bounds = output_rect; geometry.readback_offset = gfx::Vector2d(0, 0); - PaintRootRenderPass(kSurfaceRect, base::DoNothing(), base::DoNothing()); + PaintRootRenderPass(kSurfaceRect, base::DoNothing()); output_surface_->CopyOutput(AggregatedRenderPassId{0}, geometry, color_space, std::move(request), gpu::Mailbox()); output_surface_->SwapBuffersSkipped(kSurfaceRect);
diff --git a/components/viz/test/fake_skia_output_surface.cc b/components/viz/test/fake_skia_output_surface.cc index b20aa542..8c07fb66 100644 --- a/components/viz/test/fake_skia_output_surface.cc +++ b/components/viz/test/fake_skia_output_surface.cc
@@ -26,7 +26,6 @@ #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" -#include "ui/gfx/gpu_fence_handle.h" #include "ui/gfx/presentation_feedback.h" #include "ui/gfx/swap_result.h" #include "ui/gl/gl_utils.h" @@ -185,17 +184,13 @@ return sk_surface->getCanvas(); } -void FakeSkiaOutputSurface::EndPaint( - base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> return_release_fence_cb) { +void FakeSkiaOutputSurface::EndPaint(base::OnceClosure on_finished) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); sk_surfaces_[current_render_pass_id_]->flushAndSubmit(); current_render_pass_id_ = AggregatedRenderPassId{0}; if (on_finished) std::move(on_finished).Run(); - if (return_release_fence_cb) - std::move(return_release_fence_cb).Run(gfx::GpuFenceHandle()); } sk_sp<SkImage> FakeSkiaOutputSurface::MakePromiseSkImageFromRenderPass(
diff --git a/components/viz/test/fake_skia_output_surface.h b/components/viz/test/fake_skia_output_surface.h index 01b7f015..e9893a0 100644 --- a/components/viz/test/fake_skia_output_surface.h +++ b/components/viz/test/fake_skia_output_surface.h
@@ -72,9 +72,7 @@ sk_sp<SkColorSpace> color_space, bool is_overlay, const gpu::Mailbox& mailbox) override; - void EndPaint(base::OnceClosure on_finished, - base::OnceCallback<void(gfx::GpuFenceHandle)> - return_release_fence_cb) override; + void EndPaint(base::OnceClosure on_finished) override; void MakePromiseSkImage(ImageContext* image_context) override; sk_sp<SkImage> MakePromiseSkImageFromRenderPass( const AggregatedRenderPassId& id,
diff --git a/components/webapps/browser/android/add_to_homescreen_data_fetcher.cc b/components/webapps/browser/android/add_to_homescreen_data_fetcher.cc index e10a2957..b2dafd6 100644 --- a/components/webapps/browser/android/add_to_homescreen_data_fetcher.cc +++ b/components/webapps/browser/android/add_to_homescreen_data_fetcher.cc
@@ -133,8 +133,9 @@ // Send a message to the renderer to retrieve information about the page. mojo::AssociatedRemote<mojom::WebPageMetadataAgent> metadata_agent; - web_contents->GetMainFrame()->GetRemoteAssociatedInterfaces()->GetInterface( - &metadata_agent); + web_contents->GetPrimaryMainFrame() + ->GetRemoteAssociatedInterfaces() + ->GetInterface(&metadata_agent); // Bind the InterfacePtr into the callback so that it's kept alive until // there's either a connection error or a response. auto* web_page_metadata_proxy = metadata_agent.get();
diff --git a/components/webapps/browser/banners/app_banner_manager.cc b/components/webapps/browser/banners/app_banner_manager.cc index 9cff729..0b691eb 100644 --- a/components/webapps/browser/banners/app_banner_manager.cc +++ b/components/webapps/browser/banners/app_banner_manager.cc
@@ -181,7 +181,7 @@ void AppBannerManager::OnInstall(blink::mojom::DisplayMode display) { TrackInstallDisplayMode(display); mojo::Remote<blink::mojom::InstallationService> installation_service; - web_contents()->GetMainFrame()->GetRemoteInterfaces()->GetInterface( + web_contents()->GetPrimaryMainFrame()->GetRemoteInterfaces()->GetInterface( installation_service.BindNewPipeAndPassReceiver()); DCHECK(installation_service); installation_service->OnInstall(); @@ -613,7 +613,7 @@ ResetBindings(); mojo::Remote<blink::mojom::AppBannerController> controller; - web_contents()->GetMainFrame()->GetRemoteInterfaces()->GetInterface( + web_contents()->GetPrimaryMainFrame()->GetRemoteInterfaces()->GetInterface( controller.BindNewPipeAndPassReceiver()); // Get a raw controller pointer before we move out of the smart pointer to @@ -695,7 +695,7 @@ // instantiated after DidFinishLoad. Trigger the banner pipeline now (on // portal activation) if we missed the load event. if (!load_finished_ && !web_contents()->ShouldShowLoadingUI()) { - DidFinishLoad(web_contents()->GetMainFrame(), + DidFinishLoad(web_contents()->GetPrimaryMainFrame(), web_contents()->GetLastCommittedURL()); } } @@ -895,7 +895,7 @@ if (event_canceled) { TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_PREVENT_DEFAULT_CALLED); if (ShouldBypassEngagementChecks()) { - web_contents()->GetMainFrame()->AddMessageToConsole( + web_contents()->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kInfo, "Banner not shown: beforeinstallpromptevent.preventDefault() called. " "The page must call beforeinstallpromptevent.prompt() to show the "
diff --git a/components/webapps/browser/installable/installable_logging.cc b/components/webapps/browser/installable/installable_logging.cc index 31fccd2..168a5a7 100644 --- a/components/webapps/browser/installable/installable_logging.cc +++ b/components/webapps/browser/installable/installable_logging.cc
@@ -362,7 +362,7 @@ if (message.empty()) return; - web_contents->GetMainFrame()->AddMessageToConsole( + web_contents->GetPrimaryMainFrame()->AddMessageToConsole( level, GetMessagePrefix() + message); }
diff --git a/components/zoom/zoom_controller.cc b/components/zoom/zoom_controller.cc index a581483..68ba2fa8 100644 --- a/components/zoom/zoom_controller.cc +++ b/components/zoom/zoom_controller.cc
@@ -111,7 +111,7 @@ // Cannot zoom in disabled mode. Also, don't allow changing zoom level on // a crashed tab, an error page or an interstitial page. if (zoom_mode_ == ZOOM_MODE_DISABLED || - !web_contents()->GetMainFrame()->IsRenderFrameLive()) + !web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) return false; // Store client data so the |client| can be attributed when the zoom @@ -157,12 +157,14 @@ web_contents(), GetZoomLevel(), zoom_level, zoom_mode_, false /* can_show_bubble */); int process_id = web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetProcess() ->GetID(); - int view_id = - web_contents()->GetMainFrame()->GetRenderViewHost()->GetRoutingID(); + int view_id = web_contents() + ->GetPrimaryMainFrame() + ->GetRenderViewHost() + ->GetRoutingID(); if (zoom_mode_ == ZOOM_MODE_ISOLATED || zoom_map->UsesTemporaryZoomLevel(process_id, view_id)) { zoom_map->SetTemporaryZoomLevel(process_id, view_id, zoom_level); @@ -193,12 +195,14 @@ content::HostZoomMap::GetForWebContents(web_contents()); DCHECK(zoom_map); int process_id = web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetProcess() ->GetID(); - int view_id = - web_contents()->GetMainFrame()->GetRenderViewHost()->GetRoutingID(); + int view_id = web_contents() + ->GetPrimaryMainFrame() + ->GetRenderViewHost() + ->GetRoutingID(); double original_zoom_level = GetZoomLevel(); DCHECK(!event_data_); @@ -289,12 +293,14 @@ return; int process_id = web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetProcess() ->GetID(); - int view_id = - web_contents()->GetMainFrame()->GetRenderViewHost()->GetRoutingID(); + int view_id = web_contents() + ->GetPrimaryMainFrame() + ->GetRenderViewHost() + ->GetRoutingID(); content::HostZoomMap* zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); zoom_level_ = zoom_map->GetDefaultZoomLevel();
diff --git a/content/browser/accessibility/browser_accessibility_manager.cc b/content/browser/accessibility/browser_accessibility_manager.cc index fc6e570e..6ea0755 100644 --- a/content/browser/accessibility/browser_accessibility_manager.cc +++ b/content/browser/accessibility/browser_accessibility_manager.cc
@@ -474,9 +474,21 @@ DCHECK_LE(static_cast<int>(tree_update.nodes.size()), ax_tree()->size()); } - // If this page is hidden by an interstitial, suppress all events. + // If this page is hidden by an interstitial or frozen inside the + // back/forward cache, suppress all the events. If/when the page becomes + // visible, the correct set of accessibility events will be generated. + // + // Rationale for the back/forward cache behavior: + // https://docs.google.com/document/d/1_jaEAXurfcvriwcNU-5u0h8GGioh0LelagUIIGFfiuU/ BrowserAccessibilityManager* root_manager = GetRootManager(); - if (root_manager && root_manager->hidden_by_interstitial_page()) { + bool rfh_in_bfcache = false; + // |delegate_| can be nullptr in unittests. + if (delegate_) { + RenderFrameHostImpl* rfh = delegate_->AccessibilityRenderFrameHost(); + rfh_in_bfcache = rfh ? rfh->IsInBackForwardCache() : false; + } + if ((root_manager && root_manager->hidden_by_interstitial_page()) || + rfh_in_bfcache) { event_generator().ClearEvents(); return true; }
diff --git a/content/browser/aggregation_service/aggregatable_report.cc b/content/browser/aggregation_service/aggregatable_report.cc index 9201357..7f8c5b6 100644 --- a/content/browser/aggregation_service/aggregatable_report.cc +++ b/content/browser/aggregation_service/aggregatable_report.cc
@@ -282,12 +282,14 @@ base::GUID report_id, url::Origin reporting_origin, DebugMode debug_mode, - base::Value::Dict additional_fields) + base::Value::Dict additional_fields, + std::string api_version) : scheduled_report_time(scheduled_report_time), report_id(std::move(report_id)), reporting_origin(std::move(reporting_origin)), debug_mode(debug_mode), - additional_fields(std::move(additional_fields)) {} + additional_fields(std::move(additional_fields)), + api_version(std::move(api_version)) {} AggregatableReportSharedInfo::AggregatableReportSharedInfo( AggregatableReportSharedInfo&& other) = default; @@ -298,7 +300,7 @@ AggregatableReportSharedInfo AggregatableReportSharedInfo::Clone() const { return AggregatableReportSharedInfo(scheduled_report_time, report_id, reporting_origin, debug_mode, - additional_fields.Clone()); + additional_fields.Clone(), api_version); } std::string AggregatableReportSharedInfo::SerializeAsJson() const { @@ -316,8 +318,8 @@ value.Set("scheduled_report_time", base::NumberToString(scheduled_report_time.ToJavaTime() / base::Time::kMillisecondsPerSecond)); - // TODO(alexmt): Replace with a real version once a version string is decided. - value.Set("version", ""); + + value.Set("version", api_version); // Only include the field if enabled. if (debug_mode == DebugMode::kEnabled) {
diff --git a/content/browser/aggregation_service/aggregatable_report.h b/content/browser/aggregation_service/aggregatable_report.h index 43739db5..5b637b2 100644 --- a/content/browser/aggregation_service/aggregatable_report.h +++ b/content/browser/aggregation_service/aggregatable_report.h
@@ -88,7 +88,8 @@ base::GUID report_id, url::Origin reporting_origin, DebugMode debug_mode, - base::Value::Dict additional_fields); + base::Value::Dict additional_fields, + std::string api_version); AggregatableReportSharedInfo(const AggregatableReportSharedInfo& other) = delete; @@ -109,6 +110,7 @@ url::Origin reporting_origin; DebugMode debug_mode; base::Value::Dict additional_fields; + std::string api_version; }; // An AggregatableReport contains all the information needed for sending the
diff --git a/content/browser/aggregation_service/aggregatable_report_unittest.cc b/content/browser/aggregation_service/aggregatable_report_unittest.cc index 7969ff0e..f9b7535 100644 --- a/content/browser/aggregation_service/aggregatable_report_unittest.cc +++ b/content/browser/aggregation_service/aggregatable_report_unittest.cc
@@ -414,14 +414,15 @@ /*report_id=*/ base::GUID::ParseLowercase("21abd97f-73e8-4b88-9389-a9fee6abda5e"), url::Origin::Create(GURL("https://reporting.example")), - AggregatableReportSharedInfo::DebugMode::kDisabled, base::Value::Dict()); + AggregatableReportSharedInfo::DebugMode::kDisabled, base::Value::Dict(), + /*api_version=*/"1.0"); const char kExpectedString[] = R"({)" R"("report_id":"21abd97f-73e8-4b88-9389-a9fee6abda5e",)" R"("reporting_origin":"https://reporting.example",)" R"("scheduled_report_time":"1234567890",)" - R"("version":"")" + R"("version":"1.0")" R"(})"; EXPECT_EQ(shared_info.SerializeAsJson(), kExpectedString); @@ -434,7 +435,8 @@ /*report_id=*/ base::GUID::ParseLowercase("21abd97f-73e8-4b88-9389-a9fee6abda5e"), url::Origin::Create(GURL("https://reporting.example")), - AggregatableReportSharedInfo::DebugMode::kEnabled, base::Value::Dict()); + AggregatableReportSharedInfo::DebugMode::kEnabled, base::Value::Dict(), + /*api_version=*/"1.0"); const char kExpectedString[] = R"({)" @@ -442,7 +444,7 @@ R"("report_id":"21abd97f-73e8-4b88-9389-a9fee6abda5e",)" R"("reporting_origin":"https://reporting.example",)" R"("scheduled_report_time":"1234567890",)" - R"("version":"")" + R"("version":"1.0")" R"(})"; EXPECT_EQ(shared_info.SerializeAsJson(), kExpectedString); @@ -459,7 +461,8 @@ base::GUID::ParseLowercase("21abd97f-73e8-4b88-9389-a9fee6abda5e"), url::Origin::Create(GURL("https://reporting.example")), AggregatableReportSharedInfo::DebugMode::kEnabled, - std::move(additional_fields)); + std::move(additional_fields), + /*api_version=*/"1.0"); const char kExpectedString[] = R"({)" @@ -470,7 +473,7 @@ R"("report_id":"21abd97f-73e8-4b88-9389-a9fee6abda5e",)" R"("reporting_origin":"https://reporting.example",)" R"("scheduled_report_time":"1234567890",)" - R"("version":"")" + R"("version":"1.0")" R"(})"; EXPECT_EQ(shared_info.SerializeAsJson(), kExpectedString);
diff --git a/content/browser/aggregation_service/aggregation_service_test_utils.cc b/content/browser/aggregation_service/aggregation_service_test_utils.cc index b04f0060..2cb1cf7b 100644 --- a/content/browser/aggregation_service/aggregation_service_test_utils.cc +++ b/content/browser/aggregation_service/aggregation_service_test_utils.cc
@@ -201,7 +201,8 @@ base::GUID::GenerateRandomV4(), url::Origin::Create(GURL("https://reporting.example")), AggregatableReportSharedInfo::DebugMode::kDisabled, - /*additional_fields=*/base::Value::Dict())) + /*additional_fields=*/base::Value::Dict(), + /*api_version=*/"")) .value(); }
diff --git a/content/browser/attribution_reporting/aggregatable_attribution_utils.cc b/content/browser/attribution_reporting/aggregatable_attribution_utils.cc index e3f2382..a6191b07 100644 --- a/content/browser/attribution_reporting/aggregatable_attribution_utils.cc +++ b/content/browser/attribution_reporting/aggregatable_attribution_utils.cc
@@ -157,7 +157,8 @@ AggregatableReportSharedInfo( data->initial_report_time, report.external_report_id(), attribution_info.source.common_info().reporting_origin(), debug_mode, - std::move(additional_fields))); + std::move(additional_fields), + AttributionReport::AggregatableAttributionData::kVersion)); } } // namespace content
diff --git a/content/browser/attribution_reporting/attribution_aggregatable_report_golden_unittest.cc b/content/browser/attribution_reporting/attribution_aggregatable_report_golden_unittest.cc index 626d432..de876fe 100644 --- a/content/browser/attribution_reporting/attribution_aggregatable_report_golden_unittest.cc +++ b/content/browser/attribution_reporting/attribution_aggregatable_report_golden_unittest.cc
@@ -124,8 +124,10 @@ EXPECT_TRUE(VerifyReport( report.ReportBody(), std::move(expected_report.GetDict()), *base64_encoded_expected_cleartext_payload)) - << "There was an error, actual output for " << report_file - << " is:\n" + << "There was an error, consider bumping " + "AttributionReport::AggregatableAttributionData::kVersion," + " actual output for " + << report_file << " is:\n" << SerializeAttributionJson(report.ReportBody(), /*pretty_print=*/true); run_loop.Quit();
diff --git a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc index bf0493a..3c0ef1e 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc
@@ -106,7 +106,8 @@ /*reporting_origin=*/ url::Origin::Create(GURL("https://example.reporting")), AggregatableReportSharedInfo::DebugMode::kDisabled, - std::move(additional_fields)); + std::move(additional_fields), + /*api_version=*/""); return AggregatableReport(std::move(payloads), shared_info.SerializeAsJson()); }
diff --git a/content/browser/attribution_reporting/attribution_report.h b/content/browser/attribution_reporting/attribution_report.h index 3394994..5a2da1a 100644 --- a/content/browser/attribution_reporting/attribution_report.h +++ b/content/browser/attribution_reporting/attribution_report.h
@@ -90,6 +90,10 @@ // Returns the sum of the contributions (values) across all buckets. base::CheckedNumeric<int64_t> BudgetRequired() const; + // TODO(linnan): Replace with a real version once a version string is + // decided. + static constexpr char kVersion[] = ""; + // The historgram contributions. std::vector<AggregatableHistogramContribution> contributions;
diff --git a/content/browser/back_forward_cache_internal_browsertest.cc b/content/browser/back_forward_cache_internal_browsertest.cc index 83245d1..3ce20f1 100644 --- a/content/browser/back_forward_cache_internal_browsertest.cc +++ b/content/browser/back_forward_cache_internal_browsertest.cc
@@ -4,12 +4,14 @@ #include "content/browser/back_forward_cache_browsertest.h" +#include "base/bind.h" #include "base/command_line.h" #include "base/memory/raw_ptr.h" #include "base/metrics/metrics_hashes.h" #include "base/test/bind.h" #include "base/test/test_mock_time_task_runner.h" #include "build/build_config.h" +#include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/renderer_host/back_forward_cache_disable.h" #include "content/browser/renderer_host/navigation_request.h" #include "content/browser/web_contents/web_contents_impl.h" @@ -19,6 +21,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" +#include "content/public/test/accessibility_notification_waiter.h" #include "content/public/test/back_forward_cache_util.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" @@ -34,6 +37,7 @@ #include "media/base/media_switches.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "third_party/blink/public/common/features.h" +#include "ui/accessibility/ax_action_data.h" // This file contains back/forward-cache tests that test or use internal // features, e.g. cache-flushing, crashes, verifying proxies and other @@ -3473,6 +3477,79 @@ EXPECT_TRUE(ExecuteScript(rfh_a->child_at(0)->child_at(0), "true")); } +class AccessibilityBackForwardCacheBrowserTest + : public BackForwardCacheBrowserTest { + protected: + void SetUpCommandLine(base::CommandLine* command_line) override { + EnableFeatureAndSetParams(features::kEnableBackForwardCacheForScreenReader, + "", "true"); + BackForwardCacheBrowserTest::SetUpCommandLine(command_line); + } +}; + +IN_PROC_BROWSER_TEST_F(AccessibilityBackForwardCacheBrowserTest, + DoNotEvictOnAccessibilityEvents) { + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); + + // 1) Navigate to A. + EXPECT_TRUE(NavigateToURL(shell()->web_contents(), url_a)); + RenderFrameHostImplWrapper rfh_a(current_frame_host()); + // Enable accessibility for A. + EnableAccessibilityForWebContents(shell()->web_contents()); + + // 2) Navigate to B. + EXPECT_TRUE(NavigateToURL(shell()->web_contents(), url_b)); + RenderFrameHostImplWrapper rfh_b(current_frame_host()); + EXPECT_TRUE(rfh_a->IsInBackForwardCache()); + + // 3) Set the callback for generated events, and expect that this is never + // fired. + BrowserAccessibilityManager* manager = + rfh_a->GetOrCreateBrowserAccessibilityManager(); + manager->SetGeneratedEventCallbackForTesting(base::BindRepeating( + [](BrowserAccessibilityDelegate* delegate, + ui::AXEventGenerator::Event event, int event_target_id) { FAIL(); })); + // Generate an event. + mojom::AXUpdatesAndEventsPtr updates_and_events = + mojom::AXUpdatesAndEvents::New(); + ui::AXTreeUpdate update; + update.root_id = 1; + updates_and_events->updates.emplace_back(update); + updates_and_events->events.emplace_back( + ui::AXEvent(/*id=*/0, ax::mojom::Event::kChildrenChanged)); + // If any events are generated and fired, they will be fired synchronously + // in the same task of |HandleAXEventsForTests()| and and result in a test + // fail. + rfh_a->HandleAXEventsForTests(rfh_a->GetAXTreeID(), + std::move(updates_and_events), + /*reset_token=*/0); + + // Reset the callback before restoring the page so that we will not fail when + // events are generated. + manager->SetGeneratedEventCallbackForTesting( + GeneratedEventCallbackForTesting()); + + // 4) Navigate back and ensure that |rfh_a| is successfully restored from + // bfcache. + ASSERT_TRUE(HistoryGoBack(web_contents())); + EXPECT_EQ(current_frame_host(), rfh_a.get()); + ExpectRestored(FROM_HERE); + + // 5) Accessibility events are dispatched again. + AccessibilityNotificationWaiter waiter( + shell()->web_contents(), ui::kAXModeComplete, + ui::AXEventGenerator::Event::CHILDREN_CHANGED); + // Modify the DOM tree to dispatch new events to verify that the new events + // won't be dropped. + EXPECT_TRUE(ExecJs(rfh_a.get(), + "document.getElementsByTagName('body')[0].remove();")); + // Ensure the AX events are dispatched for |rfh_a|. + waiter.WaitForNotification(); + EXPECT_EQ(waiter.event_render_frame_host(), rfh_a.get()); +} + class BackgroundForegroundProcessLimitBackForwardCacheBrowserTest : public BackForwardCacheBrowserTest { protected:
diff --git a/content/browser/browser_main_loop_unittest.cc b/content/browser/browser_main_loop_unittest.cc index 96106c5..dda2e09 100644 --- a/content/browser/browser_main_loop_unittest.cc +++ b/content/browser/browser_main_loop_unittest.cc
@@ -71,7 +71,7 @@ EXPECT_GE(base::ThreadPoolInstance::Get() ->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( {base::TaskPriority::USER_VISIBLE}), - base::SysInfo::NumberOfProcessors() - 1); + static_cast<size_t>(base::SysInfo::NumberOfProcessors() - 1)); browser_main_loop.ShutdownThreadsAndCleanUp(); BrowserTaskExecutor::ResetForTesting(); }
diff --git a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc index 0e54a26..979d4c75 100644 --- a/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc +++ b/content/browser/first_party_sets/first_party_sets_handler_impl_unittest.cc
@@ -333,16 +333,12 @@ FILE_PATH_LITERAL("persisted_first_party_sets.json")); } - void SetPublicFirstPartySetsAndWait(base::StringPiece content) { - base::ScopedTempDir temp_dir; - CHECK(temp_dir.CreateUniqueTempDir()); + base::File WritePublicSetsFile(base::StringPiece content) { base::FilePath path = - temp_dir.GetPath().Append(FILE_PATH_LITERAL("sets_file.json")); + scoped_dir_.GetPath().Append(FILE_PATH_LITERAL("sets_file.json")); CHECK(base::WriteFile(path, content)); - FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( - base::File(path, base::File::FLAG_OPEN | base::File::FLAG_READ)); - env_.RunUntilIdle(); + return base::File(path, base::File::FLAG_OPEN | base::File::FLAG_READ); } void TearDown() override { @@ -407,7 +403,8 @@ const std::string input = R"({"owner": "https://foo.test", )" R"("members": ["https://member2.test"]})"; ASSERT_TRUE(base::JSONReader::Read(input)); - SetPublicFirstPartySetsAndWait(input); + FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( + WritePublicSetsFile(input)); auto expected_sets = UnorderedElementsAre( Pair(SerializesTo("https://example.test"), @@ -440,7 +437,8 @@ const std::string input = R"({"owner": "https://foo.test", )" R"("members": ["https://member2.test"]})"; ASSERT_TRUE(base::JSONReader::Read(input)); - SetPublicFirstPartySetsAndWait(input); + FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( + WritePublicSetsFile(input)); auto expected_sets = UnorderedElementsAre( Pair(SerializesTo("https://example.test"), @@ -474,7 +472,8 @@ const std::string input = R"({"owner": "https://example.test", )" R"("members": ["https://member.test"]})"; ASSERT_TRUE(base::JSONReader::Read(input)); - SetPublicFirstPartySetsAndWait(input); + FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( + WritePublicSetsFile(input)); auto expected_sets = UnorderedElementsAre(Pair(SerializesTo("https://example.test"), @@ -520,7 +519,8 @@ const std::string input = R"({"owner": "https://example.test", )" R"("members": ["https://member.test"]})"; ASSERT_TRUE(base::JSONReader::Read(input)); - SetPublicFirstPartySetsAndWait(input); + FirstPartySetsHandlerImpl::GetInstance()->SetPublicFirstPartySets( + WritePublicSetsFile(input)); EXPECT_THAT(future.Get(), UnorderedElementsAre(Pair(SerializesTo("https://example.test"),
diff --git a/content/browser/interest_group/ad_auction_service_impl.h b/content/browser/interest_group/ad_auction_service_impl.h index 4358a6a..ca92845 100644 --- a/content/browser/interest_group/ad_auction_service_impl.h +++ b/content/browser/interest_group/ad_auction_service_impl.h
@@ -70,7 +70,7 @@ scoped_refptr<network::WrapperSharedURLLoaderFactory> GetRefCountedTrustedURLLoaderFactory(); - // AuctionRunner::Delegate implementation: + // AuctionWorkletManager::Delegate implementation: network::mojom::URLLoaderFactory* GetFrameURLLoaderFactory() override; network::mojom::URLLoaderFactory* GetTrustedURLLoaderFactory() override; RenderFrameHostImpl* GetFrame() override;
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index cd8ed02..2bf604ee 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -1352,18 +1352,25 @@ } const std::string storage_domain; - // TODO(https://crbug.com/1264405): Determine if we should deprecate - // navigation in filesystem: URLs entirely or in 3p contexts; alter the - // below as necessary. NOTE: while the logic below is appropriate for - // browser-initiated navigations, it is likely incorrect to always use - // first-party StorageKeys for renderer-initiated navigations. - non_network_url_loader_factories_.emplace( - url::kFileSystemScheme, - CreateFileSystemURLLoaderFactory( - ChildProcessHost::kInvalidUniqueID, - frame_tree_node->frame_tree_node_id(), - storage_partition_->GetFileSystemContext(), storage_domain, - blink::StorageKey(url::Origin::Create(url_)))); + if (base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation) || + !frame_tree_node->navigation_request()->IsRendererInitiated()) { + // TODO(https://crbug.com/256067): Once DevTools has support for sandboxed + // file system inspection there isn't much reason anymore to support browser + // initiated filesystem: navigations, so remove this entirely at that point. + + // Navigations in to filesystem: URLs are deprecated entirely for + // renderer-initiated navigations. The logic below is appropriate for + // browser-initiated navigations, but it is incorrect to always use + // first-party StorageKeys for renderer-initiated navigations when third + // party storage partitioning is enabled. + non_network_url_loader_factories_.emplace( + url::kFileSystemScheme, + CreateFileSystemURLLoaderFactory( + ChildProcessHost::kInvalidUniqueID, + frame_tree_node->frame_tree_node_id(), + storage_partition_->GetFileSystemContext(), storage_domain, + blink::StorageKey(url::Origin::Create(url_)))); + } non_network_url_loader_factories_.emplace(url::kAboutScheme, AboutURLLoaderFactory::Create());
diff --git a/content/browser/renderer_host/back_forward_cache_can_store_document_result.cc b/content/browser/renderer_host/back_forward_cache_can_store_document_result.cc index 604c8a3..46544cc4 100644 --- a/content/browser/renderer_host/back_forward_cache_can_store_document_result.cc +++ b/content/browser/renderer_host/back_forward_cache_can_store_document_result.cc
@@ -209,8 +209,7 @@ disabled_reasons() == other.disabled_reasons() && browsing_instance_swap_result() == other.browsing_instance_swap_result() && - disallow_activation_reasons() == other.disallow_activation_reasons() && - ax_events() == other.ax_events(); + disallow_activation_reasons() == other.disallow_activation_reasons(); } bool BackForwardCacheCanStoreDocumentResult::HasNotRestoredReason( @@ -470,16 +469,6 @@ disallow_activation_reasons_.insert(reason); } -void BackForwardCacheCanStoreDocumentResult::NoDueToAXEvents( - const std::vector<ui::AXEvent>& events) { - for (auto& event : events) { - ax_events_.insert(event.event_type); - } - AddNotRestoredReason( - BackForwardCacheMetrics::NotRestoredReason::kIgnoreEventAndEvict); - disallow_activation_reasons_.insert(DisallowActivationReasonId::kAXEvent); -} - void BackForwardCacheCanStoreDocumentResult::AddReasonsFrom( const BackForwardCacheCanStoreDocumentResult& other) { not_restored_reasons_.PutAll(other.not_restored_reasons_); @@ -493,9 +482,6 @@ for (const auto reason : other.disallow_activation_reasons()) { disallow_activation_reasons_.insert(reason); } - for (const auto event : other.ax_events()) { - ax_events_.insert(event); - } } BackForwardCacheCanStoreDocumentResult::
diff --git a/content/browser/renderer_host/back_forward_cache_can_store_document_result.h b/content/browser/renderer_host/back_forward_cache_can_store_document_result.h index b4d6622..bc97864 100644 --- a/content/browser/renderer_host/back_forward_cache_can_store_document_result.h +++ b/content/browser/renderer_host/back_forward_cache_can_store_document_result.h
@@ -18,7 +18,6 @@ #include "content/public/browser/render_frame_host.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h" -#include "ui/accessibility/ax_event.h" namespace content { @@ -61,8 +60,6 @@ void NoDueToDisableForRenderFrameHostCalled( const std::set<BackForwardCache::DisabledReason>& reasons); void NoDueToDisallowActivation(uint64_t reason); - void NoDueToAXEvents(const std::vector<ui::AXEvent>& events); - void RecordAXEvent(ax::mojom::Event event_type); // The conditions for storing and restoring the pages are different in that // pages with cache-control:no-store can enter back/forward cache depending on @@ -90,8 +87,6 @@ return disallow_activation_reasons_; } - const std::set<ax::mojom::Event>& ax_events() const { return ax_events_; } - std::string ToString() const; void WriteIntoTrace( @@ -109,8 +104,6 @@ std::set<BackForwardCache::DisabledReason> disabled_reasons_; absl::optional<ShouldSwapBrowsingInstance> browsing_instance_swap_result_; std::set<uint64_t> disallow_activation_reasons_; - // The list of the accessibility events that made the page bfcache ineligible. - std::set<ax::mojom::Event> ax_events_; }; } // namespace content
diff --git a/content/browser/renderer_host/back_forward_cache_metrics.cc b/content/browser/renderer_host/back_forward_cache_metrics.cc index 775e20b9..846fcc65 100644 --- a/content/browser/renderer_host/back_forward_cache_metrics.cc +++ b/content/browser/renderer_host/back_forward_cache_metrics.cc
@@ -458,14 +458,6 @@ reason); } - for (const ax::mojom::Event event : page_store_result_->ax_events()) { - base::UmaHistogramSparse( - "BackForwardCache.HistoryNavigationOutcome." - "NotRestoredDueToAccessibility." - "AXEventType", - static_cast<int>(event)); - } - if (!DidSwapBrowsingInstance()) { DCHECK(!navigation->IsServedFromBackForwardCache());
diff --git a/content/browser/renderer_host/blocked_scheme_navigation_browsertest.cc b/content/browser/renderer_host/blocked_scheme_navigation_browsertest.cc index 8812d97..97611305a 100644 --- a/content/browser/renderer_host/blocked_scheme_navigation_browsertest.cc +++ b/content/browser/renderer_host/blocked_scheme_navigation_browsertest.cc
@@ -45,9 +45,9 @@ namespace { // The pattern to catch messages printed by the browser when navigation to a -// URL is blocked. -const char kNavigationBlockedMessage[] = - "Not allowed to navigate top frame to %s URL:*"; +// URL is blocked. Navigation to filesystem: URLs uses a slightly different +// message than other blocked schemes, so use a wildcard to match both. +const char kNavigationBlockedMessage[] = "Not allowed to navigate *to %s URL:*"; // The message printed by the data or filesystem URL when it successfully // navigates.
diff --git a/content/browser/renderer_host/blocked_scheme_navigation_throttle.cc b/content/browser/renderer_host/blocked_scheme_navigation_throttle.cc index a4dd43166..40138893 100644 --- a/content/browser/renderer_host/blocked_scheme_navigation_throttle.cc +++ b/content/browser/renderer_host/blocked_scheme_navigation_throttle.cc
@@ -21,6 +21,7 @@ namespace { const char kConsoleError[] = "Not allowed to navigate top frame to %s URL: %s"; +const char kAnyFrameConsoleError[] = "Not allowed to navigate to %s URL: %s"; } BlockedSchemeNavigationThrottle::BlockedSchemeNavigationThrottle( @@ -30,6 +31,26 @@ BlockedSchemeNavigationThrottle::~BlockedSchemeNavigationThrottle() {} NavigationThrottle::ThrottleCheckResult +BlockedSchemeNavigationThrottle::WillStartRequest() { + NavigationRequest* request = NavigationRequest::From(navigation_handle()); + if (!request->GetURL().SchemeIs(url::kFileSystemScheme)) + return PROCEED; + + if (base::FeatureList::IsEnabled(blink::features::kFileSystemUrlNavigation)) + return PROCEED; + + RenderFrameHost* top_frame = + request->frame_tree_node()->frame_tree()->root()->current_frame_host(); + top_frame->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kError, + base::StringPrintf(kAnyFrameConsoleError, + request->GetURL().scheme().c_str(), + request->GetURL().spec().c_str())); + + return CANCEL; +} + +NavigationThrottle::ThrottleCheckResult BlockedSchemeNavigationThrottle::WillProcessResponse() { NavigationRequest* request = NavigationRequest::From(navigation_handle()); if (request->IsDownload()) @@ -67,6 +88,15 @@ features::kAllowContentInitiatedDataUrlNavigations)) { return std::make_unique<BlockedSchemeNavigationThrottle>(request); } + // Block all renderer initiated navigations to filesystem: URLs. These won't + // load anyway since no URL Loader exists for them, but the throttle lets us + // add a message to the console. + if (!base::FeatureList::IsEnabled( + blink::features::kFileSystemUrlNavigation) && + request->IsRendererInitiated() && + request->GetURL().SchemeIs(url::kFileSystemScheme)) { + return std::make_unique<BlockedSchemeNavigationThrottle>(request); + } return nullptr; }
diff --git a/content/browser/renderer_host/blocked_scheme_navigation_throttle.h b/content/browser/renderer_host/blocked_scheme_navigation_throttle.h index c880f59..20a7b33c 100644 --- a/content/browser/renderer_host/blocked_scheme_navigation_throttle.h +++ b/content/browser/renderer_host/blocked_scheme_navigation_throttle.h
@@ -25,6 +25,7 @@ ~BlockedSchemeNavigationThrottle() override; // NavigationThrottle method: + ThrottleCheckResult WillStartRequest() override; ThrottleCheckResult WillProcessResponse() override; const char* GetNameForLogging() override;
diff --git a/content/browser/renderer_host/pepper/pepper_file_io_host.cc b/content/browser/renderer_host/pepper/pepper_file_io_host.cc index 7cf280e..8abdbfb1 100644 --- a/content/browser/renderer_host/pepper/pepper_file_io_host.cc +++ b/content/browser/renderer_host/pepper/pepper_file_io_host.cc
@@ -116,7 +116,7 @@ void CallOpenFile( PepperFileSystemBrowserHost::GetOperationRunnerCallback get_runner, const storage::FileSystemURL& url, - int file_flags, + uint32_t file_flags, storage::FileSystemOperationRunner::OpenFileCallback callback) { get_runner.Run()->OpenFile( url, file_flags, @@ -182,7 +182,7 @@ if (rv != PP_OK) return rv; - int platform_file_flags = 0; + uint32_t platform_file_flags = 0; if (!ppapi::PepperFileOpenFlagsToPlatformFileFlags(open_flags, &platform_file_flags)) return PP_ERROR_BADARGUMENT; @@ -246,7 +246,7 @@ void PepperFileIOHost::GotUIThreadStuffForInternalFileSystems( ppapi::host::ReplyMessageContext reply_context, - int platform_file_flags, + uint32_t platform_file_flags, UIThreadStuff ui_thread_stuff) { DCHECK_CURRENTLY_ON(BrowserThread::UI); resolved_render_process_id_ = ui_thread_stuff.resolved_render_process_id; @@ -309,7 +309,7 @@ void PepperFileIOHost::GotResolvedRenderProcessId( ppapi::host::ReplyMessageContext reply_context, base::FilePath path, - int file_flags, + uint32_t file_flags, base::ProcessId resolved_render_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); resolved_render_process_id_ = resolved_render_process_id;
diff --git a/content/browser/renderer_host/pepper/pepper_file_io_host.h b/content/browser/renderer_host/pepper/pepper_file_io_host.h index 49e3a636..729b2cc 100644 --- a/content/browser/renderer_host/pepper/pepper_file_io_host.h +++ b/content/browser/renderer_host/pepper/pepper_file_io_host.h
@@ -105,7 +105,7 @@ void GotUIThreadStuffForInternalFileSystems( ppapi::host::ReplyMessageContext reply_context, - int platform_file_flags, + uint32_t platform_file_flags, UIThreadStuff ui_thread_stuff); void DidOpenInternalFile(ppapi::host::ReplyMessageContext reply_context, base::File file, @@ -113,7 +113,7 @@ void GotResolvedRenderProcessId( ppapi::host::ReplyMessageContext reply_context, base::FilePath path, - int file_flags, + uint32_t file_flags, base::ProcessId resolved_render_process_id); void DidOpenQuotaFile(ppapi::host::ReplyMessageContext reply_context,
diff --git a/content/browser/renderer_host/private_network_access_browsertest.cc b/content/browser/renderer_host/private_network_access_browsertest.cc index beb02bb..16380651 100644 --- a/content/browser/renderer_host/private_network_access_browsertest.cc +++ b/content/browser/renderer_host/private_network_access_browsertest.cc
@@ -574,6 +574,9 @@ blink::features::kPlzDedicatedWorker, features::kBlockInsecurePrivateNetworkRequests, features::kPrivateNetworkAccessSendPreflights, + // TODO(https://crbug.com/1332598): Remove all the filesystem: + // URL tests when removing filesystem: navigation for good. + blink::features::kFileSystemUrlNavigation, }, {}) {} };
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index bdda69e..0d16bcd 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -2781,13 +2781,6 @@ gfx::NativeViewAccessible RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() { - // If this method is called when the document is in BackForwardCache, evict - // the document to avoid ignoring any accessibility related events which the - // document might not expect. - if (IsInactiveAndDisallowActivation( - DisallowActivationReasonId::kAXGetNativeView)) - return nullptr; - RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetWidget()->GetView()); if (view) @@ -2812,12 +2805,6 @@ } RenderFrameHostImpl* RenderFrameHostImpl::AccessibilityRenderFrameHost() { - // If this method is called when the frame is in BackForwardCache, evict - // the frame to avoid ignoring any accessibility related events which are not - // expected. - if (IsInactiveAndDisallowActivation( - DisallowActivationReasonId::kAXWebContents)) - return nullptr; return this; } @@ -6092,6 +6079,10 @@ case LifecycleStateImpl::kReadyToBeDeleted: return true; case LifecycleStateImpl::kInBackForwardCache: { + // This function should not be called with kAXEvent when the page is in + // back/forward cache, because |HandleAXevents()| will continue to process + // accessibility events without evicting. + DCHECK_NE(reason, kAXEvent); BackForwardCacheCanStoreDocumentResult can_store_flat; can_store_flat.NoDueToDisallowActivation(reason); EvictFromBackForwardCacheWithFlattenedReasons(can_store_flat); @@ -6123,20 +6114,6 @@ } } -bool RenderFrameHostImpl::IsInactiveAndDisallowActivationForAXEvents( - const std::vector<ui::AXEvent>& events) { - if (lifecycle_state_ != LifecycleStateImpl::kInBackForwardCache) { - return IsInactiveAndDisallowActivation( - DisallowActivationReasonId::kAXEvent); - } - // If the lifecycle state is |LifecycleStateImpl::kInBackForwardCache|, we - // cannot handle accessibility events any more. We should evict the entry. - BackForwardCacheCanStoreDocumentResult can_store_flat; - can_store_flat.NoDueToAXEvents(events); - EvictFromBackForwardCacheWithFlattenedReasons(can_store_flat); - return true; -} - void RenderFrameHostImpl::EvictFromBackForwardCache( blink::mojom::RendererEvictionReason reason) { EvictFromBackForwardCacheWithReason( @@ -7602,8 +7579,14 @@ accessibility_reset_token_ = 0; ui::AXMode accessibility_mode = delegate_->GetAccessibilityMode(); + + // If the page is in back/forward cache, do not return early and continue to + // apply AX tree updates. + // TODO(https://crbug.com/1328126): Define and implement the behavior for when + // the page is prerendering, too. if (accessibility_mode.is_mode_off() || - IsInactiveAndDisallowActivationForAXEvents(updates_and_events->events)) { + (!IsInBackForwardCache() && + IsInactiveAndDisallowActivation(DisallowActivationReasonId::kAXEvent))) { return; } if (accessibility_mode.has_mode(ui::AXMode::kNativeAPIs))
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index edd55b94d..424f4bd 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -479,14 +479,6 @@ void SendAccessibilityEventsToManager( const AXEventNotificationDetails& details); - // This is called when accessibility events arrive from renderer to browser. - // This could cause eviction if the page is in back/forward cache. Returns - // true if the eviction happens, and otherwise calls - // |RenderFrameHost::IsInactiveAndDisallowActivation()| and returns the value - // from there. - bool IsInactiveAndDisallowActivationForAXEvents( - const std::vector<ui::AXEvent>& events); - // Evict the RenderFrameHostImpl with |reason| that causes the eviction. This // constructs a flattened list of NotRestoredReasons and calls // |EvictFromBackForwardCacheWithFlattenedReasons|. @@ -2501,6 +2493,13 @@ int32_t world_id, JavaScriptResultAndTypeCallback callback); + // Call |HandleAXEvents()| for tests. + void HandleAXEventsForTests(const ui::AXTreeID& tree_id, + mojom::AXUpdatesAndEventsPtr updates_and_events, + int32_t reset_token) { + HandleAXEvents(tree_id, std::move(updates_and_events), reset_token); + } + protected: friend class RenderFrameHostFactory;
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index b0e4abfc..cf7d850 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -108,7 +108,6 @@ #include "content/browser/process_lock.h" #include "content/browser/push_messaging/push_messaging_manager.h" #include "content/browser/quota/quota_context.h" -#include "content/browser/renderer_host/code_cache_host_impl.h" #include "content/browser/renderer_host/embedded_frame_sink_provider_impl.h" #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h" #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h" @@ -1500,8 +1499,6 @@ is_unused_(true), delayed_cleanup_needed_(false), within_process_died_observer_(false), - code_cache_host_receivers_( - storage_partition_impl_->GetGeneratedCodeCacheContext()), channel_connected_(false), sent_render_process_ready_(false), shutdown_exit_code_(-1) { @@ -2343,11 +2340,6 @@ AddUIThreadInterface( registry.get(), - base::BindRepeating(&RenderProcessHostImpl::CreateCodeCacheHost, - instance_weak_factory_.GetWeakPtr())); - - AddUIThreadInterface( - registry.get(), base::BindRepeating(&RenderProcessHostImpl::CreateMediaLogRecordHost, instance_weak_factory_.GetWeakPtr())); @@ -2444,17 +2436,6 @@ dom_storage_provider_receiver_.Bind(std::move(receiver)); } -void RenderProcessHostImpl::CreateCodeCacheHost( - mojo::PendingReceiver<blink::mojom::CodeCacheHost> receiver) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Create a new CodeCacheHostImpl and bind it to the given receiver. - // TODO(crbug/1213818): This interface is used by worklets. Once worklets - // are fixed to uuse context specific code cache interface remove this code. - code_cache_host_receivers_.Add(GetID(), net::NetworkIsolationKey(), - std::move(receiver)); -} - void RenderProcessHostImpl::BindMediaInterfaceProxy( mojo::PendingReceiver<media::mojom::InterfaceFactory> receiver) { if (!media_interface_proxy_) @@ -4711,12 +4692,6 @@ instance_weak_factory_.InvalidateWeakPtrs(); - // If RenderProcessHostImpl is reused, the next renderer will send a new - // request for CodeCacheHost. Make sure that we clear the stale - // object so that we can clearly create the new CodeCacheHostImpl while - // asserting we don't have any duplicates. - code_cache_host_receivers_.Clear(); - // It's important not to wait for the DeleteTask to delete the channel // proxy. Kill it off now. That way, in case the profile is going away, the // rest of the objects attached to this RenderProcessHost start going
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 1d3c750..e444046 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -28,7 +28,6 @@ #include "components/services/storage/public/cpp/buckets/bucket_info.h" #include "components/services/storage/public/cpp/quota_error_or.h" #include "content/browser/child_process_launcher.h" -#include "content/browser/renderer_host/code_cache_host_impl.h" #include "content/browser/renderer_host/media/aec_dump_manager_impl.h" #include "content/browser/renderer_host/render_process_host_internal_observer.h" #include "content/browser/storage_partition_impl.h" @@ -787,8 +786,6 @@ mojo::PendingReceiver<viz::mojom::CompositingModeReporter> receiver); void CreateDomStorageProvider( mojo::PendingReceiver<blink::mojom::DomStorageProvider> receiver); - void CreateCodeCacheHost( - mojo::PendingReceiver<blink::mojom::CodeCacheHost> receiver); void CreateRendererHost( mojo::PendingAssociatedReceiver<mojom::RendererHost> receiver); void BindMediaInterfaceProxy( @@ -1119,14 +1116,6 @@ // The memory allocator, if any, in which the renderer will write its metrics. std::unique_ptr<base::PersistentMemoryAllocator> metrics_allocator_; - // TODO(mythria): Currently we are in the process of migrating CodeCacheHost - // interface to use execution specific contexts. Once the migration is - // complete remove CodeCacheHost interface from the RenderProcessHost. - // Currently fetching code caches from main thread use the interface - // associated with the RenderFrameHost. All others (fetches from worker - // threads, writing into code caches) use per-process interface. - CodeCacheHostImpl::ReceiverSet code_cache_host_receivers_; - bool channel_connected_; bool sent_render_process_ready_;
diff --git a/content/browser/startup_helper.cc b/content/browser/startup_helper.cc index c57cdb93..7f18e3a 100644 --- a/content/browser/startup_helper.cc +++ b/content/browser/startup_helper.cc
@@ -49,16 +49,16 @@ namespace { #if BUILDFLAG(IS_ANDROID) // Mobile config, for iOS see ios/web/app/web_main_loop.cc. -constexpr int kThreadPoolDefaultMin = 6; -constexpr int kThreadPoolMax = 8; +constexpr size_t kThreadPoolDefaultMin = 6; +constexpr size_t kThreadPoolMax = 8; constexpr double kThreadPoolCoresMultiplier = 0.6; -constexpr int kThreadPoolOffset = 0; +constexpr size_t kThreadPoolOffset = 0; #else // Desktop config. -constexpr int kThreadPoolDefaultMin = 16; -constexpr int kThreadPoolMax = 32; +constexpr size_t kThreadPoolDefaultMin = 16; +constexpr size_t kThreadPoolMax = 32; constexpr double kThreadPoolCoresMultiplier = 0.6; -constexpr int kThreadPoolOffset = 0; +constexpr size_t kThreadPoolOffset = 0; #endif const base::Feature kBrowserThreadPoolAdjustment{ @@ -73,7 +73,7 @@ void StartBrowserThreadPool() { // Ensure we always support at least one thread regardless of the field trial // param setting. - int min = std::max(kBrowserThreadPoolMin.Get(), 1); + auto min = static_cast<size_t>(std::max(kBrowserThreadPoolMin.Get(), 1)); base::ThreadPoolInstance::InitParams thread_pool_init_params = { base::RecommendedMaxNumberOfThreadsInThreadGroup( min, kThreadPoolMax, kThreadPoolCoresMultiplier, kThreadPoolOffset)};
diff --git a/content/browser/webid/federated_auth_request_impl.cc b/content/browser/webid/federated_auth_request_impl.cc index 05894c4..833c377 100644 --- a/content/browser/webid/federated_auth_request_impl.cc +++ b/content/browser/webid/federated_auth_request_impl.cc
@@ -274,7 +274,8 @@ nonce_ = nonce; prefer_auto_sign_in_ = prefer_auto_sign_in && IsFedCmAutoSigninEnabled(); start_time_ = base::TimeTicks::Now(); - delay_timer_.Reset(); + if (!ShouldCompleteRequestImmediatelyOnError()) + delay_timer_.Reset(); if (!GetApiPermissionContext()) { CompleteRequest(FederatedAuthRequestResult::kError, "", @@ -362,7 +363,8 @@ provider_ = provider; client_id_ = client_id; hint_ = hint; - delay_timer_.Reset(); + if (!ShouldCompleteRequestImmediatelyOnError()) + delay_timer_.Reset(); revoke_callback_ = std::move(callback); if (!GetApiPermissionContext()) { @@ -892,7 +894,7 @@ manifest_list_checked_ = false; idp_metadata_.reset(); - if (should_call_callback) + if (should_call_callback || ShouldCompleteRequestImmediatelyOnError()) std::move(revoke_callback_).Run(status); } @@ -1217,7 +1219,7 @@ CleanUp(); - if (should_call_callback) { + if (should_call_callback || ShouldCompleteRequestImmediatelyOnError()) { errors_logged_to_console_ = false; RequestIdTokenStatus status = @@ -1261,6 +1263,11 @@ blink::mojom::ConsoleMessageLevel::kError, message); } +bool FederatedAuthRequestImpl::ShouldCompleteRequestImmediatelyOnError() { + return GetApiPermissionContext() && + GetApiPermissionContext()->ShouldCompleteRequestImmediatelyOnError(); +} + void FederatedAuthRequestImpl::CompleteLogoutRequest( blink::mojom::LogoutRpsStatus status) { network_manager_.reset();
diff --git a/content/browser/webid/federated_auth_request_impl.h b/content/browser/webid/federated_auth_request_impl.h index 61bf2760..9c113eeb 100644 --- a/content/browser/webid/federated_auth_request_impl.h +++ b/content/browser/webid/federated_auth_request_impl.h
@@ -152,6 +152,8 @@ // information and then we can remove the console error messages. void AddConsoleErrorMessage(blink::mojom::FederatedAuthRequestResult result); + bool ShouldCompleteRequestImmediatelyOnError(); + const raw_ptr<RenderFrameHostImpl> render_frame_host_ = nullptr; const url::Origin origin_;
diff --git a/content/child/child_thread_impl.cc b/content/child/child_thread_impl.cc index c446a31..40336f3 100644 --- a/content/child/child_thread_impl.cc +++ b/content/child/child_thread_impl.cc
@@ -88,7 +88,10 @@ #endif // BUILDFLAG(IS_POSIX) #if BUILDFLAG(IS_MAC) +#include "base/debug/crash_logging.h" #include "base/mac/mach_port_rendezvous.h" +#include "base/no_destructor.h" +#include "content/common/mac/task_port_policy.h" #endif #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX) @@ -299,6 +302,20 @@ #if BUILDFLAG(IS_MAC) void GetTaskPort(GetTaskPortCallback callback) override { + static const base::NoDestructor<MachTaskPortPolicy> policy{ + GetMachTaskPortPolicy()}; + SCOPED_CRASH_KEY_STRING64( + "get-task-port", "amfi-status", + base::StringPrintf("sandbox_ms=%d amfi_status=0x%llx", + policy->amfi_status_retval, policy->amfi_status)); + SCOPED_CRASH_KEY_STRING32("get-task-port", "amfi-boot-arg", + policy->boot_args); + SCOPED_CRASH_KEY_STRING32( + "get-task-port", "csr-kernel-debugger", + base::StringPrintf("ret=%d errno=%d", + policy->csr_kernel_debugger_retval, + policy->csr_kernel_debugger_errno)); + mojo::PlatformHandle task_port( (base::mac::ScopedMachSendRight(task_self_trap()))); std::move(callback).Run(std::move(task_port));
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 3069930..c7291beb8 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -291,6 +291,8 @@ "mac/attributed_string_type_converters.mm", "mac/font_loader.h", "mac/font_loader.mm", + "mac/task_port_policy.cc", + "mac/task_port_policy.h", ] deps += [ ":mac_helpers",
diff --git a/content/common/mac/task_port_policy.cc b/content/common/mac/task_port_policy.cc new file mode 100644 index 0000000..9f73909 --- /dev/null +++ b/content/common/mac/task_port_policy.cc
@@ -0,0 +1,67 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/mac/task_port_policy.h" + +#include <sys/sysctl.h> + +#include "base/logging.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" + +extern "C" { +int csr_check(uint32_t op); +int __sandbox_ms(const char* policy, int op, void* arg); +} + +namespace content { + +MachTaskPortPolicy GetMachTaskPortPolicy() { + MachTaskPortPolicy policy; + + // Undocumented MACF system call to Apple Mobile File Integrity.kext. In + // macOS 12.4 21F79 (and at least back to macOS 12.0), this returns a + // bitmask containing the AMFI status flags. A value of 7 indicates + // "allowEverything" (corresponding to amfi_get_out_of_my_way). + policy.amfi_status_retval = __sandbox_ms("AMFI", 0x60, &policy.amfi_status); + + size_t capacity = 0; + const char kBootArgs[] = "kern.bootargs"; + std::string boot_args; + if (sysctlbyname(kBootArgs, nullptr, &capacity, nullptr, 0) == 0) { + boot_args.resize(capacity); + if (sysctlbyname(kBootArgs, boot_args.data(), &capacity, nullptr, 0) == 0) { + policy.boot_args = ParseBootArgs(boot_args); + } else { + DPLOG(ERROR) << "sysctlbyname"; + } + } else { + DPLOG(ERROR) << "sysctlbyname capacity"; + } + + // From xnu-8019.80.24/bsd/sys/csr.h. Returns -1 with EPERM if the + // operation is not allowed. + const uint32_t CSR_ALLOW_KERNEL_DEBUGGER = 1 << 3; + errno = 0; + policy.csr_kernel_debugger_retval = csr_check(CSR_ALLOW_KERNEL_DEBUGGER); + policy.csr_kernel_debugger_errno = errno; + + return policy; +} + +std::string ParseBootArgs(base::StringPiece input) { + std::vector<base::StringPiece> collect_args; + std::vector<base::StringPiece> all_args = base::SplitStringPiece( + input, " \t", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + for (const auto arg : all_args) { + // Match "amfi=" or "amfi_get_out_of_my_way=". + if (base::StartsWith(arg, "amfi") || + base::StartsWith(arg, "ipc_control_port_options=")) { + collect_args.push_back(arg); + } + } + return base::JoinString(collect_args, " "); +} + +} // namespace content
diff --git a/content/common/mac/task_port_policy.h b/content/common/mac/task_port_policy.h new file mode 100644 index 0000000..e6533df --- /dev/null +++ b/content/common/mac/task_port_policy.h
@@ -0,0 +1,41 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_COMMON_MAC_TASK_PORT_POLICY_H_ +#define CONTENT_COMMON_MAC_TASK_PORT_POLICY_H_ + +#include <cstdint> +#include <string> + +#include "base/strings/string_piece.h" +#include "content/common/content_export.h" + +namespace content { + +struct MachTaskPortPolicy { + // Return value of undocumented MACF policy system call to AMFI to get the + // configuration status. + int amfi_status_retval = 0; + // The configuration status value of the MACF policy system call. + uint64_t amfi_status = 0; + + // Filtered kernel boot arguments relevant to AMFI and task control port + // policy. + std::string boot_args{"unknown"}; + + // Return value and errno of a csr_check() for allowing kernel debugging. + int csr_kernel_debugger_retval = 0; + int csr_kernel_debugger_errno = 0; +}; + +// Gets the current MachTaskPortPolicy. +MachTaskPortPolicy GetMachTaskPortPolicy(); + +// Filters the full kern.bootargs and extracts the relevant ones for +// MachTaskPortPolicy. Exposed for testing. +std::string CONTENT_EXPORT ParseBootArgs(base::StringPiece input); + +} // namespace content + +#endif // CONTENT_COMMON_MAC_TASK_PORT_POLICY_H_
diff --git a/content/common/mac/task_port_policy_unittest.cc b/content/common/mac/task_port_policy_unittest.cc new file mode 100644 index 0000000..d907986 --- /dev/null +++ b/content/common/mac/task_port_policy_unittest.cc
@@ -0,0 +1,30 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/mac/task_port_policy.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +TEST(TaskPortPolicyTest, ParseBootArgs) { + const struct { + const char* input; + const char* output; + } kCases[] = { + {"amfi_get_out_of_my_way=0x1", "amfi_get_out_of_my_way=0x1"}, + {"-s ipc_control_port_options=1", "ipc_control_port_options=1"}, + {"amfi=0x7 ipc_control_port_options=1", + "amfi=0x7 ipc_control_port_options=1"}, + {"not_amfi=200 amfi_unrestrict_task_for_pid=1", + "amfi_unrestrict_task_for_pid=1"}, + {"not_amfi=1 -x -v", ""}, + }; + + for (const auto& testcase : kCases) { + EXPECT_EQ(testcase.output, ParseBootArgs(testcase.input)); + } +} + +} // namespace content
diff --git a/content/common/thread_pool_util.cc b/content/common/thread_pool_util.cc index 83e62f5..ecf1643 100644 --- a/content/common/thread_pool_util.cc +++ b/content/common/thread_pool_util.cc
@@ -10,9 +10,10 @@ namespace content { -int GetMinForegroundThreadsInRendererThreadPool() { +size_t GetMinForegroundThreadsInRendererThreadPool() { // Assume a busy main thread. - return std::max(1, base::SysInfo::NumberOfProcessors() - 1); + return static_cast<size_t>( + std::max(1, base::SysInfo::NumberOfProcessors() - 1)); } } // namespace content
diff --git a/content/common/thread_pool_util.h b/content/common/thread_pool_util.h index 8f98343..230e4e4 100644 --- a/content/common/thread_pool_util.h +++ b/content/common/thread_pool_util.h
@@ -5,11 +5,13 @@ #ifndef CONTENT_COMMON_THREAD_POOL_UTIL_H_ #define CONTENT_COMMON_THREAD_POOL_UTIL_H_ +#include <stddef.h> + namespace content { // Returns the minimum number of foreground threads that the ThreadPool // must have in a process that runs a renderer. -int GetMinForegroundThreadsInRendererThreadPool(); +size_t GetMinForegroundThreadsInRendererThreadPool(); } // namespace content
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index acc96e3..6a32962a 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -166,6 +166,7 @@ "favicon_status.h", "feature_observer_client.h", "federated_identity_active_session_permission_context_delegate.h", + "federated_identity_api_permission_context_delegate.cc", "federated_identity_api_permission_context_delegate.h", "federated_identity_sharing_permission_context_delegate.h", "file_select_listener.h",
diff --git a/content/public/browser/disallow_activation_reason.h b/content/public/browser/disallow_activation_reason.h index 3fe63456..b44dd70 100644 --- a/content/public/browser/disallow_activation_reason.h +++ b/content/public/browser/disallow_activation_reason.h
@@ -33,9 +33,9 @@ kAXHitTestCallback = 9, kAXPerformAction = 10, kAXSetFocus = 11, - kAXGetNativeView = 12, + // kAXGetNativeView = 12 is no longer blocking. kAXGetNativeViewForWindow = 13, - kAXWebContents = 14, + // kAXWebContents = 14 is no longer blocking. kCertificateErrors = 15, kCreateChildFrame = 16, kCommitSameDocumentNavigation = 17,
diff --git a/content/public/browser/federated_identity_api_permission_context_delegate.cc b/content/public/browser/federated_identity_api_permission_context_delegate.cc new file mode 100644 index 0000000..ca95f8c --- /dev/null +++ b/content/public/browser/federated_identity_api_permission_context_delegate.cc
@@ -0,0 +1,14 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/browser/federated_identity_api_permission_context_delegate.h" + +namespace content { + +bool FederatedIdentityApiPermissionContextDelegate:: + ShouldCompleteRequestImmediatelyOnError() const { + return false; +} + +} // namespace content
diff --git a/content/public/browser/federated_identity_api_permission_context_delegate.h b/content/public/browser/federated_identity_api_permission_context_delegate.h index 24c3df4a..2e9bbd0 100644 --- a/content/public/browser/federated_identity_api_permission_context_delegate.h +++ b/content/public/browser/federated_identity_api_permission_context_delegate.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_PUBLIC_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_ #define CONTENT_PUBLIC_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_ +#include "content/common/content_export.h" + namespace url { class Origin; } @@ -13,7 +15,7 @@ // Delegate interface for the FedCM implementation to query whether the FedCM // API is enabled in Site Settings. -class FederatedIdentityApiPermissionContextDelegate { +class CONTENT_EXPORT FederatedIdentityApiPermissionContextDelegate { public: enum class PermissionStatus { GRANTED, @@ -38,6 +40,11 @@ // permission for the passed-in |rp_origin|. Clears the dismiss and ignore // counts. virtual void RemoveEmbargoAndResetCounts(const url::Origin& rp_origin) = 0; + + // This function is so we can avoid the delay in tests. It does not really + // belong on this delegate but we don't have a better one and it seems + // wasteful to add one just for this one testing function. + virtual bool ShouldCompleteRequestImmediatelyOnError() const; }; } // namespace content
diff --git a/content/public/test/test_aggregation_service.cc b/content/public/test/test_aggregation_service.cc index a8888dde..c3db01a 100644 --- a/content/public/test/test_aggregation_service.cc +++ b/content/public/test/test_aggregation_service.cc
@@ -22,7 +22,8 @@ url::Origin reporting_origin, std::vector<GURL> processing_urls, bool is_debug_mode_enabled, - base::Value::Dict additional_fields) + base::Value::Dict additional_fields, + std::string api_version) : operation(operation), bucket(bucket), value(value), @@ -30,7 +31,8 @@ reporting_origin(std::move(reporting_origin)), processing_urls(std::move(processing_urls)), is_debug_mode_enabled(is_debug_mode_enabled), - additional_fields(std::move(additional_fields)) {} + additional_fields(std::move(additional_fields)), + api_version(std::move(api_version)) {} TestAggregationService::AssembleRequest::AssembleRequest( AssembleRequest&& other) = default;
diff --git a/content/public/test/test_aggregation_service.h b/content/public/test/test_aggregation_service.h index 83ce208d..4b7e4c8 100644 --- a/content/public/test/test_aggregation_service.h +++ b/content/public/test/test_aggregation_service.h
@@ -58,7 +58,8 @@ url::Origin reporting_origin, std::vector<GURL> processing_urls, bool is_debug_mode_enabled, - base::Value::Dict additional_fields); + base::Value::Dict additional_fields, + std::string api_version); AssembleRequest(AssembleRequest&& other); AssembleRequest& operator=(AssembleRequest&& other); ~AssembleRequest(); @@ -82,6 +83,9 @@ // Additional fields to add to shared_info. base::Value::Dict additional_fields; + + // Specifies the API version. + std::string api_version; }; virtual ~TestAggregationService() = default;
diff --git a/content/renderer/render_process_impl.cc b/content/renderer/render_process_impl.cc index 619510d..02b4f80 100644 --- a/content/renderer/render_process_impl.cc +++ b/content/renderer/render_process_impl.cc
@@ -72,7 +72,7 @@ std::unique_ptr<base::ThreadPoolInstance::InitParams> GetThreadPoolInitParams() { - constexpr int kMaxNumThreadsInForegroundPoolLowerBound = 3; + constexpr size_t kMaxNumThreadsInForegroundPoolLowerBound = 3; return std::make_unique<base::ThreadPoolInstance::InitParams>( std::max(kMaxNumThreadsInForegroundPoolLowerBound, content::GetMinForegroundThreadsInRendererThreadPool()));
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 23fe48a..fae52069 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -548,10 +548,7 @@ std::unique_ptr<VariationsRenderThreadObserver> variations_observer_; // Compositor settings. - int gpu_rasterization_msaa_sample_count_; bool is_lcd_text_enabled_; - bool is_zero_copy_enabled_; - bool is_gpu_memory_buffer_compositor_resources_enabled_; bool is_partial_raster_enabled_; bool is_elastic_overscroll_enabled_; bool is_threaded_animation_enabled_;
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index dea9f8d..51ab896 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -204,12 +204,6 @@ top_level_blame_context_.Initialize(); main_thread_scheduler_->SetTopLevelBlameContext(&top_level_blame_context_); - { - base::AutoLock lock(code_cache_host_lock_); - GetBrowserInterfaceBroker()->GetInterface( - code_cache_host_remote_.InitWithNewPipeAndPassReceiver()); - } - auto io_task_runner = GetIOTaskRunner(); if (io_task_runner) { io_task_runner->PostTask( @@ -360,43 +354,6 @@ return render_thread->GetUserAgentMetadata(); } -void RendererBlinkPlatformImpl::CacheMetadata( - blink::mojom::CodeCacheType cache_type, - const blink::WebURL& url, - base::Time response_time, - const uint8_t* data, - size_t size) { - // The browser-side GeneratedCodeCache ignores writes over 2GB. - if (size > std::numeric_limits<int32_t>::max()) - return; - // Let the browser know we generated cacheable metadata for this resource. - // The browser may cache it and return it on subsequent responses to speed - // the processing of this resource. - GetCodeCacheHost()->DidGenerateCacheableMetadata( - cache_type, url, response_time, - mojo_base::BigBuffer(base::make_span(data, size))); -} - -void RendererBlinkPlatformImpl::FetchCachedCode( - blink::mojom::CodeCacheType cache_type, - const blink::WebURL& url, - FetchCachedCodeCallback callback) { - GetCodeCacheHost()->FetchCachedCode( - cache_type, url, - base::BindOnce( - [](FetchCachedCodeCallback callback, base::Time time, - mojo_base::BigBuffer data) { - std::move(callback).Run(time, std::move(data)); - }, - std::move(callback))); -} - -void RendererBlinkPlatformImpl::ClearCodeCacheEntry( - blink::mojom::CodeCacheType cache_type, - const GURL& url) { - GetCodeCacheHost()->ClearCodeCacheEntry(cache_type, url); -} - bool RendererBlinkPlatformImpl::IsRedirectSafe(const GURL& from_url, const GURL& to_url) { return IsSafeRedirectTarget(from_url, to_url) && @@ -435,21 +392,6 @@ ->CreateWebSocketHandshakeThrottleProvider(); } -void RendererBlinkPlatformImpl::CacheMetadataInCacheStorage( - const blink::WebURL& url, - base::Time response_time, - const uint8_t* data, - size_t size, - const blink::WebSecurityOrigin& cacheStorageOrigin, - const blink::WebString& cacheStorageCacheName) { - // Let the browser know we generated cacheable metadata for this resource in - // CacheStorage. The browser may cache it and return it on subsequent - // responses to speed the processing of this resource. - GetCodeCacheHost()->DidGenerateCacheableMetadataInCacheStorage( - url, response_time, mojo_base::BigBuffer(base::make_span(data, size)), - cacheStorageOrigin, cacheStorageCacheName.Utf8()); -} - WebString RendererBlinkPlatformImpl::DefaultLocale() { return WebString::FromASCII(RenderThread::Get()->GetLocale()); } @@ -1117,20 +1059,6 @@ //------------------------------------------------------------------------------ -mojo::SharedRemote<blink::mojom::CodeCacheHost> -RendererBlinkPlatformImpl::GetCodeCacheHost() { - base::AutoLock lock(code_cache_host_lock_); - if (!code_cache_host_) { - code_cache_host_ = mojo::SharedRemote<blink::mojom::CodeCacheHost>( - std::move(code_cache_host_remote_), - base::ThreadPool::CreateSequencedTaskRunner({})); - } - // mojo::SharedRemote is not thread-safe itself, but it's safe to copy to - // other threads. So, return the code cache host by copy, rather than - // accessing the underlying interface directly. - return code_cache_host_; -} - std::unique_ptr<blink::WebV8ValueConverter> RendererBlinkPlatformImpl::CreateWebV8ValueConverter() { return std::make_unique<V8ValueConverterImpl>();
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 3c2eeb7a..156fb6cd 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -28,7 +28,6 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h" -#include "third_party/blink/public/mojom/loader/code_cache.mojom.h" #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) #include "components/services/font/public/cpp/font_loader.h" // nogncheck @@ -90,23 +89,6 @@ blink::WebString FullUserAgent() override; blink::WebString ReducedUserAgent() override; blink::UserAgentMetadata UserAgentMetadata() override; - void CacheMetadata(blink::mojom::CodeCacheType cache_type, - const blink::WebURL&, - base::Time, - const uint8_t*, - size_t) override; - void FetchCachedCode(blink::mojom::CodeCacheType cache_type, - const blink::WebURL&, - FetchCachedCodeCallback) override; - void ClearCodeCacheEntry(blink::mojom::CodeCacheType cache_type, - const GURL&) override; - void CacheMetadataInCacheStorage( - const blink::WebURL&, - base::Time, - const uint8_t*, - size_t, - const blink::WebSecurityOrigin& cacheStorageOrigin, - const blink::WebString& cacheStorageCacheName) override; bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) override; blink::WebResourceRequestSenderDelegate* GetResourceRequestSenderDelegate() override; @@ -268,10 +250,6 @@ private: bool CheckPreparsedJsCachingEnabled() const; - // Return the mojo interface for making CodeCache calls. Safe to call from - // other threads, as it returns the SharedRemote by copy. - mojo::SharedRemote<blink::mojom::CodeCacheHost> GetCodeCacheHost(); - void Collect3DContextInformation(blink::Platform::GraphicsInfo* gl_info, const gpu::GPUInfo& gpu_info) const; @@ -293,12 +271,6 @@ TopLevelBlameContext top_level_blame_context_; - base::Lock code_cache_host_lock_; - mojo::PendingRemote<blink::mojom::CodeCacheHost> code_cache_host_remote_ - GUARDED_BY(code_cache_host_lock_); - mojo::SharedRemote<blink::mojom::CodeCacheHost> code_cache_host_ - GUARDED_BY(code_cache_host_lock_); - // Event that signals `io_thread_id_` is set and ready to be read. mutable base::WaitableEvent io_thread_id_ready_event_; base::PlatformThreadId io_thread_id_ = base::kInvalidThreadId;
diff --git a/content/shell/browser/shell_federated_permission_context.cc b/content/shell/browser/shell_federated_permission_context.cc index 28fd2171..123ea85 100644 --- a/content/shell/browser/shell_federated_permission_context.cc +++ b/content/shell/browser/shell_federated_permission_context.cc
@@ -6,6 +6,7 @@ #include "base/feature_list.h" #include "content/public/common/content_features.h" +#include "content/shell/common/shell_switches.h" namespace content { @@ -92,4 +93,9 @@ account_identifier)); } +bool ShellFederatedPermissionContext::ShouldCompleteRequestImmediatelyOnError() + const { + return switches::IsRunWebTestsSwitchPresent(); +} + } // namespace content
diff --git a/content/shell/browser/shell_federated_permission_context.h b/content/shell/browser/shell_federated_permission_context.h index cef37a89..8d4072e 100644 --- a/content/shell/browser/shell_federated_permission_context.h +++ b/content/shell/browser/shell_federated_permission_context.h
@@ -57,6 +57,8 @@ const url::Origin& identity_provider, const std::string& account_identifier) override; + bool ShouldCompleteRequestImmediatelyOnError() const override; + private: // Pairs of <RP, IDP> std::set<std::pair<std::string, std::string>> request_permissions_;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 7037cff..84f9721 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -2519,6 +2519,7 @@ "../browser/web_contents/web_drag_dest_mac_unittest.mm", "../browser/web_contents/web_drag_source_mac_unittest.mm", "../common/mac/attributed_string_type_converters_unittest.mm", + "../common/mac/task_port_policy_unittest.cc", "../renderer/sandbox_mac_v2_unittest.mm", ] }
diff --git a/content/test/test_aggregation_service_impl.cc b/content/test/test_aggregation_service_impl.cc index 54f26d6..a20898b 100644 --- a/content/test/test_aggregation_service_impl.cc +++ b/content/test/test_aggregation_service_impl.cc
@@ -135,7 +135,7 @@ request.is_debug_mode_enabled ? AggregatableReportSharedInfo::DebugMode::kEnabled : AggregatableReportSharedInfo::DebugMode::kDisabled, - std::move(request.additional_fields)); + std::move(request.additional_fields), std::move(request.api_version)); absl::optional<AggregatableReportRequest> report_request = AggregatableReportRequest::CreateForTesting(
diff --git a/content/web_test/browser/web_test_browser_main_runner.cc b/content/web_test/browser/web_test_browser_main_runner.cc index d6c78e64..4ef6cc5 100644 --- a/content/web_test/browser/web_test_browser_main_runner.cc +++ b/content/web_test/browser/web_test_browser_main_runner.cc
@@ -25,6 +25,7 @@ #include "components/network_session_configurator/common/network_switches.h" #include "components/viz/common/switches.h" #include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/browser/webid/federated_auth_request_impl.h" #include "content/public/browser/browser_main_runner.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h"
diff --git a/device/fido/features.cc b/device/fido/features.cc index c65ba78..4665117 100644 --- a/device/fido/features.cc +++ b/device/fido/features.cc
@@ -37,7 +37,7 @@ extern const base::Feature kWebAuthnGoogleCorpRemoteDesktopClientPrivilege{ "WebAuthenticationGoogleCorpRemoteDesktopClientPrivilege", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; extern const base::Feature kWebAuthPasskeysUI{ "WebAuthenticationPasskeysUI", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/docs/fuchsia/README.md b/docs/fuchsia/README.md index 056b001..26f293c4b 100644 --- a/docs/fuchsia/README.md +++ b/docs/fuchsia/README.md
@@ -39,6 +39,7 @@ * [Deploying content_shell and running web_tests on Fuchsia](web_tests.md) * [Running GPU integration tests on Fuchsia](gpu_testing.md) * [Running Telemetry Benchmarks on Fuchsia](telemetry.md) +* [Fuchsia Binary Size Bot](../speed/binary_size/fuchsia_binary_size_trybot.md) ## Fuchsia WebEngine and Runners See [Fuchsia WebEngine and Runners](../../fuchsia_web/README.md). @@ -46,4 +47,4 @@ ## Resources for developers working on Chromium for Fuchsia * [Fuchsia platform versioning](platform_versioning.md) -* [Manually updating Chromium to a new Fuchsia SDK](sdk_updates.md) \ No newline at end of file +* [Manually updating Chromium to a new Fuchsia SDK](sdk_updates.md)
diff --git a/docs/process_model_and_site_isolation.md b/docs/process_model_and_site_isolation.md index c5afd44..513a620 100644 --- a/docs/process_model_and_site_isolation.md +++ b/docs/process_model_and_site_isolation.md
@@ -457,7 +457,7 @@ Several academic papers have covered topics about Chromium's process model. [**Security Architecture of the Chromium -Browser**](http://crypto.stanford.edu/websec/chromium/) +Browser**](https://crypto.stanford.edu/websec/chromium/) Adam Barth, Collin Jackson, Charles Reis, and The Google Chrome Team. Stanford Technical Report, September 2008.
diff --git a/docs/testing/rendering_representative_perf_tests.md b/docs/testing/rendering_representative_perf_tests.md deleted file mode 100644 index da3600b..0000000 --- a/docs/testing/rendering_representative_perf_tests.md +++ /dev/null
@@ -1,108 +0,0 @@ -# Representative Performance Tests for Rendering Benchmark - -`rendering_representative_perf_tests` run a subset of stories from rendering -benchmark on CQ, to prevent performance regressions. For each platform there is -a `story_tag` which describes the representative stories used in this test. -These stories will be tested using the [`run_benchmark`](../../tools/perf/run_benchmark) script, and then the recorded values for the target metric (currently `frame_times`) will be -compared with the historical upper limit described in [`src/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json`][rep_perf_json]. - -These tests are currently running on CQ on: -* mac-rel -* win10_chromium_x64_rel_ng - -[TOC] - -## Investigating Representative perf test failures - -The representative perf tests runs a set of stories and measures the `frame_times` metric during the interaction to determine performance. -The common reasons of failure are (1) the measured value is higher than the expected value and (2) crashes while running the tests. - -In the case of difference between values, a message would be logged in the output of the test explaining so. -Example:`animometer_webgl_attrib_arrays higher average frame_times(21.095) compared to upper limit (17.062)` ([Link to the task](https://chromium-swarm.appspot.com/task?d=true&id=4a92ea7a6b40d010)) -This means that the animometer_webgl_attrib_arrays story has the average frame_times of 21 ms and the recorded upper limit for the story (in the tested platform) is 17 ms. - -In these cases the failed story will be ran three more times to make sure that this has not been a flake, and the new result (average of three runs) will be reported in the same format. -For deeper investigation of such cases you can find the traces of the runs in the isolated outputs of the test. In the isolated outputs directory look at `output.json` for the initial run and at `re_run_failures/output.json` for the three traces recorded from re-runs. -If the failure is as a result of an expected regression, please follow the instructions in the next section for the "Updating Expectations". - -In the `output.json` file, you can find the name of the story and under the trace.html field of the story a gs:// link to the trace ([Example](https://isolateserver.appspot.com/browse?namespace=default-gzip&digest=f8961d773cdf0bf121525f29024c0e6c19d42e61&as=output.json)). -To download the trace run: `gsutil cp gs://link_from_output.json trace_name.html` - -Also if tests fail with no specific messages in the output, it will be useful to check the {benchmark}/benchmark_log.txt file in the isolated outputs directory for more detailed log of the failure. - -### Running representative perf tests locally - -You can run the representative perf tests locally for more investigation, but it is important to note that the values may differ with the values reported on the bots as these tests can have different values for different hardware. - -``` -./testing/scripts/run_rendering_benchmark_with_gated_performance.py ./tools/perf/run_benchmark \ ---benchmark rendering.desktop --isolated-script-test-output /tmp/temp_dir/ \ ---isolated-script-test-perf-output /tmp/temp_dir -``` -*rendering.mobile for running mobile representatives* - - -For investigation of crashes (or when the comparison of the values is not the focus) it might be easier to directly run the benchmark for the representative story tags such as: -* `representative_win_desktop (benchmark: rendering.desktop)` -* `representative_mac_desktop (benchmark: rendering.desktop)` -* `representative_mobile (benchmark: rendering.mobile)` - -``` -./tools/perf/run_benchmark rendering.desktop --story-tag-filter representative_win_desktop -``` - -## Updating Expectations - -There might be multiple reasons to skip a story in representative perf tests such as: -* Tests results are flaky and the story needs to be skipped -* Adding a new change with expected regression, so we need to skip the test, so that the change would pass on CQ), and adjust the upper limit later. -* We want to add a new story to the representative set and the appropriate upper limit is not known yet - -In these cases the story should not cause a failure but it needs to record the values for later adjustments. -As a result the preferred method to skip a story of the representative perf test is to mark the specific story as experimental in [`src/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json`][rep_perf_json] along with a bug referring to the cause of test suppression (flakiness, change with expected regression or experimenting with new representatives). This way the test will be run but the values will not be considered for failing the test. - -To do so find the story under the affected platform in [`src/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json`][rep_perf_json] and add the "experimental" tag to it. - -``` -"platform": { - "story_name": { - "ci_095": 0.377, - "avg": 31.486, - "experimental": true, - "_comment": "crbug.com/bug_id" - }, -} -``` -*[Example Cl](https://chromium-review.googlesource.com/c/chromium/src/+/2208294)* - - -## Maintaining Representative Performance Tests - -### Clustering the Benchmark and Choosing Representatives - -The clustering of the benchmark is based on the historical values recorded for -`frame_times`. For steps on clustering the benchmark check [Clustering benchmark stories](../../tools/perf/experimental/story_clustering/README.md). - -Currently there are three sets of representatives described by story tags below: -* `representative_mac_desktop` -* `representative_mobile` -* `representative_win_desktop` - -Adding more stories to representatives or removing stories from the set is -managed by adding and removing story tags above to stories in [rendering benchmark](../../tools/perf/page_sets/rendering). - -### Updating the Upper Limits - -The upper limits for averages and confidence interval (CI) ranges of -`frame_times` described in [`src/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json`][rep_perf_json] are used to passing or failing a test. These values are the 95 percentile of the past 30 runs of the test on each platform (for both average and CI). - -This helps with catching sudden regressions which results in a value higher -than the upper limits. But in case of gradual regressions, the upper limits -may not be useful in not updated frequently. Updating these upper limits also -helps with adopting to improvements. - -Updating these values can be done by running [`src/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits.py`](../../tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits.py) and committing the changes. -The script will create a new JSON file using the values of recent runs in place -of [`src/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json`][rep_perf_json]. - -[rep_perf_json]: ../../testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json \ No newline at end of file
diff --git a/extensions/browser/api/alarms/alarms_api_unittest.cc b/extensions/browser/api/alarms/alarms_api_unittest.cc index 664bb8e..4f06ecd0 100644 --- a/extensions/browser/api/alarms/alarms_api_unittest.cc +++ b/extensions/browser/api/alarms/alarms_api_unittest.cc
@@ -320,7 +320,8 @@ TEST_F(ExtensionAlarmsTest, CreateDelayBelowMinimum) { // Create an alarm with delay below the minimum accepted value. ConsoleLogMessageLocalFrame local_frame; - local_frame.Init(contents()->GetMainFrame()->GetRemoteAssociatedInterfaces()); + local_frame.Init( + contents()->GetPrimaryMainFrame()->GetRemoteAssociatedInterfaces()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(local_frame.message_count(), 0u); CreateAlarm("[\"negative\", {\"delayInMinutes\": -0.2}]");
diff --git a/extensions/browser/api/app_window/app_window_api.cc b/extensions/browser/api/app_window/app_window_api.cc index fc589a8a..6a622cd 100644 --- a/extensions/browser/api/app_window/app_window_api.cc +++ b/extensions/browser/api/app_window/app_window_api.cc
@@ -190,7 +190,7 @@ create_params.window_key); if (existing_window) { content::RenderFrameHost* existing_frame = - existing_window->web_contents()->GetMainFrame(); + existing_window->web_contents()->GetPrimaryMainFrame(); int frame_id = MSG_ROUTING_NONE; if (source_process_id() == existing_frame->GetProcess()->GetID()) { frame_id = existing_frame->GetRoutingID(); @@ -410,7 +410,7 @@ } content::RenderFrameHost* created_frame = - app_window->web_contents()->GetMainFrame(); + app_window->web_contents()->GetPrimaryMainFrame(); int frame_id = MSG_ROUTING_NONE; if (create_params.creator_process_id == created_frame->GetProcess()->GetID()) frame_id = created_frame->GetRoutingID();
diff --git a/extensions/browser/api/app_window/app_window_apitest.cc b/extensions/browser/api/app_window/app_window_apitest.cc index 83bf2ebc..2dc5879 100644 --- a/extensions/browser/api/app_window/app_window_apitest.cc +++ b/extensions/browser/api/app_window/app_window_apitest.cc
@@ -211,7 +211,7 @@ (*app_windows.begin())->web_contents(); EXPECT_EQ(GURL("chrome://version"), app_window_contents->GetLastCommittedURL()); - EXPECT_FALSE(app_window_contents->GetMainFrame()->IsErrorDocument()); + EXPECT_FALSE(app_window_contents->GetPrimaryMainFrame()->IsErrorDocument()); } #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/extensions/browser/api/automation_internal/automation_internal_api.cc b/extensions/browser/api/automation_internal/automation_internal_api.cc index acc1792..84ec787d 100644 --- a/extensions/browser/api/automation_internal/automation_internal_api.cc +++ b/extensions/browser/api/automation_internal/automation_internal_api.cc
@@ -77,7 +77,7 @@ : content::WebContentsObserver(web_contents), request_id_(request_id), callback_(std::move(callback)) { - content::RenderFrameHost* rfh = web_contents->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents->GetPrimaryMainFrame(); rfh->Send(new ExtensionMsg_AutomationQuerySelector( rfh->GetRoutingID(), request_id, acc_obj_id, query)); @@ -300,7 +300,7 @@ *web_contents), browser_context_(web_contents->GetBrowserContext()) { if (web_contents->IsCurrentlyAudible()) { - content::RenderFrameHost* rfh = web_contents->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents->GetPrimaryMainFrame(); if (!rfh) return; @@ -354,7 +354,7 @@ tab_id = automation_api_delegate->GetTabId(contents); } - content::RenderFrameHost* rfh = contents->GetMainFrame(); + content::RenderFrameHost* rfh = contents->GetPrimaryMainFrame(); if (!rfh) return RespondNow(Error("Could not enable accessibility for active tab"));
diff --git a/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc b/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc index 7dbf86b5..e2c52113 100644 --- a/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc +++ b/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc
@@ -1264,23 +1264,23 @@ ASSERT_TRUE(web_contents); GURL example_url("http://example.com"); - simulate_navigation(web_contents->GetMainFrame(), example_url); + simulate_navigation(web_contents->GetPrimaryMainFrame(), example_url); absl::optional<RequestAction> action = matcher->GetAllowlistedFrameActionForTesting( - web_contents->GetMainFrame()); + web_contents->GetPrimaryMainFrame()); EXPECT_FALSE(action); GURL google_url_1("http://google.com/xyz"); - simulate_navigation(web_contents->GetMainFrame(), google_url_1); + simulate_navigation(web_contents->GetPrimaryMainFrame(), google_url_1); action = matcher->GetAllowlistedFrameActionForTesting( - web_contents->GetMainFrame()); + web_contents->GetPrimaryMainFrame()); RequestAction google_rule_2_action = CreateRequestActionForTesting(RequestAction::Type::ALLOW_ALL_REQUESTS, *google_rule_2.id, *google_rule_2.priority); EXPECT_EQ(google_rule_2_action, action); auto* rfh_tester = - content::RenderFrameHostTester::For(web_contents->GetMainFrame()); + content::RenderFrameHostTester::For(web_contents->GetPrimaryMainFrame()); content::RenderFrameHost* child = rfh_tester->AppendChild("sub_frame"); ASSERT_TRUE(child); @@ -1300,9 +1300,9 @@ action = matcher->GetAllowlistedFrameActionForTesting(child); EXPECT_FALSE(action); - simulate_frame_destroyed(web_contents->GetMainFrame()); + simulate_frame_destroyed(web_contents->GetPrimaryMainFrame()); action = matcher->GetAllowlistedFrameActionForTesting( - web_contents->GetMainFrame()); + web_contents->GetPrimaryMainFrame()); EXPECT_FALSE(action); } @@ -1353,7 +1353,7 @@ ->NavigateAndCommit(google_url); testing::NiceMock<content::MockNavigationHandle> navigation_handle( - google_url, web_contents->GetMainFrame()); + google_url, web_contents->GetPrimaryMainFrame()); navigation_handle.set_has_committed(true); matcher->OnDidFinishNavigation(&navigation_handle); @@ -1383,7 +1383,8 @@ params.first_party_origin = url::Origin::Create(google_url); params.is_third_party = true; params.element_type = url_pattern_index::flat::ElementType_SUBDOCUMENT; - params.parent_routing_id = web_contents->GetMainFrame()->GetGlobalId(); + params.parent_routing_id = + web_contents->GetPrimaryMainFrame()->GetGlobalId(); EXPECT_EQ(test_case.expected_action, matcher->GetBeforeRequestAction(params));
diff --git a/extensions/browser/api/messaging/message_service.cc b/extensions/browser/api/messaging/message_service.cc index 91f2c01..729869f 100644 --- a/extensions/browser/api/messaging/message_service.cc +++ b/extensions/browser/api/messaging/message_service.cc
@@ -532,7 +532,8 @@ return; } - MaybeDisableBackForwardCacheForMessaging(receiver_contents->GetMainFrame()); + MaybeDisableBackForwardCacheForMessaging( + receiver_contents->GetPrimaryMainFrame()); const PortId receiver_port_id = source_port_id.GetOppositePortId(); std::unique_ptr<MessagePort> receiver =
diff --git a/extensions/browser/api_unittest.cc b/extensions/browser/api_unittest.cc index 5a21767..fd010741 100644 --- a/extensions/browser/api_unittest.cc +++ b/extensions/browser/api_unittest.cc
@@ -62,7 +62,7 @@ const std::string& args) { function->set_extension(extension()); if (contents_) - function->SetRenderFrameHost(contents_->GetMainFrame()); + function->SetRenderFrameHost(contents_->GetPrimaryMainFrame()); return std::unique_ptr<base::Value>(utils::RunFunctionAndReturnSingleResult( function, args, browser_context())); } @@ -100,7 +100,7 @@ const std::string& args) { function->set_extension(extension()); if (contents_) - function->SetRenderFrameHost(contents_->GetMainFrame()); + function->SetRenderFrameHost(contents_->GetPrimaryMainFrame()); return utils::RunFunctionAndReturnError(function, args, browser_context()); }
diff --git a/extensions/browser/app_window/app_web_contents_helper.cc b/extensions/browser/app_window/app_web_contents_helper.cc index d71035b..825c86da 100644 --- a/extensions/browser/app_window/app_web_contents_helper.cc +++ b/extensions/browser/app_window/app_web_contents_helper.cc
@@ -56,7 +56,7 @@ // TODO(mihaip): Can we check for user gestures instead? WindowOpenDisposition disposition = params.disposition; if (disposition == WindowOpenDisposition::CURRENT_TAB) { - web_contents_->GetMainFrame()->AddMessageToConsole( + web_contents_->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, base::StringPrintf( "Can't open same-window link to \"%s\"; try target=\"_blank\".", @@ -72,7 +72,7 @@ content::WebContents* contents = app_delegate_->OpenURLFromTab(browser_context_, web_contents_, params); if (!contents) { - web_contents_->GetMainFrame()->AddMessageToConsole( + web_contents_->GetPrimaryMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, base::StringPrintf( "Can't navigate to \"%s\"; apps do not support navigation.", @@ -89,7 +89,7 @@ bool has_permission = IsExtensionWithPermissionOrSuggestInConsole( mojom::APIPermissionID::kPointerLock, extension, - web_contents_->GetMainFrame()); + web_contents_->GetPrimaryMainFrame()); if (has_permission) web_contents_->GotResponseToLockMouseRequest(
diff --git a/extensions/browser/app_window/app_window.cc b/extensions/browser/app_window/app_window.cc index 046c7e3d..0af15c6 100644 --- a/extensions/browser/app_window/app_window.cc +++ b/extensions/browser/app_window/app_window.cc
@@ -930,7 +930,7 @@ if (!IsExtensionWithPermissionOrSuggestInConsole( mojom::APIPermissionID::kFullscreen, extension, - source->GetMainFrame())) { + source->GetPrimaryMainFrame())) { return; }
diff --git a/extensions/browser/app_window/app_window_contents.cc b/extensions/browser/app_window/app_window_contents.cc index 0a99175a..063c6a9 100644 --- a/extensions/browser/app_window/app_window_contents.cc +++ b/extensions/browser/app_window/app_window_contents.cc
@@ -46,10 +46,10 @@ void AppWindowContentsImpl::LoadContents(int32_t creator_process_id) { // Sandboxed page that are not in the Chrome App package are loaded in a // different process. - if (web_contents_->GetMainFrame()->GetProcess()->GetID() != + if (web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID() != creator_process_id) { VLOG(1) << "AppWindow created in new process (" - << web_contents_->GetMainFrame()->GetProcess()->GetID() + << web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID() << ") != creator (" << creator_process_id << "). Routing disabled."; } web_contents_->GetController().LoadURL( @@ -64,7 +64,7 @@ base::Value::List args; args.Append(std::move(dictionary)); - content::RenderFrameHost* rfh = web_contents_->GetMainFrame(); + content::RenderFrameHost* rfh = web_contents_->GetPrimaryMainFrame(); // Return early if this method is called before RenderFrameCreated(). (e.g. // if AppWindow is created and shown before navigation, this method is called // for the visibility change.) @@ -78,10 +78,10 @@ void AppWindowContentsImpl::NativeWindowClosed(bool send_onclosed) { // Return early if this method is called when the render frame is not live. - if (!web_contents_->GetMainFrame()->IsRenderFrameLive()) + if (!web_contents_->GetPrimaryMainFrame()->IsRenderFrameLive()) return; ExtensionWebContentsObserver::GetForWebContents(web_contents()) - ->GetLocalFrame(web_contents_->GetMainFrame()) + ->GetLocalFrame(web_contents_->GetPrimaryMainFrame()) ->AppWindowClosed(send_onclosed); }
diff --git a/extensions/browser/content_script_matching_browsertest.cc b/extensions/browser/content_script_matching_browsertest.cc index 7ec3418..32175d1 100644 --- a/extensions/browser/content_script_matching_browsertest.cc +++ b/extensions/browser/content_script_matching_browsertest.cc
@@ -208,7 +208,7 @@ content::RenderFrameHost* tab1_fooFrame() { EXPECT_TRUE(tab1_); - return tab1_->GetMainFrame(); + return tab1_->GetPrimaryMainFrame(); } content::RenderFrameHost* tab1_fooBlankFrame() { @@ -234,7 +234,7 @@ content::RenderFrameHost* tab2_barBlankFrame1() { EXPECT_TRUE(tab2_); - return tab2_->GetMainFrame(); + return tab2_->GetPrimaryMainFrame(); } content::RenderFrameHost* tab2_barBlankFrame2() {
diff --git a/extensions/browser/content_script_tracker.cc b/extensions/browser/content_script_tracker.cc index 49cc755..f551286 100644 --- a/extensions/browser/content_script_tracker.cc +++ b/extensions/browser/content_script_tracker.cc
@@ -332,8 +332,10 @@ owner_site_url.host_piece() == extension.id()) { WebViewContentScriptManager* script_manager = WebViewContentScriptManager::Get(frame->GetBrowserContext()); - int embedder_process_id = - guest->owner_web_contents()->GetMainFrame()->GetProcess()->GetID(); + int embedder_process_id = guest->owner_web_contents() + ->GetPrimaryMainFrame() + ->GetProcess() + ->GetID(); std::set<std::string> script_ids = script_manager->GetContentScriptIDSet( embedder_process_id, guest->view_instance_id());
diff --git a/extensions/browser/extension_api_frame_id_map.cc b/extensions/browser/extension_api_frame_id_map.cc index 9fbe9c26..df1f60a2 100644 --- a/extensions/browser/extension_api_frame_id_map.cc +++ b/extensions/browser/extension_api_frame_id_map.cc
@@ -118,7 +118,7 @@ return nullptr; if (frame_id == kTopFrameId) - return web_contents->GetMainFrame(); + return web_contents->GetPrimaryMainFrame(); DCHECK_GE(frame_id, 1);
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 5b5901317..8c9128e 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1725,6 +1725,7 @@ SHAREDSTORAGEPRIVATE_REMOVE = 1662, FILEMANAGERPRIVATEINTERNAL_GETFILESRESTRICTEDBYDLP = 1663, WMDESKSPRIVATE_GETALLDESKS = 1664, + AUTOTESTPRIVATE_FORCEAUTOTHEMEMODE = 1665, // Last entry: Add new entries above, then run: // tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/browser/extension_host.cc b/extensions/browser/extension_host.cc index 045808b..70279e6b 100644 --- a/extensions/browser/extension_host.cc +++ b/extensions/browser/extension_host.cc
@@ -63,7 +63,7 @@ content::WebContentsObserver::Observe(host_contents_.get()); host_contents_->SetDelegate(this); SetViewType(host_contents_.get(), host_type); - main_frame_host_ = host_contents_->GetMainFrame(); + main_frame_host_ = host_contents_->GetPrimaryMainFrame(); // Listen for when an extension is unloaded from the same profile, as it may // be the same extension that this points to. @@ -211,7 +211,7 @@ // process, so it is expected to lose our connection to the render view. // Do nothing. RenderProcessHost* process_host = - host_contents_->GetMainFrame()->GetProcess(); + host_contents_->GetPrimaryMainFrame()->GetProcess(); if (process_host && process_host->FastShutdownStarted()) return;
diff --git a/extensions/browser/extension_navigation_throttle.cc b/extensions/browser/extension_navigation_throttle.cc index c12b21b..322ef3d0 100644 --- a/extensions/browser/extension_navigation_throttle.cc +++ b/extensions/browser/extension_navigation_throttle.cc
@@ -131,7 +131,7 @@ ProcessManager* process_manager = ProcessManager::Get(browser_context); DCHECK(process_manager); ExtensionHost* host = process_manager->GetExtensionHostForRenderFrameHost( - web_contents->GetMainFrame()); + web_contents->GetPrimaryMainFrame()); // Navigation throttles don't intercept same document navigations, hence we // can ignore that case.
diff --git a/extensions/browser/extension_web_contents_observer.cc b/extensions/browser/extension_web_contents_observer.cc index 11d36d3..43e3b8d 100644 --- a/extensions/browser/extension_web_contents_observer.cc +++ b/extensions/browser/extension_web_contents_observer.cc
@@ -210,7 +210,7 @@ ExtensionRegistry::Get(browser_context_); const Extension* const extension = - GetExtensionFromFrame(web_contents()->GetMainFrame(), false); + GetExtensionFromFrame(web_contents()->GetPrimaryMainFrame(), false); KioskDelegate* const kiosk_delegate = ExtensionsBrowserClient::Get()->GetKioskDelegate(); DCHECK(kiosk_delegate);
diff --git a/extensions/browser/guest_view/extension_options/extension_options_guest.cc b/extensions/browser/guest_view/extension_options/extension_options_guest.cc index bddbd37c..8349c8c 100644 --- a/extensions/browser/guest_view/extension_options/extension_options_guest.cc +++ b/extensions/browser/guest_view/extension_options/extension_options_guest.cc
@@ -264,7 +264,7 @@ if (!url::IsSameOriginWith(navigation_handle->GetURL(), options_page_)) { bad_message::ReceivedBadMessage( - web_contents()->GetMainFrame()->GetProcess(), + web_contents()->GetPrimaryMainFrame()->GetProcess(), bad_message::EOG_BAD_ORIGIN); } }
diff --git a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc index 8c4bea67..ed5510d 100644 --- a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc +++ b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc
@@ -77,7 +77,7 @@ return; // Could happen at tab shutdown. EventRouter::DispatchEventToSender( - owner->GetMainFrame()->GetProcess(), guest->browser_context(), + owner->GetPrimaryMainFrame()->GetProcess(), guest->browser_context(), guest->owner_host(), histogram_value, event_name, content::ChildProcessHost::kInvalidUniqueID, extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId, std::move(event_args), @@ -103,10 +103,12 @@ // Ok for |owner_extension| to be nullptr, the embedder might be WebUI. Feature::Availability availability = feature->IsAvailableToContext( owner_extension, - process_map->GetMostLikelyContextType( - owner_extension, - guest->owner_web_contents()->GetMainFrame()->GetProcess()->GetID(), - &owner_site_url), + process_map->GetMostLikelyContextType(owner_extension, + guest->owner_web_contents() + ->GetPrimaryMainFrame() + ->GetProcess() + ->GetID(), + &owner_site_url), owner_site_url, util::GetBrowserContextId(context_)); return availability.is_available();
diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc index b652f1f..aef9d1a 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc
@@ -381,7 +381,7 @@ if (SetFullscreenState(true)) { if (auto* delegate = embedder_web_contents()->GetDelegate()) { delegate->EnterFullscreenModeForTab( - embedder_web_contents()->GetMainFrame(), options); + embedder_web_contents()->GetPrimaryMainFrame(), options); } } }
diff --git a/extensions/browser/guest_view/web_view/web_view_apitest.cc b/extensions/browser/guest_view/web_view/web_view_apitest.cc index eb2c8d4..ee2ac9b 100644 --- a/extensions/browser/guest_view/web_view/web_view_apitest.cc +++ b/extensions/browser/guest_view/web_view/web_view_apitest.cc
@@ -504,7 +504,7 @@ // before RenderFrameHost receives. auto context_menu_interceptor = std::make_unique<content::ContextMenuInterceptor>( - guest_web_contents->GetMainFrame()); + guest_web_contents->GetPrimaryMainFrame()); // Trigger the context menu. AppShell doesn't show a context menu; this is // just a sanity check that nothing breaks. @@ -770,8 +770,9 @@ "runTest('testRemoveWebviewOnExit')")); content::WebContents* guest_web_contents = GetGuestWebContents(); - EXPECT_TRUE( - guest_web_contents->GetMainFrame()->GetProcess()->IsForGuestsOnly()); + EXPECT_TRUE(guest_web_contents->GetPrimaryMainFrame() + ->GetProcess() + ->IsForGuestsOnly()); ASSERT_TRUE(guest_loaded_listener.WaitUntilSatisfied()); content::WebContentsDestroyedWatcher destroyed_watcher(guest_web_contents);
diff --git a/extensions/browser/guest_view/web_view/web_view_guest.cc b/extensions/browser/guest_view/web_view/web_view_guest.cc index d5fdb2e97..a5b2bc5 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.cc +++ b/extensions/browser/guest_view/web_view/web_view_guest.cc
@@ -308,7 +308,7 @@ void WebViewGuest::CreateWebContents(const base::DictionaryValue& create_params, WebContentsCreatedCallback callback) { RenderProcessHost* owner_render_process_host = - owner_web_contents()->GetMainFrame()->GetProcess(); + owner_web_contents()->GetPrimaryMainFrame()->GetProcess(); DCHECK_EQ(browser_context(), owner_render_process_host->GetBrowserContext()); std::string storage_partition_id; @@ -375,7 +375,7 @@ // // TODO(dcheng): Is granting commit origin really the right thing to do here? content::ChildProcessSecurityPolicy::GetInstance()->GrantCommitOrigin( - new_contents->GetMainFrame()->GetProcess()->GetID(), + new_contents->GetPrimaryMainFrame()->GetProcess()->GetID(), url::Origin::Create(GetOwnerSiteURL())); std::move(callback).Run(new_contents); @@ -392,13 +392,13 @@ web_view_permission_helper_ = std::make_unique<WebViewPermissionHelper>(this); rules_registry_id_ = GetOrGenerateRulesRegistryID( - owner_web_contents()->GetMainFrame()->GetProcess()->GetID(), + owner_web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), view_instance_id()); // We must install the mapping from guests to WebViews prior to resuming // suspended resource loads so that the WebRequest API will catch resource // requests. - PushWebViewStateToIOThread(web_contents()->GetMainFrame()); + PushWebViewStateToIOThread(web_contents()->GetPrimaryMainFrame()); ApplyAttributes(create_params); } @@ -496,15 +496,15 @@ // RenderFrameDeleted(), such as when destroying unattached guests that never // had a RenderFrame created. WebViewRendererState::GetInstance()->RemoveGuest( - web_contents()->GetMainFrame()->GetProcess()->GetID(), - web_contents()->GetMainFrame()->GetRoutingID()); + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), + web_contents()->GetPrimaryMainFrame()->GetRoutingID()); } void WebViewGuest::GuestReady() { // The guest RenderView should always live in an isolated guest process. - CHECK(web_contents()->GetMainFrame()->GetProcess()->IsForGuestsOnly()); + CHECK(web_contents()->GetPrimaryMainFrame()->GetProcess()->IsForGuestsOnly()); ExtensionWebContentsObserver::GetForWebContents(web_contents()) - ->GetLocalFrame(web_contents()->GetMainFrame()) + ->GetLocalFrame(web_contents()->GetPrimaryMainFrame()) ->SetFrameName(name_); // We don't want to accidentally set the opacity of an interstitial page. @@ -709,10 +709,13 @@ void WebViewGuest::Terminate() { base::RecordAction(UserMetricsAction("WebView.Guest.Terminate")); - base::ProcessHandle process_handle = - web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); + base::ProcessHandle process_handle = web_contents() + ->GetPrimaryMainFrame() + ->GetProcess() + ->GetProcess() + .Handle(); if (process_handle) { - web_contents()->GetMainFrame()->GetProcess()->Shutdown( + web_contents()->GetPrimaryMainFrame()->GetProcess()->Shutdown( content::RESULT_CODE_KILLED); } } @@ -732,7 +735,7 @@ // First clear http cache data and then clear the code cache in // |ClearCodeCache| and the rest is cleared in |ClearDataInternal|. int render_process_id = - web_contents()->GetMainFrame()->GetProcess()->GetID(); + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); // We need to clear renderer cache separately for our process because // StoragePartitionHttpCacheDataRemover::ClearData() does not clear that. web_cache::WebCacheManager::GetInstance()->ClearCacheForProcess( @@ -823,7 +826,7 @@ args->SetIntKey(webview::kInternalEntryCount, web_contents()->GetController().GetEntryCount()); args->SetIntKey(webview::kInternalProcessId, - web_contents()->GetMainFrame()->GetProcess()->GetID()); + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()); DispatchEventToView(std::make_unique<GuestViewEvent>( webview::kEventLoadCommit, std::move(args))); @@ -889,7 +892,7 @@ auto args = std::make_unique<base::DictionaryValue>(); args->SetIntKey(webview::kProcessId, - web_contents()->GetMainFrame()->GetProcess()->GetID()); + web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()); args->SetStringKey(webview::kReason, TerminationStatusToString(status)); DispatchEventToView( std::make_unique<GuestViewEvent>(webview::kEventExit, std::move(args))); @@ -1008,7 +1011,7 @@ WebViewRendererState::WebViewInfo web_view_info; web_view_info.embedder_process_id = - owner_web_contents()->GetMainFrame()->GetProcess()->GetID(); + owner_web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); web_view_info.instance_id = view_instance_id(); web_view_info.partition_id = storage_partition_config.partition_name(); web_view_info.owner_host = owner_host(); @@ -1056,7 +1059,7 @@ void WebViewGuest::WillAttachToEmbedder() { rules_registry_id_ = GetOrGenerateRulesRegistryID( - owner_web_contents()->GetMainFrame()->GetProcess()->GetID(), + owner_web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), view_instance_id()); // We must install the mapping from guests to WebViews prior to resuming @@ -1065,7 +1068,7 @@ // // TODO(alexmos): This may be redundant with the call in // RenderFrameCreated() and should be cleaned up. - PushWebViewStateToIOThread(web_contents()->GetMainFrame()); + PushWebViewStateToIOThread(web_contents()->GetPrimaryMainFrame()); } content::JavaScriptDialogManager* WebViewGuest::GetJavaScriptDialogManager( @@ -1218,10 +1221,10 @@ // Return early if this method is called before RenderFrameCreated(). // In that case, we still have a chance to update the name at GuestReady(). - if (!web_contents()->GetMainFrame()->IsRenderFrameLive()) + if (!web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) return; ExtensionWebContentsObserver::GetForWebContents(web_contents()) - ->GetLocalFrame(web_contents()->GetMainFrame()) + ->GetLocalFrame(web_contents()->GetPrimaryMainFrame()) ->SetFrameName(name_); } @@ -1230,7 +1233,7 @@ return; is_spatial_navigation_enabled_ = enabled; ExtensionWebContentsObserver::GetForWebContents(web_contents()) - ->GetLocalFrame(web_contents()->GetMainFrame()) + ->GetLocalFrame(web_contents()->GetPrimaryMainFrame()) ->SetSpatialNavigationEnabled(enabled); } @@ -1256,7 +1259,7 @@ allow_transparency_ = allow; if (!web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetWidget() ->GetView()) @@ -1267,7 +1270,7 @@ void WebViewGuest::SetTransparency() { auto* view = web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetWidget() ->GetView(); @@ -1293,7 +1296,7 @@ return false; } const url::Origin& owner_origin = - owner_web_contents()->GetMainFrame()->GetLastCommittedOrigin(); + owner_web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin(); const bool base_in_owner_origin = owner_origin.IsSameOriginWith(base_url); // |base_url| must be a valid URL. It is also limited to URLs that the owner // is trusted to have control over. @@ -1494,8 +1497,8 @@ } GURL validated_url(url); - web_contents()->GetMainFrame()->GetProcess()->FilterURL(false, - &validated_url); + web_contents()->GetPrimaryMainFrame()->GetProcess()->FilterURL( + false, &validated_url); // As guests do not swap processes on navigation, only navigations to // normal web URLs are supported. No protocol handlers are installed for // other schemes (e.g., WebUI or extensions), and no permissions or bindings @@ -1565,7 +1568,7 @@ bool allow, const std::string& user_input) { auto* guest = WebViewGuest::From( - owner_web_contents()->GetMainFrame()->GetProcess()->GetID(), + owner_web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(), new_window_instance_id); if (!guest) return; @@ -1604,7 +1607,7 @@ // Since we changed fullscreen state, sending a SynchronizeVisualProperties // message ensures that renderer/ sees the change. web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties();
diff --git a/extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.cc b/extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.cc index bff2a8c7..6f434b8d 100644 --- a/extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.cc +++ b/extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.cc
@@ -74,7 +74,7 @@ const Extension* extension = GetExtensionForWebContents(web_contents); if (extension && alerting_frame_origin.IsSameOriginWith( - web_contents->GetMainFrame()->GetLastCommittedOrigin())) { + web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin())) { *name_out = extension->name(); return true; }
diff --git a/extensions/renderer/bindings/api_binding.cc b/extensions/renderer/bindings/api_binding.cc index ae6f419..737ba8f 100644 --- a/extensions/renderer/bindings/api_binding.cc +++ b/extensions/renderer/bindings/api_binding.cc
@@ -74,7 +74,7 @@ dict->FindKeyOfType("returns_async", base::Value::Type::DICTIONARY); return APISignature::CreateFromValues(*params, returns_async, access_checker, - api_name); + api_name, false /*is_event_signature*/); } void RunAPIBindingHandlerCallback( @@ -332,6 +332,21 @@ } } + if (binding::IsResponseValidationEnabled()) { + const base::Value* params = + event_dict->FindKeyOfType("parameters", base::Value::Type::LIST); + // NOTE: At least in tests, events may omit "parameters". It's unclear + // if real schemas do, too. For now, sub in an empty list if necessary. + // TODO(devlin): Track this down and CHECK(params). + base::Value empty_params(base::Value::Type::LIST); + std::unique_ptr<APISignature> event_signature = + APISignature::CreateFromValues( + params ? *params : empty_params, nullptr /*returns_async*/, + access_checker, name, true /*is_event_signature*/); + DCHECK(!event_signature->has_async_return()); + type_refs_->AddEventSignature(full_name, std::move(event_signature)); + } + events_.push_back(std::make_unique<EventData>( std::move(name), std::move(full_name), supports_filters, supports_rules, supports_lazy_listeners, max_listeners,
diff --git a/extensions/renderer/bindings/api_binding_js_util.cc b/extensions/renderer/bindings/api_binding_js_util.cc index 293bc4c9..7391858 100644 --- a/extensions/renderer/bindings/api_binding_js_util.cc +++ b/extensions/renderer/bindings/api_binding_js_util.cc
@@ -305,7 +305,8 @@ custom_signature_name, APISignature::CreateFromValues(*base_signature, nullptr /*returns_async*/, nullptr /*access_checker*/, - custom_signature_name)); + custom_signature_name, + false /*is_event_signature*/)); } void APIBindingJSUtil::ValidateCustomSignature(
diff --git a/extensions/renderer/bindings/api_bindings_system.cc b/extensions/renderer/bindings/api_bindings_system.cc index 8e16846c..243935f 100644 --- a/extensions/renderer/bindings/api_bindings_system.cc +++ b/extensions/renderer/bindings/api_bindings_system.cc
@@ -45,6 +45,8 @@ if (binding::IsResponseValidationEnabled()) { request_handler_.SetResponseValidator( std::make_unique<APIResponseValidator>(&type_reference_map_)); + event_handler_.SetResponseValidator( + std::make_unique<APIResponseValidator>(&type_reference_map_)); } }
diff --git a/extensions/renderer/bindings/api_bindings_system_unittest.cc b/extensions/renderer/bindings/api_bindings_system_unittest.cc index 74ce87b..2c4603f 100644 --- a/extensions/renderer/bindings/api_bindings_system_unittest.cc +++ b/extensions/renderer/bindings/api_bindings_system_unittest.cc
@@ -68,7 +68,12 @@ "parameters": [{"name": "e", "$ref": "alpha.enumRef"}] }], "events": [{ - "name": "alphaEvent" + "name": "alphaEvent", + "parameters": [{ + "name": "eventArg", + "type": "object", + "properties": { "key": {"type": "integer"} } + }] }, { "name": "alphaOtherEvent" }] @@ -320,7 +325,7 @@ });)"; CallFunctionOnObject(context, alpha_api, kTestCall); - const char kResponseArgsJson[] = R"(["response",1,{"key":42}])"; + const char kResponseArgsJson[] = R"([{"key":42}])"; base::Value::List expected_args = ListValueFromString(kResponseArgsJson); bindings_system()->FireEventInContext("alpha.alphaEvent", context, expected_args, nullptr);
diff --git a/extensions/renderer/bindings/api_event_handler.cc b/extensions/renderer/bindings/api_event_handler.cc index 1e805ca..bb2d056 100644 --- a/extensions/renderer/bindings/api_event_handler.cc +++ b/extensions/renderer/bindings/api_event_handler.cc
@@ -18,6 +18,7 @@ #include "base/values.h" #include "content/public/renderer/v8_value_converter.h" #include "extensions/common/mojom/event_dispatcher.mojom.h" +#include "extensions/renderer/bindings/api_response_validator.h" #include "extensions/renderer/bindings/event_emitter.h" #include "extensions/renderer/bindings/get_per_context_data.h" #include "extensions/renderer/bindings/js_runner.h" @@ -109,6 +110,11 @@ exception_handler_(exception_handler) {} APIEventHandler::~APIEventHandler() {} +void APIEventHandler::SetResponseValidator( + std::unique_ptr<APIResponseValidator> validator) { + api_response_validator_ = std::move(validator); +} + v8::Local<v8::Object> APIEventHandler::CreateEventInstance( const std::string& event_name, bool supports_filters, @@ -257,6 +263,17 @@ auto massager_iter = data->massagers.find(event_name); if (massager_iter == data->massagers.end()) { + // Validate the event arguments if there are no massagers (and validation is + // enabled). Unfortunately, massagers both transform the event args from + // unexpected -> expected and (badly!) from expected -> unexpected. As such, + // we simply don't validate if there's a massager attached to the event. + // TODO(crbug.com/1329587): Ideally, we'd be able to validate the response + // after the massagers run. This requires fixing our schema for at least + // chrome.permissions events. + if (api_response_validator_) { + api_response_validator_->ValidateEvent(context, event_name, *arguments); + } + emitter->Fire(context, arguments, std::move(filter), std::move(callback)); } else { DCHECK(!callback) << "Can't use an event callback with argument massagers.";
diff --git a/extensions/renderer/bindings/api_event_handler.h b/extensions/renderer/bindings/api_event_handler.h index d5c949f7..4fa861c 100644 --- a/extensions/renderer/bindings/api_event_handler.h +++ b/extensions/renderer/bindings/api_event_handler.h
@@ -16,6 +16,7 @@ #include "v8/include/v8.h" namespace extensions { +class APIResponseValidator; class ExceptionHandler; // The object to handle API events. This includes vending v8::Objects for the @@ -39,6 +40,9 @@ ~APIEventHandler(); + // Sets the response validator to be used in verifying event arguments. + void SetResponseValidator(std::unique_ptr<APIResponseValidator> validator); + // Returns a new v8::Object for an event with the given |event_name|. If // |notify_on_change| is true, notifies whenever listeners state is changed. // TODO(devlin): Maybe worth creating a Params struct to hold the event @@ -111,6 +115,10 @@ // The exception handler associated with the bindings system; guaranteed to // outlive this object. ExceptionHandler* const exception_handler_; + + // The response validator used to verify event arguments. Only non-null if + // validation is enabled. + std::unique_ptr<APIResponseValidator> api_response_validator_; }; } // namespace extensions
diff --git a/extensions/renderer/bindings/api_response_validator.cc b/extensions/renderer/bindings/api_response_validator.cc index 42cb471..8022d06 100644 --- a/extensions/renderer/bindings/api_response_validator.cc +++ b/extensions/renderer/bindings/api_response_validator.cc
@@ -6,6 +6,8 @@ #include <ostream> +#include "base/containers/contains.h" +#include "base/ranges/algorithm.h" #include "extensions/renderer/bindings/api_binding_util.h" #include "extensions/renderer/bindings/api_signature.h" #include "extensions/renderer/bindings/api_type_reference_map.h" @@ -14,21 +16,35 @@ namespace { -APIResponseValidator::TestHandler::HandlerMethod* - g_failure_handler_for_testing = nullptr; +APIResponseValidator::TestHandler* g_handler_for_testing = nullptr; } // namespace APIResponseValidator::TestHandler::TestHandler(HandlerMethod method) : method_(method) { - DCHECK(!g_failure_handler_for_testing) + DCHECK(!g_handler_for_testing) << "Only one TestHandler is allowed at a time."; - g_failure_handler_for_testing = &method_; + g_handler_for_testing = this; } APIResponseValidator::TestHandler::~TestHandler() { - DCHECK_EQ(&method_, g_failure_handler_for_testing); - g_failure_handler_for_testing = nullptr; + DCHECK_EQ(this, g_handler_for_testing); + g_handler_for_testing = nullptr; +} + +void APIResponseValidator::TestHandler::IgnoreSignature(std::string signature) { + signatures_to_ignore_.insert(std::move(signature)); +} + +void APIResponseValidator::TestHandler::HandleFailure( + const std::string& signature_name, + const std::string& error) { + method_.Run(signature_name, error); +} + +bool APIResponseValidator::TestHandler::ShouldIgnoreSignature( + const std::string& signature_name) const { + return base::Contains(signatures_to_ignore_, signature_name); } APIResponseValidator::APIResponseValidator(const APITypeReferenceMap* type_refs) @@ -72,12 +88,63 @@ } // The response did not match the expected schema. - if (g_failure_handler_for_testing) { - g_failure_handler_for_testing->Run(method_name, error); + if (g_handler_for_testing) { + g_handler_for_testing->HandleFailure(method_name, error); } else { NOTREACHED() << "Error validating response to `" << method_name << "`: " << error; } } +void APIResponseValidator::ValidateEvent( + v8::Local<v8::Context> context, + const std::string& event_name, + const std::vector<v8::Local<v8::Value>>& event_args) { + DCHECK(binding::IsResponseValidationEnabled()); + + const APISignature* signature = type_refs_->GetEventSignature(event_name); + // If there's no corresponding signature, don't validate. This can + // legitimately happen with APIs that create custom requests. + if (!signature) + return; + + if (g_handler_for_testing && + g_handler_for_testing->ShouldIgnoreSignature(event_name)) + return; + + // The following signatures are incorrect (the parameters dispatched to the + // event don't match the schema's event definition). These should be fixed + // and then validated. + // TODO(https://crbug.com/1329587): Eliminate this list. + static constexpr char const* kBrokenSignaturesToIgnore[] = { + "automationInternal.onAccessibilityEvent", + "chromeWebViewInternal.onClicked", + "test.onMessage", + }; + + if (base::ranges::find(kBrokenSignaturesToIgnore, event_name) != + std::end(kBrokenSignaturesToIgnore)) + return; + + std::string error; + if (signature->ValidateCall(context, event_args, *type_refs_, &error)) { + // Response was valid. + return; + } + + // The response did not match the expected schema. + // Pull to helper method. + if (g_handler_for_testing) { + g_handler_for_testing->HandleFailure(event_name, error); + } else { + // TODO(https://crbug.com/1329587): There are a few more lingering events + // that violate their signature, but they only show up on certain builds + // that aren't part of our normal CQ. Avoid a hard crash for now in order + // to land the bulk of this implementation before enabling the hard crash + // to make reverts less painful. + // NOTREACHED() << "Error validating event arguments to `" << event_name + // << "`: " << error; + } +} + } // namespace extensions
diff --git a/extensions/renderer/bindings/api_response_validator.h b/extensions/renderer/bindings/api_response_validator.h index 7628739..8144678 100644 --- a/extensions/renderer/bindings/api_response_validator.h +++ b/extensions/renderer/bindings/api_response_validator.h
@@ -5,6 +5,7 @@ #ifndef EXTENSIONS_RENDERER_BINDINGS_API_RESPONSE_VALIDATOR_H_ #define EXTENSIONS_RENDERER_BINDINGS_API_RESPONSE_VALIDATOR_H_ +#include <set> #include <string> #include <vector> @@ -17,6 +18,8 @@ // A class to validate the responses to API calls sent by the browser. This // helps ensure that the browser returns values that match the expected schema // (which corresponds to the public documentation). +// TODO(devlin): This is now used for both API method responses and event +// arguments. Rename to APISignatureValidator? class APIResponseValidator { public: // Allow overriding the default failure behavior. @@ -32,8 +35,21 @@ ~TestHandler(); + // Ignores the given `signature` for testing purposes. + void IgnoreSignature(std::string signature); + + // Forwards the failure call to the handler `method_`. + void HandleFailure(const std::string& signature_name, + const std::string& error); + + // Returns true if the given `signature_name` should be ignored for + // testing purposes. + bool ShouldIgnoreSignature(const std::string& signature_name) const; + private: HandlerMethod method_; + + std::set<std::string> signatures_to_ignore_; }; // The origin of the callback passed to the response. @@ -65,6 +81,12 @@ const std::string& api_error, CallbackType callback_type); + // Validates a collection of event arguments against the expected schema. + // By default, this will NOTREACHED() in cases of validation failure. + void ValidateEvent(v8::Local<v8::Context> context, + const std::string& event_name, + const std::vector<v8::Local<v8::Value>>& event_args); + private: // The type reference map; guaranteed to outlive this object. const APITypeReferenceMap* type_refs_;
diff --git a/extensions/renderer/bindings/api_signature.cc b/extensions/renderer/bindings/api_signature.cc index 6165522..9a0d69e 100644 --- a/extensions/renderer/bindings/api_signature.cc +++ b/extensions/renderer/bindings/api_signature.cc
@@ -445,6 +445,59 @@ return result; } +// A helper method used to validate a signature for an internal caller (such as +// a response to an API method or event arguments) to ensure it matches the +// expected schema. +bool ValidateSignatureForInternalCaller( + v8::Local<v8::Context> context, + const std::vector<v8::Local<v8::Value>>& arguments, + const std::vector<std::unique_ptr<ArgumentSpec>>& expected, + const APITypeReferenceMap& type_refs, + std::string* error) { + size_t expected_size = expected.size(); + size_t actual_size = arguments.size(); + if (actual_size > expected_size) { + *error = api_errors::TooManyArguments(); + return false; + } + + // Easy validation: arguments go in order, and must match the expected schema. + // Anything less is failure. + std::string parse_error; + for (size_t i = 0; i < actual_size; ++i) { + DCHECK(!arguments[i].IsEmpty()); + const ArgumentSpec& spec = *expected[i]; + if (arguments[i]->IsNullOrUndefined()) { + if (!spec.optional()) { + *error = api_errors::MissingRequiredArgument(spec.name().c_str()); + return false; + } + continue; + } + + if (!spec.ParseArgument(context, arguments[i], type_refs, nullptr, nullptr, + &parse_error)) { + *error = api_errors::ArgumentError(spec.name(), parse_error); + return false; + } + } + + // Responses may omit trailing optional parameters (which would then be + // undefined for the caller). + // NOTE(devlin): It might be nice to see if we could require all arguments to + // be present, no matter what. For one, it avoids this loop, and it would also + // unify what a "not found" value was (some APIs use undefined, some use + // null). + for (size_t i = actual_size; i < expected_size; ++i) { + if (!expected[i]->optional()) { + *error = api_errors::MissingRequiredArgument(expected[i]->name().c_str()); + return false; + } + } + + return true; +} + } // namespace APISignature::ReturnsAsync::ReturnsAsync() = default; @@ -467,7 +520,7 @@ std::vector<std::unique_ptr<ArgumentSpec>> signature, std::unique_ptr<APISignature::ReturnsAsync> returns_async, BindingAccessChecker* access_checker) - : method_signature_(std::move(signature)), + : signature_(std::move(signature)), returns_async_(std::move(returns_async)), access_checker_(access_checker) { if (returns_async_) { @@ -481,7 +534,7 @@ auto callback = std::make_unique<ArgumentSpec>(ArgumentType::FUNCTION); callback->set_optional(returns_async_->optional); callback->set_name("callback"); - method_signature_.push_back(std::move(callback)); + signature_.push_back(std::move(callback)); if (returns_async_->promise_support == binding::APIPromiseSupport::kSupported) { @@ -500,7 +553,8 @@ const base::Value& spec_list, const base::Value* returns_async, BindingAccessChecker* access_checker, - const std::string& api_name) { + const std::string& api_name, + bool is_event_signature) { bool uses_returns_async = returns_async != nullptr; auto argument_specs = ValueListToArgumentSpecs(spec_list, uses_returns_async); @@ -511,8 +565,9 @@ // all the asynchronous API schemas to use the returns_async format it will be // clear when this is the case, but for now we keep a list of the names of // these APIs to ensure we are handling them correctly. + // This is irrelevant for event signatures. const base::Value* returns_async_spec = returns_async; - if (!argument_specs.empty() && + if (!is_event_signature && !argument_specs.empty() && argument_specs.back()->type() == ArgumentType::FUNCTION && !base::Contains(kNonCallbackTrailingFunctionAPINames, api_name)) { DCHECK(!returns_async_spec); @@ -537,7 +592,7 @@ const std::vector<v8::Local<v8::Value>>& arguments, const APITypeReferenceMap& type_refs) const { PromisesAllowed promises_allowed = CheckPromisesAllowed(context); - return V8ArgumentParser(context, method_signature_, arguments, type_refs, + return V8ArgumentParser(context, signature_, arguments, type_refs, promises_allowed) .ParseArguments(has_async_return()); } @@ -547,8 +602,8 @@ const std::vector<v8::Local<v8::Value>>& arguments, const APITypeReferenceMap& type_refs) const { PromisesAllowed promises_allowed = CheckPromisesAllowed(context); - return BaseValueArgumentParser(context, method_signature_, arguments, - type_refs, promises_allowed) + return BaseValueArgumentParser(context, signature_, arguments, type_refs, + promises_allowed) .ParseArguments(has_async_return()); } @@ -615,56 +670,24 @@ std::string* error) const { DCHECK(returns_async_); DCHECK(returns_async_->signature); - size_t expected_size = returns_async_->signature->size(); - size_t actual_size = arguments.size(); - if (actual_size > expected_size) { - *error = api_errors::TooManyArguments(); - return false; - } + return ValidateSignatureForInternalCaller( + context, arguments, *returns_async_->signature, type_refs, error); +} - // Easy validation: arguments go in order, and must match the expected schema. - // Anything less is failure. - std::string parse_error; - for (size_t i = 0; i < actual_size; ++i) { - DCHECK(!arguments[i].IsEmpty()); - const ArgumentSpec& spec = *returns_async_->signature.value()[i]; - if (arguments[i]->IsNullOrUndefined()) { - if (!spec.optional()) { - *error = api_errors::MissingRequiredArgument(spec.name().c_str()); - return false; - } - continue; - } - - if (!spec.ParseArgument(context, arguments[i], type_refs, nullptr, nullptr, - &parse_error)) { - *error = api_errors::ArgumentError(spec.name(), parse_error); - return false; - } - } - - // Responses may omit trailing optional parameters (which would then be - // undefined for the caller). - // NOTE(devlin): It might be nice to see if we could require all arguments to - // be present, no matter what. For one, it avoids this loop, and it would also - // unify what a "not found" value was (some APIs use undefined, some use - // null). - for (size_t i = actual_size; i < expected_size; ++i) { - if (!returns_async_->signature.value()[i]->optional()) { - *error = api_errors::MissingRequiredArgument( - returns_async_->signature.value()[i]->name().c_str()); - return false; - } - } - - return true; +bool APISignature::ValidateCall( + v8::Local<v8::Context> context, + const std::vector<v8::Local<v8::Value>>& arguments, + const APITypeReferenceMap& type_refs, + std::string* error) const { + return ValidateSignatureForInternalCaller(context, arguments, signature_, + type_refs, error); } std::string APISignature::GetExpectedSignature() const { - if (!expected_signature_.empty() || method_signature_.empty()) + if (!expected_signature_.empty() || signature_.empty()) return expected_signature_; - expected_signature_ = ArgumentSpecsToString(method_signature_); + expected_signature_ = ArgumentSpecsToString(signature_); return expected_signature_; }
diff --git a/extensions/renderer/bindings/api_signature.h b/extensions/renderer/bindings/api_signature.h index 9d599f1..3841be9c 100644 --- a/extensions/renderer/bindings/api_signature.h +++ b/extensions/renderer/bindings/api_signature.h
@@ -29,8 +29,10 @@ kDisallowed, }; -// A representation of the expected signature for an API method, along with the +// A representation of the expected signature for an API, along with the // ability to match provided arguments and convert them to base::Values. +// This is primarily used for API methods, but can also be used for API event +// signatures. class APISignature { public: // Struct that bundles all the details about an asynchronous return. @@ -69,7 +71,8 @@ const base::Value& specification_list, const base::Value* returns_async, BindingAccessChecker* access_checker, - const std::string& api_name); + const std::string& api_name, + bool is_event_signature); struct V8ParseResult { // Appease the Chromium style plugin (out of line ctor/dtor). @@ -147,6 +150,15 @@ const APITypeReferenceMap& type_refs, std::string* error) const; + // Same as `ValidateResponse`, but verifies the given `arguments` against the + // `signature_` instead of the `returns_async_` types. This can be used when + // validating that APIs return proper values to an event (which has a + // signature, but no return). + bool ValidateCall(v8::Local<v8::Context> context, + const std::vector<v8::Local<v8::Value>>& arguments, + const APITypeReferenceMap& type_refs, + std::string* error) const; + // Returns a developer-readable string of the expected signature. For // instance, if this signature expects a string 'someStr' and an optional int // 'someInt', this would return "string someStr, optional integer someInt". @@ -162,10 +174,10 @@ // |context|. PromisesAllowed CheckPromisesAllowed(v8::Local<v8::Context> context) const; - // The list of expected arguments for the API method. - std::vector<std::unique_ptr<ArgumentSpec>> method_signature_; + // The list of expected arguments for the API signature. + std::vector<std::unique_ptr<ArgumentSpec>> signature_; - // The details of any asynchronous return the API method may have. Will be + // The details of any asynchronous return an API method may have. This will be // nullptr if the the API doesn't have an asynchronous return. std::unique_ptr<APISignature::ReturnsAsync> returns_async_;
diff --git a/extensions/renderer/bindings/api_type_reference_map.cc b/extensions/renderer/bindings/api_type_reference_map.cc index 9274906..9378919 100644 --- a/extensions/renderer/bindings/api_type_reference_map.cc +++ b/extensions/renderer/bindings/api_type_reference_map.cc
@@ -97,4 +97,18 @@ return iter != custom_signatures_.end() ? iter->second.get() : nullptr; } +void APITypeReferenceMap::AddEventSignature( + const std::string& event_name, + std::unique_ptr<APISignature> signature) { + DCHECK(event_signatures_.find(event_name) == event_signatures_.end()) + << "Cannot re-register signature for: " << event_name; + event_signatures_[event_name] = std::move(signature); +} + +const APISignature* APITypeReferenceMap::GetEventSignature( + const std::string& event_name) const { + auto iter = event_signatures_.find(event_name); + return iter != event_signatures_.end() ? iter->second.get() : nullptr; +} + } // namespace extensions
diff --git a/extensions/renderer/bindings/api_type_reference_map.h b/extensions/renderer/bindings/api_type_reference_map.h index 748e43a..fdfdd20 100644 --- a/extensions/renderer/bindings/api_type_reference_map.h +++ b/extensions/renderer/bindings/api_type_reference_map.h
@@ -68,6 +68,13 @@ // Looks up a custom signature that was previously added. const APISignature* GetCustomSignature(const std::string& name) const; + // Adds a signature for an API event with the given `event_name`. + void AddEventSignature(const std::string& event_name, + std::unique_ptr<APISignature> signature); + + // Retrieves a signature for an API event with the given `event_name`. + const APISignature* GetEventSignature(const std::string& event_name) const; + // Returns the associated APISignature for the given |name|. Logic differs // slightly from a normal GetAPIMethodSignature as we don't want to initialize // a new type if the signature is not found. @@ -80,9 +87,12 @@ InitializeTypeCallback initialize_type_; std::map<std::string, std::unique_ptr<ArgumentSpec>> type_refs_; - std::map<std::string, std::unique_ptr<APISignature>> api_methods_; - std::map<std::string, std::unique_ptr<APISignature>> type_methods_; - std::map<std::string, std::unique_ptr<APISignature>> custom_signatures_; + + using SignatureMap = std::map<std::string, std::unique_ptr<APISignature>>; + SignatureMap api_methods_; + SignatureMap type_methods_; + SignatureMap custom_signatures_; + SignatureMap event_signatures_; }; } // namespace extensions
diff --git a/extensions/renderer/native_extension_bindings_system_unittest.cc b/extensions/renderer/native_extension_bindings_system_unittest.cc index 451a77a57..887cd27 100644 --- a/extensions/renderer/native_extension_bindings_system_unittest.cc +++ b/extensions/renderer/native_extension_bindings_system_unittest.cc
@@ -1135,18 +1135,19 @@ EXPECT_EQ(context, api_bridge.As<v8::Object>()->GetCreationContextChecked()); } -class ResponseValidationNativeExtensionBindingsSystemUnittest +class SignatureValidationNativeExtensionBindingsSystemUnittest : public NativeExtensionBindingsSystemUnittest, public testing::WithParamInterface<bool> { public: - ResponseValidationNativeExtensionBindingsSystemUnittest() = default; + SignatureValidationNativeExtensionBindingsSystemUnittest() = default; - ResponseValidationNativeExtensionBindingsSystemUnittest( - const ResponseValidationNativeExtensionBindingsSystemUnittest&) = delete; - ResponseValidationNativeExtensionBindingsSystemUnittest& operator=( - const ResponseValidationNativeExtensionBindingsSystemUnittest&) = delete; + SignatureValidationNativeExtensionBindingsSystemUnittest( + const SignatureValidationNativeExtensionBindingsSystemUnittest&) = delete; + SignatureValidationNativeExtensionBindingsSystemUnittest& operator=( + const SignatureValidationNativeExtensionBindingsSystemUnittest&) = delete; - ~ResponseValidationNativeExtensionBindingsSystemUnittest() override = default; + ~SignatureValidationNativeExtensionBindingsSystemUnittest() override = + default; void SetUp() override { response_validation_override_ = @@ -1163,7 +1164,7 @@ std::unique_ptr<base::AutoReset<bool>> response_validation_override_; }; -TEST_P(ResponseValidationNativeExtensionBindingsSystemUnittest, +TEST_P(SignatureValidationNativeExtensionBindingsSystemUnittest, ResponseValidation) { // The APIResponseValidator should only be used if response validation is // enabled. Otherwise, it should be null. @@ -1239,9 +1240,98 @@ } } +TEST_P(SignatureValidationNativeExtensionBindingsSystemUnittest, + EventArgumentValidation) { + // The APIResponseValidator should only be used if response validation is + // enabled. Otherwise, it should be null. + EXPECT_EQ(GetParam(), bindings_system() + ->api_system() + ->request_handler() + ->has_response_validator_for_testing()); + + absl::optional<std::string> validation_failure_method_name; + absl::optional<std::string> validation_failure_error; + + auto on_validation_failure = + [&validation_failure_method_name, &validation_failure_error]( + const std::string& method_name, const std::string& error) { + validation_failure_method_name = method_name; + validation_failure_error = error; + }; + APIResponseValidator::TestHandler test_validation_failure_handler( + base::BindLambdaForTesting(on_validation_failure)); + + scoped_refptr<const Extension> extension = + ExtensionBuilder("foo").AddPermissions({"idle"}).Build(); + RegisterExtension(extension); + + v8::HandleScope handle_scope(isolate()); + v8::Local<v8::Context> context = MainContext(); + + ScriptContext* script_context = CreateScriptContext( + context, extension.get(), Feature::BLESSED_EXTENSION_CONTEXT); + script_context->set_url(extension->url()); + + bindings_system()->UpdateBindingsForContext(script_context); + + const char kAddListenerFunction[] = + R"((function() { + chrome.idle.onStateChanged.addListener((state) => { + this.returnedState = state; + }); + });)"; + v8::Local<v8::Function> add_listener_function = + FunctionFromString(context, kAddListenerFunction); + RunFunctionOnGlobal(add_listener_function, context, 0, nullptr); + + EXPECT_TRUE(bindings_system()->HasEventListenerInContext( + "idle.onStateChanged", script_context)); + + // Dispatch an event with an argument that matches the expected schema. + { + base::Value::List event_args; + event_args.Append("active"); + bindings_system()->DispatchEventInContext("idle.onStateChanged", event_args, + nullptr, script_context); + } + + // Validation should have succeeded. + std::string returned_state = + GetStringPropertyFromObject(context->Global(), context, "returnedState"); + EXPECT_FALSE(validation_failure_method_name); + EXPECT_FALSE(validation_failure_error); + EXPECT_EQ(R"("active")", returned_state); + + // Now, dispatch the event with an invalid argument. + { + base::Value::List event_args; + event_args.Append("bad enum"); + bindings_system()->DispatchEventInContext("idle.onStateChanged", event_args, + nullptr, script_context); + } + + // Event validation should have failed. + returned_state = + GetStringPropertyFromObject(context->Global(), context, "returnedState"); + + if (GetParam()) { + EXPECT_EQ(validation_failure_method_name, "idle.onStateChanged"); + EXPECT_EQ(api_errors::ArgumentError( + "newState", + api_errors::InvalidEnumValue({"active", "idle", "locked"})), + validation_failure_error.value_or("no value")); + } else { + EXPECT_FALSE(validation_failure_method_name); + EXPECT_FALSE(validation_failure_error); + } + + // Even though validation failed, we still dispatch the event. + EXPECT_EQ(R"("bad enum")", returned_state); +} + INSTANTIATE_TEST_SUITE_P( All, - ResponseValidationNativeExtensionBindingsSystemUnittest, + SignatureValidationNativeExtensionBindingsSystemUnittest, testing::Bool()); } // namespace extensions
diff --git a/extensions/renderer/native_renderer_messaging_service_unittest.cc b/extensions/renderer/native_renderer_messaging_service_unittest.cc index 16622c4c..b8f49b02 100644 --- a/extensions/renderer/native_renderer_messaging_service_unittest.cc +++ b/extensions/renderer/native_renderer_messaging_service_unittest.cc
@@ -17,6 +17,7 @@ #include "extensions/common/value_builder.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/api_binding_types.h" +#include "extensions/renderer/bindings/api_response_validator.h" #include "extensions/renderer/message_target.h" #include "extensions/renderer/messaging_util.h" #include "extensions/renderer/native_extension_bindings_system.h" @@ -26,6 +27,40 @@ namespace extensions { +namespace { + +// Unfortunately, we have a layering violation in the runtime API. The runtime +// API is defined at the //extensions layer, but the `MessageSender` type has an +// optional `tabs.Tab` property. This causes issues in type validation because +// when we try to look up the `tabs.Tab` property, it fails (since it's only +// defined in //chrome). This is a "real bug" in that it's a layering violation, +// but it doesn't have real-world implications since right now the only consumer +// of //extensions is //chrome (and thus, the tabs API will always be defined). +// Ignore validation for the affected runtime message-related events. +class RuntimeMessageValidationIgnorer { + public: + RuntimeMessageValidationIgnorer() + : test_handler_(base::BindRepeating( + &RuntimeMessageValidationIgnorer::HardValidationFailure)) { + test_handler_.IgnoreSignature("runtime.onMessage"); + test_handler_.IgnoreSignature("runtime.onMessageExternal"); + test_handler_.IgnoreSignature("runtime.onConnect"); + } + ~RuntimeMessageValidationIgnorer() = default; + + private: + // Hard-fail on any unexpected validation errors. + static void HardValidationFailure(const std::string& name, + const std::string& failure) { + NOTREACHED() << "Unexpected validation failure: " << name << ", " + << failure; + } + + APIResponseValidator::TestHandler test_handler_; +}; + +} // namespace + class NativeRendererMessagingServiceTest : public NativeExtensionBindingsSystemUnittest { public: @@ -101,6 +136,8 @@ } TEST_F(NativeRendererMessagingServiceTest, OpenMessagePort) { + RuntimeMessageValidationIgnorer message_validation_ignorer; + v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -435,6 +472,8 @@ // this is more thoroughly tested in the OneTimeMessageHandler tests; this is // just to ensure NativeRendererMessagingService correctly forwards the calls. TEST_F(NativeRendererMessagingServiceTest, ReceiveOneTimeMessage) { + RuntimeMessageValidationIgnorer message_validation_ignorer; + v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -498,6 +537,8 @@ // Test sending a one-time message from an external source (e.g., a different // extension). This shouldn't conflict with messages sent from the same source. TEST_F(NativeRendererMessagingServiceTest, TestExternalOneTimeMessages) { + RuntimeMessageValidationIgnorer message_validation_ignorer; + v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext();
diff --git a/extensions/renderer/one_time_message_handler_unittest.cc b/extensions/renderer/one_time_message_handler_unittest.cc index 3ed5ce6e..0e49a25 100644 --- a/extensions/renderer/one_time_message_handler_unittest.cc +++ b/extensions/renderer/one_time_message_handler_unittest.cc
@@ -312,9 +312,10 @@ const PortId port_id(other_context_id, 0, false, SerializationFormat::kJson); EXPECT_FALSE(message_handler()->HasPort(script_context(), port_id)); - v8::Local<v8::Object> sender = gin::DataObjectBuilder(isolate()) - .Set("key", std::string("sender")) - .Build(); + v8::Local<v8::Object> sender = + gin::DataObjectBuilder(isolate()) + .Set("origin", std::string("https://example.com")) + .Build(); message_handler()->AddReceiver(script_context(), port_id, sender, messaging_util::kOnMessageEvent); EXPECT_TRUE(message_handler()->HasPort(script_context(), port_id)); @@ -328,7 +329,8 @@ message_handler()->DeliverMessage(script_context(), message, port_id); EXPECT_EQ("\"Hi\"", GetGlobalProperty(context, "eventMessage")); - EXPECT_EQ(R"({"key":"sender"})", GetGlobalProperty(context, "eventSender")); + EXPECT_EQ(R"({"origin":"https://example.com"})", + GetGlobalProperty(context, "eventSender")); // TODO(devlin): Right now, the port lives eternally. In JS bindings, we have // two ways of dealing with this:
diff --git a/extensions/shell/test/shell_test_helper_aura.cc b/extensions/shell/test/shell_test_helper_aura.cc index 9e9d4c4..4c036c8e 100644 --- a/extensions/shell/test/shell_test_helper_aura.cc +++ b/extensions/shell/test/shell_test_helper_aura.cc
@@ -46,7 +46,7 @@ app_window_contents->GetWebContents()); content::RenderFrameHost* main_frame = - app_window_contents->GetWebContents()->GetMainFrame(); + app_window_contents->GetWebContents()->GetPrimaryMainFrame(); DCHECK(main_frame); AppWindow::CreateParams params;
diff --git a/fuchsia_web/webengine/BUILD.gn b/fuchsia_web/webengine/BUILD.gn index 3e3934b..a91f455 100644 --- a/fuchsia_web/webengine/BUILD.gn +++ b/fuchsia_web/webengine/BUILD.gn
@@ -91,6 +91,7 @@ "//components/cast_streaming/renderer", "//components/cdm/renderer", "//components/client_hints/browser:in_memory", + "//components/embedder_support", "//components/embedder_support:browser_util", "//components/embedder_support/origin_trials", "//components/favicon/content", @@ -259,6 +260,8 @@ "browser/web_engine_browser_main.h", "browser/web_engine_browser_main_parts.cc", "browser/web_engine_browser_main_parts.h", + "browser/web_engine_config.cc", + "browser/web_engine_config.h", "browser/web_engine_content_browser_client.cc", "browser/web_engine_content_browser_client.h", "browser/web_engine_devtools_controller.cc", @@ -546,6 +549,7 @@ "browser/navigation_controller_impl_unittest.cc", "browser/navigation_policy_throttle_unittest.cc", "browser/url_request_rewrite_type_converters_unittest.cc", + "browser/web_engine_config_unittest.cc", "context_provider_impl_unittest.cc", "fake_context.cc", "fake_context.h",
diff --git a/fuchsia_web/webengine/browser/DEPS b/fuchsia_web/webengine/browser/DEPS index 0903581..047aa96 100644 --- a/fuchsia_web/webengine/browser/DEPS +++ b/fuchsia_web/webengine/browser/DEPS
@@ -1,5 +1,6 @@ include_rules = [ # Do NOT add components/cast or other Cast-specific code to this file. + "+cc/base", "+components/client_hints/browser", "+components/favicon/content", "+components/favicon/core", @@ -14,8 +15,10 @@ "+components/url_rewrite/browser", "+components/url_rewrite/common", "+components/url_rewrite/mojom", + "+components/viz/common", "+content/public/common", "+content/public/browser", + "+gpu/config", "+media/base", "+media/capabilities", "+media/fuchsia/cdm/service", @@ -41,6 +44,7 @@ "+ui/display", "+ui/events", "+ui/gfx", + "+ui/gl", "+ui/ozone/public", "+ui/platform_window", "+ui/wm/core",
diff --git a/fuchsia_web/webengine/browser/accessibility_bridge.cc b/fuchsia_web/webengine/browser/accessibility_bridge.cc index e23ae6ee..065f876 100644 --- a/fuchsia_web/webengine/browser/accessibility_bridge.cc +++ b/fuchsia_web/webengine/browser/accessibility_bridge.cc
@@ -266,7 +266,8 @@ action_data.scroll_behavior = ax::mojom::ScrollBehavior::kScrollIfVisible; } - auto* frame = web_contents_->GetMainFrame()->FromAXTreeID(ax_id->first); + auto* frame = + web_contents_->GetPrimaryMainFrame()->FromAXTreeID(ax_id->first); if (!frame) { // Fuchsia targeted a tree that does not exist. callback(false); @@ -280,7 +281,8 @@ // Perform an action with a corresponding event to signal the action has // been pumped through. action_data.action = ax::mojom::Action::kSignalEndOfTest; - web_contents_->GetMainFrame()->AccessibilityPerformAction(action_data); + web_contents_->GetPrimaryMainFrame()->AccessibilityPerformAction( + action_data); } } @@ -296,7 +298,7 @@ action_data.hit_test_event_to_fire = ax::mojom::Event::kHitTestResult; pending_hit_test_callbacks_[action_data.request_id] = std::move(callback); - web_contents_->GetMainFrame()->AccessibilityPerformAction(action_data); + web_contents_->GetPrimaryMainFrame()->AccessibilityPerformAction(action_data); } void AccessibilityBridge::OnSemanticsModeChanged( @@ -420,7 +422,8 @@ MaybeDisconnectTreeFromParentTree(tree); const bool is_main_frame_tree = - tree->GetAXTreeID() == web_contents_->GetMainFrame()->GetAXTreeID(); + tree->GetAXTreeID() == + web_contents_->GetPrimaryMainFrame()->GetAXTreeID(); if (is_main_frame_tree) root_id_ = tree->root()->id(); @@ -578,7 +581,8 @@ } bool AccessibilityBridge::ShouldHoldCommit() { - const auto& main_frame_tree_id = web_contents_->GetMainFrame()->GetAXTreeID(); + const auto& main_frame_tree_id = + web_contents_->GetPrimaryMainFrame()->GetAXTreeID(); auto main_tree_it = ax_trees_.find(main_frame_tree_id); if (main_tree_it == ax_trees_.end()) { // The main tree is not present yet, commit should be held. @@ -681,7 +685,8 @@ absl::optional<AccessibilityBridge::AXNodeID> AccessibilityBridge::GetFocusedNodeId() const { - const auto& main_frame_tree_id = web_contents_->GetMainFrame()->GetAXTreeID(); + const auto& main_frame_tree_id = + web_contents_->GetPrimaryMainFrame()->GetAXTreeID(); const auto main_tree_it = ax_trees_.find(main_frame_tree_id); if (main_tree_it == ax_trees_.end()) return absl::nullopt; @@ -785,7 +790,8 @@ DCHECK(container); const bool is_main_frame_tree = - tree->GetAXTreeID() == web_contents_->GetMainFrame()->GetAXTreeID(); + tree->GetAXTreeID() == + web_contents_->GetPrimaryMainFrame()->GetAXTreeID(); const bool is_root = is_main_frame_tree ? node_id == root_id_ : false; float device_scale_factor = ax_node->id() == tree->root()->id() ? GetDeviceScaleFactor() : 0.0f;
diff --git a/fuchsia_web/webengine/browser/accessibility_bridge_browsertest.cc b/fuchsia_web/webengine/browser/accessibility_bridge_browsertest.cc index 9b60f67..1eba95da 100644 --- a/fuchsia_web/webengine/browser/accessibility_bridge_browsertest.cc +++ b/fuchsia_web/webengine/browser/accessibility_bridge_browsertest.cc
@@ -471,8 +471,9 @@ // Fetch the AXTreeID of the main frame (the page just loaded). This ID will // be used in the operations that follow to simulate new data coming in. - auto tree_id = - frame_impl_->web_contents_for_test()->GetMainFrame()->GetAXTreeID(); + auto tree_id = frame_impl_->web_contents_for_test() + ->GetPrimaryMainFrame() + ->GetAXTreeID(); AccessibilityBridge* bridge = frame_impl_->accessibility_bridge_for_test(); size_t tree_size = 5; @@ -658,8 +659,9 @@ // Fetch the AXTreeID of the main frame (the page just loaded). This ID will // be used in the operations that follow to simulate new data coming in. - auto tree_id = - frame_impl_->web_contents_for_test()->GetMainFrame()->GetAXTreeID(); + auto tree_id = frame_impl_->web_contents_for_test() + ->GetPrimaryMainFrame() + ->GetAXTreeID(); AccessibilityBridge* bridge = frame_impl_->accessibility_bridge_for_test(); size_t tree_size = 5; @@ -818,8 +820,9 @@ // Fetch the AXTreeID of the main frame (the page just loaded). This ID will // be used in the operations that follow to simulate new data coming in. - auto tree_id = - frame_impl_->web_contents_for_test()->GetMainFrame()->GetAXTreeID(); + auto tree_id = frame_impl_->web_contents_for_test() + ->GetPrimaryMainFrame() + ->GetAXTreeID(); AccessibilityBridge* bridge = frame_impl_->accessibility_bridge_for_test(); size_t tree_size = 5; @@ -902,8 +905,9 @@ // Fetch the AXTreeID of the main frame (the page just loaded). This ID will // be used in the operations that follow to simulate new data coming in. - auto tree_id = - frame_impl_->web_contents_for_test()->GetMainFrame()->GetAXTreeID(); + auto tree_id = frame_impl_->web_contents_for_test() + ->GetPrimaryMainFrame() + ->GetAXTreeID(); AccessibilityBridge* bridge = frame_impl_->accessibility_bridge_for_test(); size_t tree_size = 5; @@ -974,8 +978,9 @@ // Fetch the AXTreeID of the main frame (the page just loaded). This ID will // be used in the operations that follow to simulate new data coming in. - auto tree_id = - frame_impl_->web_contents_for_test()->GetMainFrame()->GetAXTreeID(); + auto tree_id = frame_impl_->web_contents_for_test() + ->GetPrimaryMainFrame() + ->GetAXTreeID(); AccessibilityBridge* bridge = frame_impl_->accessibility_bridge_for_test(); size_t tree_size = 5; @@ -1157,7 +1162,7 @@ action_data.target_node_id = bridge->ax_tree_for_test()->root()->id(); frame_impl_->web_contents_for_test() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->AccessibilityPerformAction(action_data); FakeSemanticTree* semantic_tree = semantics_manager_.semantic_tree(); @@ -1186,7 +1191,7 @@ bridge->node_id_mapper_for_test()->ToAXNodeID(new_focus_id)->second; frame_impl_->web_contents_for_test() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->AccessibilityPerformAction(action_data); semantic_tree->RunUntilConditionIsTrue(
diff --git a/fuchsia_web/webengine/browser/autoplay_browsertest.cc b/fuchsia_web/webengine/browser/autoplay_browsertest.cc index c650966..3144b3b 100644 --- a/fuchsia_web/webengine/browser/autoplay_browsertest.cc +++ b/fuchsia_web/webengine/browser/autoplay_browsertest.cc
@@ -69,7 +69,7 @@ context_impl() ->GetFrameImplForTest(&frame.ptr()) ->web_contents_for_test() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kTest);
diff --git a/fuchsia_web/webengine/browser/frame_impl.cc b/fuchsia_web/webengine/browser/frame_impl.cc index 889036af..b77eed7 100644 --- a/fuchsia_web/webengine/browser/frame_impl.cc +++ b/fuchsia_web/webengine/browser/frame_impl.cc
@@ -393,8 +393,8 @@ std::move(callback)); } - web_contents_->GetMainFrame()->ExecuteJavaScript(*script_utf16, - std::move(result_callback)); + web_contents_->GetPrimaryMainFrame()->ExecuteJavaScript( + *script_utf16, std::move(result_callback)); if (!need_result) { // If no result is required then invoke callback() immediately. @@ -1014,7 +1014,7 @@ } void FrameImpl::GetPrivateMemorySize(GetPrivateMemorySizeCallback callback) { - if (!web_contents_->GetMainFrame()->GetProcess()->IsReady()) { + if (!web_contents_->GetPrimaryMainFrame()->GetProcess()->IsReady()) { // Renderer process is not yet started. callback(0); return; @@ -1022,7 +1022,7 @@ zx_info_task_stats_t task_stats; zx_status_t status = zx_object_get_info( - web_contents_->GetMainFrame()->GetProcess()->GetProcess().Handle(), + web_contents_->GetPrimaryMainFrame()->GetProcess()->GetProcess().Handle(), ZX_INFO_TASK_STATS, &task_stats, sizeof(task_stats), nullptr, nullptr); if (status != ZX_OK) {
diff --git a/fuchsia_web/webengine/browser/frame_impl_browsertest.cc b/fuchsia_web/webengine/browser/frame_impl_browsertest.cc index a55ea83..d1d00fc4 100644 --- a/fuchsia_web/webengine/browser/frame_impl_browsertest.cc +++ b/fuchsia_web/webengine/browser/frame_impl_browsertest.cc
@@ -197,7 +197,7 @@ context_impl() ->GetFrameImplForTest(&frame.ptr()) ->web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess(); content::RenderProcessHostWatcher( @@ -689,8 +689,8 @@ content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes; content::RenderFrameDeletedObserver crash_observer( - web_contents->GetMainFrame()); - web_contents->GetMainFrame()->GetProcess()->Shutdown(1); + web_contents->GetPrimaryMainFrame()); + web_contents->GetPrimaryMainFrame()->GetProcess()->Shutdown(1); crash_observer.WaitUntilDeleted(); }
diff --git a/fuchsia_web/webengine/browser/frame_permission_controller.cc b/fuchsia_web/webengine/browser/frame_permission_controller.cc index f85d8a0e..9b24fbe27e 100644 --- a/fuchsia_web/webengine/browser/frame_permission_controller.cc +++ b/fuchsia_web/webengine/browser/frame_permission_controller.cc
@@ -103,7 +103,7 @@ const url::Origin& requesting_origin) { url::Origin embedding_origin = url::Origin::Create( permissions::PermissionUtil::GetLastCommittedOriginAsURL( - web_contents_->GetMainFrame())); + web_contents_->GetPrimaryMainFrame())); const url::Origin& canonical_origin = GetCanonicalOrigin(permission, requesting_origin, embedding_origin);
diff --git a/fuchsia_web/webengine/browser/frame_window_tree_host.cc b/fuchsia_web/webengine/browser/frame_window_tree_host.cc index d8a34b3..9bb5b9a 100644 --- a/fuchsia_web/webengine/browser/frame_window_tree_host.cc +++ b/fuchsia_web/webengine/browser/frame_window_tree_host.cc
@@ -136,8 +136,8 @@ void FrameWindowTreeHost::OnWindowBoundsChanged(const BoundsChange& bounds) { aura::WindowTreeHostPlatform::OnBoundsChanged(bounds); - if (web_contents_->GetMainFrame()->IsRenderFrameLive()) { - web_contents_->GetMainFrame()->GetView()->SetInsets( + if (web_contents_->GetPrimaryMainFrame()->IsRenderFrameLive()) { + web_contents_->GetPrimaryMainFrame()->GetView()->SetInsets( bounds.system_ui_overlap); } }
diff --git a/fuchsia_web/webengine/browser/web_engine_browser_main.cc b/fuchsia_web/webengine/browser/web_engine_browser_main.cc index cbe6647..00216b4 100644 --- a/fuchsia_web/webengine/browser/web_engine_browser_main.cc +++ b/fuchsia_web/webengine/browser/web_engine_browser_main.cc
@@ -6,10 +6,23 @@ #include <memory> +#include "base/logging.h" #include "build/build_config.h" +#include "components/fuchsia_component_support/config_reader.h" #include "content/public/browser/browser_main_runner.h" +#include "fuchsia_web/webengine/browser/web_engine_config.h" int WebEngineBrowserMain(content::MainFunctionParams parameters) { + // Process package config-data if any. + const absl::optional<base::Value>& config = + fuchsia_component_support::LoadPackageConfig(); + if (config) { + bool config_valid = UpdateCommandLineFromConfigFile( + config.value(), base::CommandLine::ForCurrentProcess()); + if (!config_valid) + LOG(FATAL) << "WebEngine config is invalid."; + } + std::unique_ptr<content::BrowserMainRunner> main_runner = content::BrowserMainRunner::Create(); int exit_code = main_runner->Initialize(std::move(parameters));
diff --git a/fuchsia_web/webengine/browser/web_engine_config.cc b/fuchsia_web/webengine/browser/web_engine_config.cc new file mode 100644 index 0000000..6246fd1 --- /dev/null +++ b/fuchsia_web/webengine/browser/web_engine_config.cc
@@ -0,0 +1,168 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia_web/webengine/browser/web_engine_config.h" + +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/containers/contains.h" +#include "base/logging.h" +#include "base/strings/strcat.h" +#include "base/values.h" +#include "cc/base/switches.h" +#include "components/embedder_support/switches.h" +#include "components/viz/common/features.h" +#include "components/viz/common/switches.h" +#include "content/public/common/content_switches.h" +#include "fuchsia_web/webengine/switches.h" +#include "gpu/command_buffer/service/gpu_switches.h" +#include "gpu/config/gpu_switches.h" +#include "media/base/media_switches.h" +#include "third_party/blink/public/common/switches.h" +#include "ui/display/display_switches.h" +#include "ui/gl/gl_switches.h" +#include "ui/ozone/public/ozone_switches.h" + +namespace { + +// Appends `value` to the value of `switch_name` in the `command_line`. +// The switch is assumed to consist of comma-separated values. If `switch_name` +// is already set in `command_line` then a comma will be appended, followed by +// `value`, otherwise the switch will be set to `value`. +void AppendToSwitch(base::StringPiece switch_name, + base::StringPiece value, + base::CommandLine* command_line) { + if (!command_line->HasSwitch(switch_name)) { + command_line->AppendSwitchNative(switch_name, value); + return; + } + + std::string new_value = base::StrCat( + {command_line->GetSwitchValueASCII(switch_name), ",", value}); + command_line->RemoveSwitch(switch_name); + command_line->AppendSwitchNative(switch_name, new_value); +} + +bool AddCommandLineArgsFromConfig(const base::Value& config, + base::CommandLine* command_line) { + const base::Value* args = config.FindDictKey("command-line-args"); + if (!args) + return true; + + static const base::StringPiece kAllowedArgs[] = { + blink::switches::kSharedArrayBufferAllowedOrigins, + blink::switches::kGpuRasterizationMSAASampleCount, + blink::switches::kMinHeightForGpuRasterTile, + cc::switches::kEnableClippedImageScaling, + cc::switches::kEnableGpuBenchmarking, + embedder_support::kOriginTrialPublicKey, + embedder_support::kOriginTrialDisabledFeatures, + embedder_support::kOriginTrialDisabledTokens, + switches::kDisableFeatures, + switches::kDisableGpuWatchdog, + switches::kDisableMipmapGeneration, + // TODO(crbug.com/1082821): Remove this switch from the allow-list. + switches::kEnableCastStreamingReceiver, + switches::kEnableFeatures, + switches::kEnableLowEndDeviceMode, + switches::kForceDeviceScaleFactor, + switches::kForceGpuMemAvailableMb, + switches::kForceGpuMemDiscardableLimitMb, + switches::kForceMaxTextureSize, + switches::kGoogleApiKey, + switches::kMaxDecodedImageSizeMb, + switches::kOzonePlatform, + switches::kRendererProcessLimit, + switches::kUseCmdDecoder, + switches::kV, + switches::kVModule, + switches::kVulkanHeapMemoryLimitMb, + switches::kVulkanSyncCpuMemoryLimitMb, + switches::kWebglAntialiasingMode, + switches::kWebglMSAASampleCount, + }; + + for (const auto arg : args->DictItems()) { + if (!base::Contains(kAllowedArgs, arg.first)) { + // TODO(https://crbug.com/1032439): Increase severity and return false + // once we have a mechanism for soft transitions of supported arguments. + LOG(WARNING) << "Unknown command-line arg: '" << arg.first + << "'. Config file and WebEngine version may not match."; + continue; + } + + if (arg.second.is_none()) { + DCHECK(!command_line->HasSwitch(arg.first)); + command_line->AppendSwitch(arg.first); + } else if (arg.second.is_string()) { + if (arg.first == switches::kEnableFeatures || + arg.first == switches::kDisableFeatures) { + AppendToSwitch(arg.first, arg.second.GetString(), command_line); + } else { + DCHECK(!command_line->HasSwitch(arg.first)) << " " << arg.first; + command_line->AppendSwitchNative(arg.first, arg.second.GetString()); + } + } else { + LOG(ERROR) << "Config command-line arg must be a string: " << arg.first; + return false; + } + + // TODO(https://crbug.com/1023012): enable-low-end-device-mode currently + // fakes 512MB total physical memory, which triggers RGB4444 textures, + // which we don't yet support. + if (arg.first == switches::kEnableLowEndDeviceMode) + command_line->AppendSwitch(blink::switches::kDisableRGBA4444Textures); + } + + return true; +} + +} // namespace + +bool UpdateCommandLineFromConfigFile(const base::Value& config, + base::CommandLine* command_line) { + if (!AddCommandLineArgsFromConfig(config, command_line)) + return false; + + // The following two args are set by calling component. They are used to set + // other flags below. + const bool playready_enabled = + command_line->HasSwitch(switches::kPlayreadyKeySystem); + const bool widevine_enabled = + command_line->HasSwitch(switches::kEnableWidevine); + + const bool allow_protected_graphics = + config.FindBoolPath("allow-protected-graphics").value_or(false); + const bool force_protected_graphics = + config.FindBoolPath("force-protected-graphics").value_or(false); + const bool enable_protected_graphics = + ((playready_enabled || widevine_enabled) && allow_protected_graphics) || + force_protected_graphics; + const bool use_overlays_for_video = + config.FindBoolPath("use-overlays-for-video").value_or(false); + + if (enable_protected_graphics) { + command_line->AppendSwitch(switches::kEnableVulkanProtectedMemory); + command_line->AppendSwitch(switches::kEnableProtectedVideoBuffers); + const bool force_protected_video_buffers = + config.FindBoolPath("force-protected-video-buffers").value_or(false); + if (force_protected_video_buffers) { + command_line->AppendSwitch(switches::kForceProtectedVideoOutputBuffers); + } + } + + if (use_overlays_for_video) { + // Overlays are only available if OutputPresenterFuchsia is in use. + AppendToSwitch(switches::kEnableFeatures, + features::kUseSkiaOutputDeviceBufferQueue.name, + command_line); + AppendToSwitch(switches::kEnableFeatures, + features::kUseRealBuffersForPageFlipTest.name, command_line); + command_line->AppendSwitchASCII(switches::kEnableHardwareOverlays, + "underlay"); + command_line->AppendSwitch(switches::kUseOverlaysForVideo); + } + + return true; +}
diff --git a/fuchsia_web/webengine/browser/web_engine_config.h b/fuchsia_web/webengine/browser/web_engine_config.h new file mode 100644 index 0000000..7bc76f9 --- /dev/null +++ b/fuchsia_web/webengine/browser/web_engine_config.h
@@ -0,0 +1,21 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_WEB_WEBENGINE_BROWSER_WEB_ENGINE_CONFIG_H_ +#define FUCHSIA_WEB_WEBENGINE_BROWSER_WEB_ENGINE_CONFIG_H_ + +#include "fuchsia_web/webengine/web_engine_export.h" + +namespace base { +class Value; +class CommandLine; +} // namespace base + +// Updates the `command_line` based on `config`. Returns `false` if the config +// is invalid. +WEB_ENGINE_EXPORT bool UpdateCommandLineFromConfigFile( + const base::Value& config, + base::CommandLine* command_line); + +#endif // FUCHSIA_WEB_WEBENGINE_BROWSER_WEB_ENGINE_CONFIG_H_
diff --git a/fuchsia_web/webengine/browser/web_engine_config_unittest.cc b/fuchsia_web/webengine/browser/web_engine_config_unittest.cc new file mode 100644 index 0000000..fbeb5162 --- /dev/null +++ b/fuchsia_web/webengine/browser/web_engine_config_unittest.cc
@@ -0,0 +1,61 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia_web/webengine/browser/web_engine_config.h" + +#include "base/command_line.h" +#include "base/values.h" +#include "fuchsia_web/webengine/switches.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +constexpr char kCommandLineArgs[] = "command-line-args"; + +base::Value CreateConfigWithSwitchValue(std::string switch_name, + std::string switch_value) { + base::Value config_dict(base::Value::Type::DICTIONARY); + base::Value args(base::Value::Type::DICTIONARY); + args.SetStringKey(switch_name, switch_value); + config_dict.SetKey(kCommandLineArgs, std::move(args)); + return config_dict; +} + +} // namespace + +TEST(WebEngineConfig, CommandLineArgs) { + // Specify a configuration that sets valid args with valid strings. + auto config = CreateConfigWithSwitchValue("renderer-process-limit", "0"); + base::CommandLine command(base::CommandLine::NO_PROGRAM); + EXPECT_TRUE(UpdateCommandLineFromConfigFile(config, &command)); + EXPECT_EQ(command.GetSwitchValueASCII("renderer-process-limit"), "0"); +} + +TEST(WebEngineConfig, DisallowedCommandLineArgs) { + // Specify a configuration that sets a disallowed command-line argument. + auto config = CreateConfigWithSwitchValue("kittens-are-nice", "0"); + base::CommandLine command(base::CommandLine::NO_PROGRAM); + EXPECT_TRUE(UpdateCommandLineFromConfigFile(config, &command)); + EXPECT_FALSE(command.HasSwitch("kittens-are-nice")); +} + +TEST(WebEngineConfig, WronglyTypedCommandLineArgs) { + base::Value config(base::Value::Type::DICTIONARY); + + // Specify a configuration that sets valid args with invalid value. + base::Value args(base::Value::Type::DICTIONARY); + args.SetBoolKey("renderer-process-limit", false); + config.SetKey(kCommandLineArgs, std::move(args)); + + base::CommandLine command(base::CommandLine::NO_PROGRAM); + EXPECT_FALSE(UpdateCommandLineFromConfigFile(config, &command)); +} + +TEST(WebEngineConfig, WithGoogleApiKeyValue) { + constexpr char kDummyApiKey[] = "apikey123"; + auto config = CreateConfigWithSwitchValue("google-api-key", kDummyApiKey); + base::CommandLine command(base::CommandLine::NO_PROGRAM); + EXPECT_TRUE(UpdateCommandLineFromConfigFile(config, &command)); + EXPECT_EQ(command.GetSwitchValueASCII(switches::kGoogleApiKey), kDummyApiKey); +} \ No newline at end of file
diff --git a/fuchsia_web/webengine/context_provider_impl_unittest.cc b/fuchsia_web/webengine/context_provider_impl_unittest.cc index 6d56a42e..d8a8cad 100644 --- a/fuchsia_web/webengine/context_provider_impl_unittest.cc +++ b/fuchsia_web/webengine/context_provider_impl_unittest.cc
@@ -57,8 +57,6 @@ constexpr uint64_t kTestQuotaBytes = 1024; constexpr char kTestQuotaBytesSwitchValue[] = "1024"; -constexpr char kCommandLineArgs[] = "command-line-args"; - MULTIPROCESS_TEST_MAIN(SpawnContextServer) { base::test::SingleThreadTaskEnvironment task_environment( base::test::SingleThreadTaskEnvironment::MainThreadType::IO); @@ -286,15 +284,6 @@ return output; } -base::Value CreateConfigWithSwitchValue(std::string switch_name, - std::string switch_value) { - base::Value config_dict(base::Value::Type::DICTIONARY); - base::Value args(base::Value::Type::DICTIONARY); - args.SetStringKey(switch_name, switch_value); - config_dict.SetKey(kCommandLineArgs, std::move(args)); - return config_dict; -} - fidl::InterfaceHandle<fuchsia::io::Directory> OpenCacheDirectory() { fidl::InterfaceHandle<fuchsia::io::Directory> cache_handle; zx_status_t result = @@ -586,80 +575,6 @@ CheckContextUnresponsive(&context); } -TEST_F(ContextProviderImplTest, WithConfigWithCommandLineArgs) { - // Specify a configuration that sets valid args with valid strings. - base::Value config_dict = - CreateConfigWithSwitchValue("renderer-process-limit", "0"); - - base::RunLoop loop; - provider_->set_config_for_test(std::move(config_dict)); - fake_environment_.fake_launcher().set_create_component_callback( - base::BindLambdaForTesting([&loop](const base::CommandLine& command) { - loop.Quit(); - EXPECT_TRUE(command.HasSwitch("renderer-process-limit")); - })); - - fuchsia::web::ContextPtr context; - context.set_error_handler([&loop](zx_status_t status) { - loop.Quit(); - ZX_LOG(ERROR, status); - ADD_FAILURE(); - }); - provider_ptr_->Create(BuildCreateContextParams(), context.NewRequest()); - - loop.Run(); -} - -TEST_F(ContextProviderImplTest, WithConfigWithDisallowedCommandLineArgs) { - // Specify a configuration that sets a disallowed command-line argument. - base::Value config_dict = - CreateConfigWithSwitchValue("kittens-are-nice", "0"); - - base::RunLoop loop; - provider_->set_config_for_test(std::move(config_dict)); - fake_environment_.fake_launcher().set_create_component_callback( - base::BindLambdaForTesting([&loop](const base::CommandLine& command) { - loop.Quit(); - EXPECT_FALSE(command.HasSwitch("kittens-are-nice")); - })); - - fuchsia::web::ContextPtr context; - context.set_error_handler([&loop](zx_status_t status) { - loop.Quit(); - ZX_LOG(ERROR, status); - ADD_FAILURE(); - }); - provider_ptr_->Create(BuildCreateContextParams(), context.NewRequest()); - - loop.Run(); -} - -TEST_F(ContextProviderImplTest, WithConfigWithWronglyTypedCommandLineArgs) { - base::Value config_dict(base::Value::Type::DICTIONARY); - - // Specify a configuration that sets valid args with invalid value. - base::Value args(base::Value::Type::DICTIONARY); - args.SetBoolKey("renderer-process-limit", false); - config_dict.SetKey(kCommandLineArgs, std::move(args)); - - base::RunLoop loop; - provider_->set_config_for_test(std::move(config_dict)); - fake_environment_.fake_launcher().set_create_component_callback( - base::BindLambdaForTesting([&loop](const base::CommandLine& command) { - loop.Quit(); - ADD_FAILURE(); - })); - - fuchsia::web::ContextPtr context; - context.set_error_handler([&loop](zx_status_t status) { - loop.Quit(); - EXPECT_EQ(status, ZX_ERR_INTERNAL); - }); - provider_ptr_->Create(BuildCreateContextParams(), context.NewRequest()); - - loop.Run(); -} - // Tests that unsafely_treat_insecure_origins_as_secure properly adds the right // command-line arguments to the Context process. TEST_F(ContextProviderImplTest, WithInsecureOriginsAsSecure) { @@ -721,33 +636,6 @@ loop.Run(); } -TEST_F(ContextProviderImplTest, WithGoogleApiKeyValue) { - constexpr char kDummyApiKey[] = "apikey123"; - - base::Value config_dict = - CreateConfigWithSwitchValue("google-api-key", kDummyApiKey); - - base::RunLoop loop; - provider_->set_config_for_test(std::move(config_dict)); - fake_environment_.fake_launcher().set_create_component_callback( - base::BindLambdaForTesting( - [&loop, kDummyApiKey](const base::CommandLine& command) { - loop.Quit(); - EXPECT_EQ(command.GetSwitchValueASCII(switches::kGoogleApiKey), - kDummyApiKey); - })); - - fuchsia::web::ContextPtr context; - context.set_error_handler([&loop](zx_status_t status) { - loop.Quit(); - ZX_LOG(ERROR, status); - ADD_FAILURE(); - }); - provider_ptr_->Create(BuildCreateContextParams(), context.NewRequest()); - - loop.Run(); -} - // TODO(crbug.com/1013412): This test doesn't actually exercise DRM, so could // be executed everywhere if DRM support were configurable. #if defined(ARCH_CPU_ARM64)
diff --git a/fuchsia_web/webengine/test/scenic_test_helper.cc b/fuchsia_web/webengine/test/scenic_test_helper.cc index da7e9429..8f90d36 100644 --- a/fuchsia_web/webengine/test/scenic_test_helper.cc +++ b/fuchsia_web/webengine/test/scenic_test_helper.cc
@@ -46,7 +46,8 @@ void ScenicTestHelper::SetUpViewForInteraction( content::WebContents* web_contents) { - content::RenderWidgetHostView* view = web_contents->GetMainFrame()->GetView(); + content::RenderWidgetHostView* view = + web_contents->GetPrimaryMainFrame()->GetView(); view->SetBounds(kBounds); view->Focus(); base::RunLoop().RunUntilIdle();
diff --git a/fuchsia_web/webinstance_host/BUILD.gn b/fuchsia_web/webinstance_host/BUILD.gn index 0cfce30..f9322bc 100644 --- a/fuchsia_web/webinstance_host/BUILD.gn +++ b/fuchsia_web/webinstance_host/BUILD.gn
@@ -25,7 +25,6 @@ deps = [ "//base", "//base:base_static", - "//components/embedder_support", "//components/fuchsia_component_support", "//content/public/common", "//fuchsia/base", @@ -33,13 +32,11 @@ "//gpu/command_buffer/service", "//media", "//services/network/public/cpp", - "//third_party/blink/public/common", "//third_party/fuchsia-sdk/sdk/pkg/async", "//third_party/fuchsia-sdk/sdk/pkg/fdio", "//third_party/fuchsia-sdk/sdk/pkg/sys_cpp", "//third_party/fuchsia-sdk/sdk/pkg/zx", "//third_party/widevine/cdm:headers", - "//ui/gfx", "//ui/ozone", ] public_deps = [
diff --git a/fuchsia_web/webinstance_host/DEPS b/fuchsia_web/webinstance_host/DEPS index 077e7f2..9c7461f 100644 --- a/fuchsia_web/webinstance_host/DEPS +++ b/fuchsia_web/webinstance_host/DEPS
@@ -1,14 +1,11 @@ include_rules = [ - "+cc/base/switches.h", "+components/embedder_support", "+components/fuchsia_component_support", - "+components/viz/common", "+content/public/common", "+fuchsia/base", "+fuchsia_web/webengine/features.h", "+fuchsia_web/webengine/switches.h", "+gpu/config/gpu_finch_features.h", - "+gpu/config/gpu_switches.h", "+gpu/command_buffer/service/gpu_switches.h", "+media/base/key_system_names.h", "+media/base/media_switches.h",
diff --git a/fuchsia_web/webinstance_host/web_instance_host.cc b/fuchsia_web/webinstance_host/web_instance_host.cc index 019c285..e5df747d 100644 --- a/fuchsia_web/webinstance_host/web_instance_host.cc +++ b/fuchsia_web/webinstance_host/web_instance_host.cc
@@ -24,7 +24,6 @@ #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" -#include "base/containers/contains.h" #include "base/files/file_path.h" #include "base/fuchsia/file_utils.h" #include "base/fuchsia/fuchsia_logging.h" @@ -36,29 +35,21 @@ #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/values.h" #include "build/build_config.h" -#include "cc/base/switches.h" -#include "components/embedder_support/switches.h" #include "components/fuchsia_component_support/config_reader.h" #include "components/fuchsia_component_support/feedback_registration.h" -#include "components/viz/common/features.h" -#include "components/viz/common/switches.h" #include "content/public/common/content_switches.h" #include "fuchsia/base/string_util.h" #include "fuchsia_web/webengine/features.h" #include "fuchsia_web/webengine/switches.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/config/gpu_finch_features.h" -#include "gpu/config/gpu_switches.h" #include "media/base/key_system_names.h" #include "media/base/media_switches.h" #include "net/http/http_util.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/network_switches.h" -#include "third_party/blink/public/common/switches.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" -#include "ui/display/display_switches.h" #include "ui/gfx/switches.h" #include "ui/gl/gl_switches.h" #include "ui/ozone/public/ozone_switches.h" @@ -340,76 +331,6 @@ return true; } -// Returns false if the config is present but has invalid contents. -bool MaybeAddCommandLineArgsFromConfig(const base::Value& config, - base::CommandLine* command_line) { - const base::Value* args = config.FindDictKey("command-line-args"); - if (!args) - return true; - - static const base::StringPiece kAllowedArgs[] = { - blink::switches::kSharedArrayBufferAllowedOrigins, - blink::switches::kGpuRasterizationMSAASampleCount, - blink::switches::kMinHeightForGpuRasterTile, - cc::switches::kEnableClippedImageScaling, - cc::switches::kEnableGpuBenchmarking, - embedder_support::kOriginTrialPublicKey, - embedder_support::kOriginTrialDisabledFeatures, - embedder_support::kOriginTrialDisabledTokens, - switches::kDisableFeatures, - switches::kDisableGpuWatchdog, - switches::kDisableMipmapGeneration, - // TODO(crbug.com/1082821): Remove this switch from the allow-list. - switches::kEnableCastStreamingReceiver, - switches::kEnableFeatures, - switches::kEnableLowEndDeviceMode, - switches::kForceDeviceScaleFactor, - switches::kForceGpuMemAvailableMb, - switches::kForceGpuMemDiscardableLimitMb, - switches::kForceMaxTextureSize, - switches::kGoogleApiKey, - switches::kMaxDecodedImageSizeMb, - switches::kOzonePlatform, - switches::kRendererProcessLimit, - switches::kUseCmdDecoder, - switches::kV, - switches::kVModule, - switches::kVulkanHeapMemoryLimitMb, - switches::kVulkanSyncCpuMemoryLimitMb, - switches::kWebglAntialiasingMode, - switches::kWebglMSAASampleCount, - }; - - for (const auto arg : args->DictItems()) { - if (!base::Contains(kAllowedArgs, arg.first)) { - // TODO(https://crbug.com/1032439): Increase severity and return false - // once we have a mechanism for soft transitions of supported arguments. - LOG(WARNING) << "Unknown command-line arg: '" << arg.first - << "'. Config file and WebEngine version may not match."; - continue; - } - - DCHECK(!command_line->HasSwitch(arg.first)); - if (arg.second.is_none()) { - command_line->AppendSwitch(arg.first); - } else if (arg.second.is_string()) { - command_line->AppendSwitchNative(arg.first, arg.second.GetString()); - } else { - LOG(ERROR) << "Config command-line arg must be a string: " << arg.first; - return false; - } - - // TODO(https://crbug.com/1023012): enable-low-end-device-mode currently - // fakes 512MB total physical memory, which triggers RGB4444 textures, - // which - // we don't yet support. - if (arg.first == switches::kEnableLowEndDeviceMode) - command_line->AppendSwitch(blink::switches::kDisableRGBA4444Textures); - } - - return true; -} - // Returns true if DRM is supported in current configuration. Currently we // assume that it is supported on ARM64, but not on x64. // @@ -570,20 +491,6 @@ : kWebInstanceComponentUrl; launch_info.flat_namespace = fuchsia::sys::FlatNamespace::New(); - // Process command-line settings specified in our package config-data. - base::Value web_engine_config; - if (config_for_test_.is_none()) { - const absl::optional<base::Value>& config = - fuchsia_component_support::LoadPackageConfig(); - web_engine_config = - config ? config->Clone() : base::Value(base::Value::Type::DICTIONARY); - } else { - web_engine_config = std::move(config_for_test_); - } - if (!MaybeAddCommandLineArgsFromConfig(web_engine_config, &launch_args)) { - return ZX_ERR_INTERNAL; - } - fuchsia::web::ContextFeatureFlags features = {}; if (params.has_features()) features = params.features(); @@ -648,41 +555,6 @@ enable_widevine = false; } - bool allow_protected_graphics = - web_engine_config.FindBoolPath("allow-protected-graphics") - .value_or(false); - bool force_protected_graphics = - web_engine_config.FindBoolPath("force-protected-graphics") - .value_or(false); - bool enable_protected_graphics = - ((enable_playready || enable_widevine) && allow_protected_graphics) || - force_protected_graphics; - bool use_overlays_for_video = - web_engine_config.FindBoolPath("use-overlays-for-video").value_or(false); - - if (enable_protected_graphics) { - launch_args.AppendSwitch(switches::kEnableVulkanProtectedMemory); - launch_args.AppendSwitch(switches::kEnableProtectedVideoBuffers); - bool force_protected_video_buffers = - web_engine_config.FindBoolPath("force-protected-video-buffers") - .value_or(false); - if (force_protected_video_buffers) { - launch_args.AppendSwitch(switches::kForceProtectedVideoOutputBuffers); - } - } - - if (use_overlays_for_video) { - // Overlays are only available if OutputPresenterFuchsia is in use. - AppendToSwitch(switches::kEnableFeatures, - features::kUseSkiaOutputDeviceBufferQueue.name, - &launch_args); - AppendToSwitch(switches::kEnableFeatures, - features::kUseRealBuffersForPageFlipTest.name, &launch_args); - launch_args.AppendSwitchASCII(switches::kEnableHardwareOverlays, - "underlay"); - launch_args.AppendSwitch(switches::kUseOverlaysForVideo); - } - if (enable_vulkan) { if (is_headless) { DLOG(ERROR) << "VULKAN and HEADLESS features cannot be used together."; @@ -690,6 +562,7 @@ } VLOG(1) << "Enabling Vulkan GPU acceleration."; + // Vulkan requires use of SkiaRenderer, configured to a use Vulkan context. launch_args.AppendSwitch(switches::kUseVulkan); AppendToSwitch(switches::kEnableFeatures, features::kVulkan.name,
diff --git a/gin/v8_platform.cc b/gin/v8_platform.cc index 1a41a28..03cbb53 100644 --- a/gin/v8_platform.cc +++ b/gin/v8_platform.cc
@@ -395,7 +395,7 @@ int V8Platform::NumberOfWorkerThreads() { // V8Platform assumes the scheduler uses the same set of workers for default // and user blocking tasks. - const int num_foreground_workers = + const size_t num_foreground_workers = base::ThreadPoolInstance::Get() ->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( kDefaultTaskTraits); @@ -403,7 +403,7 @@ base::ThreadPoolInstance::Get() ->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( kBlockingTaskTraits)); - return std::max(1, num_foreground_workers); + return std::max(1, static_cast<int>(num_foreground_workers)); } void V8Platform::CallOnWorkerThread(std::unique_ptr<v8::Task> task) {
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 899b8be..9108af1 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -103,7 +103,7 @@ } void ActivateContents(content::WebContents* contents) override { - contents->GetMainFrame()->GetRenderViewHost()->GetWidget()->Focus(); + contents->GetPrimaryMainFrame()->GetRenderViewHost()->GetWidget()->Focus(); } void CloseContents(content::WebContents* source) override { @@ -306,7 +306,7 @@ HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents.get()), browser_context_(browser_context), - render_process_host_(web_contents->GetMainFrame()->GetProcess()), + render_process_host_(web_contents->GetPrimaryMainFrame()->GetProcess()), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(std::move(web_contents)), agent_host_( @@ -355,7 +355,7 @@ } void HeadlessWebContentsImpl::RenderViewReady() { - DCHECK(web_contents()->GetMainFrame()->IsRenderFrameLive()); + DCHECK(web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()); if (devtools_target_ready_notification_sent_) return; @@ -367,21 +367,24 @@ } int HeadlessWebContentsImpl::GetMainFrameRenderProcessId() const { - if (!web_contents() || !web_contents()->GetMainFrame()) + if (!web_contents() || !web_contents()->GetPrimaryMainFrame()) return -1; - return web_contents()->GetMainFrame()->GetProcess()->GetID(); + return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } int HeadlessWebContentsImpl::GetMainFrameTreeNodeId() const { - if (!web_contents() || !web_contents()->GetMainFrame()) + if (!web_contents() || !web_contents()->GetPrimaryMainFrame()) return -1; - return web_contents()->GetMainFrame()->GetFrameTreeNodeId(); + return web_contents()->GetPrimaryMainFrame()->GetFrameTreeNodeId(); } std::string HeadlessWebContentsImpl::GetMainFrameDevToolsId() const { - if (!web_contents() || !web_contents()->GetMainFrame()) + if (!web_contents() || !web_contents()->GetPrimaryMainFrame()) return ""; - return web_contents()->GetMainFrame()->GetDevToolsFrameToken().ToString(); + return web_contents() + ->GetPrimaryMainFrame() + ->GetDevToolsFrameToken() + .ToString(); } bool HeadlessWebContentsImpl::OpenURL(const GURL& url) { @@ -442,7 +445,8 @@ } HeadlessDevToolsTarget* HeadlessWebContentsImpl::GetDevToolsTarget() { - return web_contents()->GetMainFrame()->IsRenderFrameLive() ? this : nullptr; + return web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive() ? this + : nullptr; } std::unique_ptr<HeadlessDevToolsChannel>
diff --git a/headless/lib/browser/protocol/page_handler.cc b/headless/lib/browser/protocol/page_handler.cc index 8b818021..4f601ce 100644 --- a/headless/lib/browser/protocol/page_handler.cc +++ b/headless/lib/browser/protocol/page_handler.cc
@@ -64,7 +64,7 @@ absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( - web_contents_->GetMainFrame()->GetLastCommittedURL(), + web_contents_->GetPrimaryMainFrame()->GetLastCommittedURL(), OptionalFromMaybe<bool>(landscape), OptionalFromMaybe<bool>(display_header_footer), OptionalFromMaybe<bool>(print_background), @@ -91,7 +91,7 @@ Page::PrintToPDF::TransferModeEnum::ReturnAsStream; print_to_pdf::PdfPrintManager::FromWebContents(web_contents_.get()) ->PrintToPdf( - web_contents_->GetMainFrame(), page_ranges.fromMaybe(""), + web_contents_->GetPrimaryMainFrame(), page_ranges.fromMaybe(""), std::move(absl::get<printing::mojom::PrintPagesParamsPtr>( print_pages_params)), base::BindOnce(&PageHandler::PDFCreated, weak_factory_.GetWeakPtr(),
diff --git a/infra/config/generated/builders/ci/ios16-sdk-simulator/properties.json b/infra/config/generated/builders/ci/ios16-sdk-simulator/properties.json index 1e7df42..952e623 100644 --- a/infra/config/generated/builders/ci/ios16-sdk-simulator/properties.json +++ b/infra/config/generated/builders/ci/ios16-sdk-simulator/properties.json
@@ -59,5 +59,5 @@ }, "builder_group": "chromium.fyi", "recipe": "chromium", - "xcode_build_version": "13c100" + "xcode_build_version": "14a5228q" } \ No newline at end of file
diff --git a/infra/config/generated/builders/try/ios16-sdk-simulator/properties.json b/infra/config/generated/builders/try/ios16-sdk-simulator/properties.json index 25ca46bb..13bf18ae 100644 --- a/infra/config/generated/builders/try/ios16-sdk-simulator/properties.json +++ b/infra/config/generated/builders/try/ios16-sdk-simulator/properties.json
@@ -53,5 +53,5 @@ }, "builder_group": "tryserver.chromium.mac", "recipe": "chromium_trybot", - "xcode_build_version": "13c100" + "xcode_build_version": "14a5228q" } \ No newline at end of file
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 60f0795..95ec790 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -31103,8 +31103,8 @@ '}' execution_timeout_secs: 36000 caches { - name: "xcode_ios_13c100" - path: "xcode_ios_13c100.app" + name: "xcode_ios_14a5228q" + path: "xcode_ios_14a5228q.app" } build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" @@ -61484,8 +61484,8 @@ path: "win_toolchain" } caches { - name: "xcode_ios_13c100" - path: "xcode_ios_13c100.app" + name: "xcode_ios_14a5228q" + path: "xcode_ios_14a5228q.app" } build_numbers: YES service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com"
diff --git a/infra/config/lib/builders.star b/infra/config/lib/builders.star index 197cc76..96f600c 100644 --- a/infra/config/lib/builders.star +++ b/infra/config/lib/builders.star
@@ -167,8 +167,10 @@ x12e262 = xcode_enum("12e262"), # Default Xcode 13 for chromium iOS. x13main = xcode_enum("13c100"), - # A newer Xcode version used on beta bots. + # A newer Xcode 13 version used on beta bots. x13betabots = xcode_enum("13f17a"), + # A newer Xcode 14 version used on beta bots. + x14betabots = xcode_enum("14a5228q"), # in use by ios-webkit-tot x13wk = xcode_enum("13a1030dwk"), )
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index 8ef5118..f89e3c0 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -1503,6 +1503,7 @@ os = os.MAC_DEFAULT, schedule = "0 2,6,10,14,18,22 * * *", triggered_by = [], + xcode = xcode.x14betabots, ) ci.builder(
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star index 3a08700..c3600688 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star
@@ -384,6 +384,7 @@ mirrors = [ "ci/ios16-sdk-simulator", ], + xcode = xcode.x14betabots, ) try_.gpu.optional_tests_builder(
diff --git a/ios/chrome/browser/DEPS b/ios/chrome/browser/DEPS index e9e381f..110f116 100644 --- a/ios/chrome/browser/DEPS +++ b/ios/chrome/browser/DEPS
@@ -115,6 +115,8 @@ "+components/update_client", "+components/upload_list", "+components/url_formatter", + "+components/url_param_filter/core", + "+components/url_param_filter/ios", "+components/variations", "+components/variations/net", "+components/version_info",
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm index a5a97cf1..e02aaa4 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm
@@ -353,7 +353,10 @@ : self.discoverFeedWrapperViewController; // Configures the feed header in the view hierarchy if it is visible. if (self.feedHeaderViewController) { - self.feedHeaderViewController.view.layer.zPosition = FLT_MAX; + // Ensure that sticky header is not covered by omnibox. + if ([self.ntpContentDelegate isContentHeaderSticky]) { + self.feedHeaderViewController.view.layer.zPosition = FLT_MAX; + } [self addViewController:self.feedHeaderViewController toParentViewController:parentViewController]; }
diff --git a/ios/chrome/browser/web_state_list/BUILD.gn b/ios/chrome/browser/web_state_list/BUILD.gn index 9220b1c6..3762c8a 100644 --- a/ios/chrome/browser/web_state_list/BUILD.gn +++ b/ios/chrome/browser/web_state_list/BUILD.gn
@@ -73,6 +73,8 @@ "//base", "//components/navigation_metrics", "//components/profile_metrics", + "//components/url_param_filter/core", + "//components/url_param_filter/ios", "//ios/chrome/browser:chrome_url_constants", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/browser_state_metrics",
diff --git a/ios/chrome/browser/web_state_list/tab_insertion_browser_agent.mm b/ios/chrome/browser/web_state_list/tab_insertion_browser_agent.mm index 4912268..a7b6c614 100644 --- a/ios/chrome/browser/web_state_list/tab_insertion_browser_agent.mm +++ b/ios/chrome/browser/web_state_list/tab_insertion_browser_agent.mm
@@ -4,6 +4,8 @@ #import "ios/chrome/browser/web_state_list/tab_insertion_browser_agent.h" +#import "components/url_param_filter/core/features.h" +#import "components/url_param_filter/ios/cross_otr_tab_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/ntp/new_tab_page_tab_helper.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" @@ -63,6 +65,15 @@ NewTabPageTabHelper::FromWebState(web_state.get()) ->SetShowStartSurface(true); } + + if (base::FeatureList::IsEnabled( + url_param_filter::features::kIncognitoParamFilterEnabled) && + web_state->GetBrowserState()->IsOffTheRecord() && !parent) { + // Only attach the CrossOtrTabHelper to OTR web_state if parent is null, + // as this indicates that it's the result of a "Open In Incognito" press. + url_param_filter::CrossOtrTabHelper::CreateForWebState(web_state.get()); + } + web_state->GetNavigationManager()->LoadURLWithParams(params); int inserted_index =
diff --git a/ios/web/init/ios_global_state.mm b/ios/web/init/ios_global_state.mm index 66f36e41..1904149 100644 --- a/ios/web/init/ios_global_state.mm +++ b/ios/web/init/ios_global_state.mm
@@ -72,10 +72,10 @@ void StartThreadPool() { static dispatch_once_t once_token; dispatch_once(&once_token, ^{ - constexpr int kMinForegroundThreads = 6; - constexpr int kMaxForegroundThreads = 16; + constexpr size_t kMinForegroundThreads = 6; + constexpr size_t kMaxForegroundThreads = 16; constexpr double kCoreMultiplierForegroundThreads = 0.6; - constexpr int kOffsetForegroundThreads = 0; + constexpr size_t kOffsetForegroundThreads = 0; base::ThreadPoolInstance::Get()->Start( {base::RecommendedMaxNumberOfThreadsInThreadGroup( kMinForegroundThreads, kMaxForegroundThreads,
diff --git a/media/gpu/android/media_codec_video_decoder.cc b/media/gpu/android/media_codec_video_decoder.cc index 8a54ce2..94215b3 100644 --- a/media/gpu/android/media_codec_video_decoder.cc +++ b/media/gpu/android/media_codec_video_decoder.cc
@@ -417,6 +417,9 @@ // sure, request a deferred flush. deferred_flush_pending_ = true; deferred_reallocation_pending_ = true; + // Since this will re-use the same surface, allow a retry to work around a + // race condition in the android framework. + should_retry_codec_allocation_ = true; last_width_ = width; } // else leave |last_width_| unmodified, since we're re-using the codec. } @@ -707,6 +710,21 @@ std::unique_ptr<MediaCodecBridge> codec) { DCHECK(!codec_); DCHECK_EQ(state_, State::kRunning); + bool should_retry_codec_allocation = should_retry_codec_allocation_; + should_retry_codec_allocation_ = false; + + // In rare cases, the framework can fail transiently when trying to re-use a + // surface. If we're in one of those cases, then retry codec allocation. + // This only happens on R and S, so skip it otherwise. + if (!codec && should_retry_codec_allocation && + device_info_->SdkVersion() >= base::android::SDK_VERSION_R && + device_info_->SdkVersion() <= 32 /* SDK_VERSION_S_V2 */ + ) { + // We might want to post this with a short delay, but there is already quite + // a lot of overhead in codec allocation. + CreateCodec(); + return; + } if (!codec) { EnterTerminalState(State::kError, "Unable to allocate codec"); @@ -778,6 +796,8 @@ if (deferred_reallocation_pending_) { deferred_reallocation_pending_ = false; ReleaseCodec(); + // Re-initializing the codec with the same surface may need to retry. + should_retry_codec_allocation_ = !SurfaceTransitionPending(); CreateCodec(); }
diff --git a/media/gpu/android/media_codec_video_decoder.h b/media/gpu/android/media_codec_video_decoder.h index 66394c1..c8277943 100644 --- a/media/gpu/android/media_codec_video_decoder.h +++ b/media/gpu/android/media_codec_video_decoder.h
@@ -353,6 +353,10 @@ // See https://crbug.com/1081346 . bool allow_nonsecure_overlays_ = true; + // If set, then the next call to `CodecConfig()` will be allowed to retry if + // it fails to get a codec. This is to work around b/191966399. + bool should_retry_codec_allocation_ = false; + base::WeakPtrFactory<MediaCodecVideoDecoder> weak_factory_{this}; base::WeakPtrFactory<MediaCodecVideoDecoder> codec_allocator_weak_factory_{ this};
diff --git a/net/disk_cache/README.md b/net/disk_cache/README.md index c2a4ac7..fd30387 100644 --- a/net/disk_cache/README.md +++ b/net/disk_cache/README.md
@@ -47,7 +47,7 @@ ### [disk_cache/blockfile directory](/net/disk_cache/blockfile/) -This implementation backs the HTTP cache on Windows and OS X. It tries to pack +This implementation backs the HTTP cache on Windows. It tries to pack many small entries caches typically have into "block" files, which can help performance but introduces a lot of complexity and makes recovery from corruption very tricky. @@ -59,9 +59,9 @@ ### [disk_cache/simple directory](/net/disk_cache/simple/) -This implementation backs the HTTP cache on Android, ChromeOS, and Linux, and -is used to implement some features like CacheStorage on all platforms. The -design is centered around roughly having a single file per cache entry (more +This implementation backs the HTTP cache on Android, ChromeOS, and Linux, +macOS and is used to implement some features like CacheStorage on all platforms. +The design is centered around roughly having a single file per cache entry (more precisely for streams 0 and 1), with a compact and simple in-memory index for membership tests, which makes it very robust against failures, but also highly sensitive to OS file system performance.
diff --git a/pdf/pdf_accessibility_data_handler.h b/pdf/pdf_accessibility_data_handler.h index 29bda105..85fcd845 100644 --- a/pdf/pdf_accessibility_data_handler.h +++ b/pdf/pdf_accessibility_data_handler.h
@@ -21,14 +21,13 @@ virtual ~PdfAccessibilityDataHandler() = default; virtual void SetAccessibilityViewportInfo( - const AccessibilityViewportInfo& viewport_info) = 0; - virtual void SetAccessibilityDocInfo( - const AccessibilityDocInfo& doc_info) = 0; + AccessibilityViewportInfo viewport_info) = 0; + virtual void SetAccessibilityDocInfo(AccessibilityDocInfo doc_info) = 0; virtual void SetAccessibilityPageInfo( - const AccessibilityPageInfo& page_info, - const std::vector<AccessibilityTextRunInfo>& text_runs, - const std::vector<AccessibilityCharInfo>& chars, - const AccessibilityPageObjects& page_objects) = 0; + AccessibilityPageInfo page_info, + std::vector<AccessibilityTextRunInfo> text_runs, + std::vector<AccessibilityCharInfo> chars, + AccessibilityPageObjects page_objects) = 0; }; } // namespace chrome_pdf
diff --git a/pdf/pdf_view_web_plugin.cc b/pdf/pdf_view_web_plugin.cc index c1ec327..91b6e61d 100644 --- a/pdf/pdf_view_web_plugin.cc +++ b/pdf/pdf_view_web_plugin.cc
@@ -996,10 +996,7 @@ } void PdfViewWebPlugin::SetAccessibilityDocInfo(AccessibilityDocInfo doc_info) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&PdfViewWebPlugin::OnSetAccessibilityDocInfo, - weak_factory_.GetWeakPtr(), std::move(doc_info))); + pdf_accessibility_data_handler_->SetAccessibilityDocInfo(std::move(doc_info)); } void PdfViewWebPlugin::SetAccessibilityPageInfo( @@ -1007,19 +1004,15 @@ std::vector<AccessibilityTextRunInfo> text_runs, std::vector<AccessibilityCharInfo> chars, AccessibilityPageObjects page_objects) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&PdfViewWebPlugin::OnSetAccessibilityPageInfo, - weak_factory_.GetWeakPtr(), - std::move(page_info), std::move(text_runs), - std::move(chars), std::move(page_objects))); + pdf_accessibility_data_handler_->SetAccessibilityPageInfo( + std::move(page_info), std::move(text_runs), std::move(chars), + std::move(page_objects)); } void PdfViewWebPlugin::SetAccessibilityViewportInfo( AccessibilityViewportInfo viewport_info) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&PdfViewWebPlugin::OnSetAccessibilityViewportInfo, - weak_factory_.GetWeakPtr(), std::move(viewport_info))); + pdf_accessibility_data_handler_->SetAccessibilityViewportInfo( + std::move(viewport_info)); } void PdfViewWebPlugin::SetContentRestrictions(int content_restrictions) { @@ -1144,34 +1137,6 @@ client_->Print(); } -void PdfViewWebPlugin::OnSetAccessibilityDocInfo( - AccessibilityDocInfo doc_info) { - if (!pdf_accessibility_data_handler_) - return; - pdf_accessibility_data_handler_->SetAccessibilityDocInfo(doc_info); - // `this` may be deleted. Don't do anything else. -} - -void PdfViewWebPlugin::OnSetAccessibilityPageInfo( - AccessibilityPageInfo page_info, - std::vector<AccessibilityTextRunInfo> text_runs, - std::vector<AccessibilityCharInfo> chars, - AccessibilityPageObjects page_objects) { - if (!pdf_accessibility_data_handler_) - return; - pdf_accessibility_data_handler_->SetAccessibilityPageInfo( - page_info, text_runs, chars, page_objects); - // `this` may be deleted. Don't do anything else. -} - -void PdfViewWebPlugin::OnSetAccessibilityViewportInfo( - AccessibilityViewportInfo viewport_info) { - if (!pdf_accessibility_data_handler_) - return; - pdf_accessibility_data_handler_->SetAccessibilityViewportInfo(viewport_info); - // `this` may be deleted. Don't do anything else. -} - void PdfViewWebPlugin::ResetRecentlySentFindUpdate() { recently_sent_find_update_ = false; }
diff --git a/pdf/pdf_view_web_plugin.h b/pdf/pdf_view_web_plugin.h index aae60a25..abfe399e 100644 --- a/pdf/pdf_view_web_plugin.h +++ b/pdf/pdf_view_web_plugin.h
@@ -396,22 +396,6 @@ // the plugin are moved off the main thread. void OnInvokePrintDialog(); - // Callback to set the document information in the accessibility tree - // asynchronously. - void OnSetAccessibilityDocInfo(AccessibilityDocInfo doc_info); - - // Callback to set the page information in the accessibility tree - // asynchronously. - void OnSetAccessibilityPageInfo( - AccessibilityPageInfo page_info, - std::vector<AccessibilityTextRunInfo> text_runs, - std::vector<AccessibilityCharInfo> chars, - AccessibilityPageObjects page_objects); - - // Callback to set the viewport information in the accessibility tree - // asynchronously. - void OnSetAccessibilityViewportInfo(AccessibilityViewportInfo viewport_info); - void ResetRecentlySentFindUpdate(); // Records metrics about the document metadata. @@ -485,7 +469,7 @@ // Used for submitting forms. std::unique_ptr<UrlLoader> form_loader_; - // May be null in unit tests. + // Handler for accessibility data updates. std::unique_ptr<PdfAccessibilityDataHandler> const pdf_accessibility_data_handler_;
diff --git a/pdf/pdf_view_web_plugin_unittest.cc b/pdf/pdf_view_web_plugin_unittest.cc index e3a4283..6775ab7 100644 --- a/pdf/pdf_view_web_plugin_unittest.cc +++ b/pdf/pdf_view_web_plugin_unittest.cc
@@ -30,6 +30,7 @@ #include "pdf/content_restriction.h" #include "pdf/mojom/pdf.mojom.h" #include "pdf/paint_ready_rect.h" +#include "pdf/pdf_accessibility_data_handler.h" #include "pdf/pdf_view_plugin_base.h" #include "pdf/test/test_helpers.h" #include "pdf/test/test_pdfium_engine.h" @@ -200,6 +201,26 @@ (override)); }; +class MockPdfAccessibilityDataHandler : public PdfAccessibilityDataHandler { + public: + // PdfAccessibilityDataHandler: + MOCK_METHOD(void, + SetAccessibilityViewportInfo, + (AccessibilityViewportInfo), + (override)); + MOCK_METHOD(void, + SetAccessibilityDocInfo, + (AccessibilityDocInfo), + (override)); + MOCK_METHOD(void, + SetAccessibilityPageInfo, + (AccessibilityPageInfo, + std::vector<AccessibilityTextRunInfo>, + std::vector<AccessibilityCharInfo>, + AccessibilityPageObjects), + (override)); +}; + class FakePdfViewWebPluginClient : public PdfViewWebPlugin::Client { public: FakePdfViewWebPluginClient() { @@ -298,6 +319,11 @@ MOCK_METHOD(void, DidStopLoading, (), (override)); MOCK_METHOD(void, RecordComputedAction, (const std::string&), (override)); + + MOCK_METHOD(std::unique_ptr<PdfAccessibilityDataHandler>, + CreateAccessibilityDataHandler, + (PdfAccessibilityActionHandler*), + (override)); }; class FakePdfService : public pdf::mojom::PdfService { @@ -356,6 +382,13 @@ engine_ptr_ = engine.get(); return engine; }); + ON_CALL(*client_ptr_, CreateAccessibilityDataHandler) + .WillByDefault([this]() { + auto handler = + std::make_unique<NiceMock<MockPdfAccessibilityDataHandler>>(); + accessibility_data_handler_ptr_ = handler.get(); + return handler; + }); SetUpClient(); plugin_ = @@ -398,6 +431,7 @@ raw_ptr<FakePdfViewWebPluginClient> client_ptr_; std::unique_ptr<PdfViewWebPlugin, PluginDeleter> plugin_; raw_ptr<TestPDFiumEngine> engine_ptr_; + raw_ptr<MockPdfAccessibilityDataHandler> accessibility_data_handler_ptr_; }; class PdfViewWebPluginTest : public PdfViewWebPluginWithoutInitializeTest { @@ -617,6 +651,8 @@ "type": "printPreviewLoaded", })"))) .Times(0); + EXPECT_CALL(*accessibility_data_handler_ptr_, SetAccessibilityDocInfo) + .Times(0); EXPECT_CALL(*client_ptr_, DidStopLoading).Times(0); EXPECT_CALL(pdf_service_, UpdateContentRestrictions).Times(0); plugin_->DocumentLoadComplete(); @@ -644,6 +680,8 @@ "type": "printPreviewLoaded", })"))) .Times(0); + EXPECT_CALL(*accessibility_data_handler_ptr_, SetAccessibilityDocInfo) + .Times(0); EXPECT_CALL(*client_ptr_, DidStopLoading); EXPECT_CALL(pdf_service_, UpdateContentRestrictions(kContentRestrictionPrint | kContentRestrictionPaste | @@ -1717,6 +1755,8 @@ EXPECT_CALL(*client_ptr_, PostMessage(base::test::IsJson(R"({ "type": "printPreviewLoaded", })"))); + EXPECT_CALL(*accessibility_data_handler_ptr_, SetAccessibilityDocInfo) + .Times(0); EXPECT_CALL(*client_ptr_, DidStopLoading).Times(0); EXPECT_CALL(pdf_service_, UpdateContentRestrictions).Times(0); plugin_->DocumentLoadComplete();
diff --git a/ppapi/shared_impl/file_type_conversion.cc b/ppapi/shared_impl/file_type_conversion.cc index 4ca4618..b76c10ce 100644 --- a/ppapi/shared_impl/file_type_conversion.cc +++ b/ppapi/shared_impl/file_type_conversion.cc
@@ -36,7 +36,7 @@ } bool PepperFileOpenFlagsToPlatformFileFlags(int32_t pp_open_flags, - int* flags_out) { + uint32_t* flags_out) { bool pp_read = !!(pp_open_flags & PP_FILEOPENFLAG_READ); bool pp_write = !!(pp_open_flags & PP_FILEOPENFLAG_WRITE); bool pp_create = !!(pp_open_flags & PP_FILEOPENFLAG_CREATE); @@ -45,7 +45,7 @@ bool pp_append = !!(pp_open_flags & PP_FILEOPENFLAG_APPEND); // Pepper allows Touch on any open file, so always set this Windows-only flag. - int flags = base::File::FLAG_WRITE_ATTRIBUTES; + uint32_t flags = base::File::FLAG_WRITE_ATTRIBUTES; if (pp_read) flags |= base::File::FLAG_READ;
diff --git a/ppapi/shared_impl/file_type_conversion.h b/ppapi/shared_impl/file_type_conversion.h index d49831a9..a628f493 100644 --- a/ppapi/shared_impl/file_type_conversion.h +++ b/ppapi/shared_impl/file_type_conversion.h
@@ -20,7 +20,7 @@ // Returns |true| if okay. PPAPI_SHARED_EXPORT bool PepperFileOpenFlagsToPlatformFileFlags( int32_t pp_open_flags, - int* flags_out); + uint32_t* flags_out); PPAPI_SHARED_EXPORT void FileInfoToPepperFileInfo(const base::File::Info& info, PP_FileSystemType fs_type,
diff --git a/sandbox/policy/mac/common.sb b/sandbox/policy/mac/common.sb index 1c531988..3cf7b61 100644 --- a/sandbox/policy/mac/common.sb +++ b/sandbox/policy/mac/common.sb
@@ -233,6 +233,7 @@ (sysctl-name "hw.physicalcpu_max") (sysctl-name "hw.tbfrequency_compat") (sysctl-name "hw.vectorunit") + (sysctl-name "kern.bootargs") ; Temporary for https://crbug.com/1291789. (sysctl-name "kern.hostname") (sysctl-name "kern.maxfilesperproc") (sysctl-name "kern.osproductversion")
diff --git a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc index db1f90f..ea12da0e 100644 --- a/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc +++ b/services/viz/public/cpp/compositing/transferable_resource_mojom_traits.cc
@@ -25,8 +25,6 @@ return viz::mojom::SynchronizationType::kSyncToken; case viz::TransferableResource::SynchronizationType::kGpuCommandsCompleted: return viz::mojom::SynchronizationType::kGpuCommandsCompleted; - case viz::TransferableResource::SynchronizationType::kReleaseFence: - return viz::mojom::SynchronizationType::kReleaseFence; } NOTREACHED(); return viz::mojom::SynchronizationType::kSyncToken; @@ -45,9 +43,6 @@ *out = viz::TransferableResource::SynchronizationType::kGpuCommandsCompleted; return true; - case viz::mojom::SynchronizationType::kReleaseFence: - *out = viz::TransferableResource::SynchronizationType::kReleaseFence; - return true; } return false; }
diff --git a/services/viz/public/mojom/compositing/transferable_resource.mojom b/services/viz/public/mojom/compositing/transferable_resource.mojom index e169be2..b4c970b08 100644 --- a/services/viz/public/mojom/compositing/transferable_resource.mojom +++ b/services/viz/public/mojom/compositing/transferable_resource.mojom
@@ -18,7 +18,6 @@ enum SynchronizationType { kSyncToken, kGpuCommandsCompleted, - kReleaseFence, }; // See components/viz/common/resources/transferable_resource.h.
diff --git a/storage/browser/file_system/async_file_util.h b/storage/browser/file_system/async_file_util.h index 7c6a896..5c8a5e5 100644 --- a/storage/browser/file_system/async_file_util.h +++ b/storage/browser/file_system/async_file_util.h
@@ -101,7 +101,7 @@ // virtual void CreateOrOpen(std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) = 0; // Ensures that the given |url| exist. This creates a empty new file
diff --git a/storage/browser/file_system/async_file_util_adapter.cc b/storage/browser/file_system/async_file_util_adapter.cc index a6e33ab..f9ad0bd8 100644 --- a/storage/browser/file_system/async_file_util_adapter.cc +++ b/storage/browser/file_system/async_file_util_adapter.cc
@@ -177,7 +177,7 @@ void AsyncFileUtilAdapter::CreateOrOpen( std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) { FileSystemOperationContext* context_ptr = context.release(); base::PostTaskAndReplyWithResult(
diff --git a/storage/browser/file_system/async_file_util_adapter.h b/storage/browser/file_system/async_file_util_adapter.h index bb9cb2e..7102993 100644 --- a/storage/browser/file_system/async_file_util_adapter.h +++ b/storage/browser/file_system/async_file_util_adapter.h
@@ -43,7 +43,7 @@ // AsyncFileUtil overrides. void CreateOrOpen(std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url, - int file_flags, + uint32_t file_flags, CreateOrOpenCallback callback) override; void EnsureFileExists(std::unique_ptr<FileSystemOperationContext> context, const FileSystemURL& url,
diff --git a/storage/browser/file_system/file_system_operation.h b/storage/browser/file_system/file_system_operation.h index c3faa335..984e75d3 100644 --- a/storage/browser/file_system/file_system_operation.h +++ b/storage/browser/file_system/file_system_operation.h
@@ -347,7 +347,7 @@ // // This function is used only by Pepper as of writing. virtual void OpenFile(const FileSystemURL& path, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) = 0; // Creates a local snapshot file for a given |path| and returns the
diff --git a/storage/browser/file_system/file_system_operation_impl.cc b/storage/browser/file_system/file_system_operation_impl.cc index 1c42e058..64d8367 100644 --- a/storage/browser/file_system/file_system_operation_impl.cc +++ b/storage/browser/file_system/file_system_operation_impl.cc
@@ -250,7 +250,7 @@ } void FileSystemOperationImpl::OpenFile(const FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) { DCHECK(SetPendingOperationType(kOperationOpenFile)); @@ -515,7 +515,7 @@ void FileSystemOperationImpl::DoOpenFile(const FileSystemURL& url, OpenFileCallback callback, - int file_flags) { + uint32_t file_flags) { async_file_util_->CreateOrOpen( std::move(operation_context_), url, file_flags, base::BindOnce(&DidOpenFile, file_system_context_, weak_ptr_,
diff --git a/storage/browser/file_system/file_system_operation_impl.h b/storage/browser/file_system/file_system_operation_impl.h index 119d598..eab03e9 100644 --- a/storage/browser/file_system/file_system_operation_impl.h +++ b/storage/browser/file_system/file_system_operation_impl.h
@@ -93,7 +93,7 @@ const base::Time& last_modified_time, StatusCallback callback) override; void OpenFile(const FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) override; void Cancel(StatusCallback cancel_callback) override; void CreateSnapshotFile(const FileSystemURL& path, @@ -166,7 +166,7 @@ int64_t length); void DoOpenFile(const FileSystemURL& url, OpenFileCallback callback, - int file_flags); + uint32_t file_flags); // Callback for CreateFile for |exclusive|=true cases. void DidEnsureFileExistsExclusive(StatusCallback callback,
diff --git a/storage/browser/file_system/file_system_operation_runner.cc b/storage/browser/file_system/file_system_operation_runner.cc index 629b346..38b569d 100644 --- a/storage/browser/file_system/file_system_operation_runner.cc +++ b/storage/browser/file_system/file_system_operation_runner.cc
@@ -383,7 +383,7 @@ } OperationID FileSystemOperationRunner::OpenFile(const FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback) { base::File::Error error = base::File::FILE_OK; std::unique_ptr<FileSystemOperation> operation =
diff --git a/storage/browser/file_system/file_system_operation_runner.h b/storage/browser/file_system/file_system_operation_runner.h index 97802e2..f07f5ea 100644 --- a/storage/browser/file_system/file_system_operation_runner.h +++ b/storage/browser/file_system/file_system_operation_runner.h
@@ -171,7 +171,7 @@ // all situation e.g. it will always fail for the sandboxed system when in // Incognito mode. OperationID OpenFile(const FileSystemURL& url, - int file_flags, + uint32_t file_flags, OpenFileCallback callback); // Creates a local snapshot file for a given |url| and returns the
diff --git a/storage/browser/file_system/native_file_util.cc b/storage/browser/file_system/native_file_util.cc index d2ea763..7def1d7 100644 --- a/storage/browser/file_system/native_file_util.cc +++ b/storage/browser/file_system/native_file_util.cc
@@ -134,7 +134,7 @@ } base::File NativeFileUtil::CreateOrOpen(const base::FilePath& path, - int file_flags) { + uint32_t file_flags) { if (!base::DirectoryExists(path.DirName())) { // If its parent does not exist, should return NOT_FOUND error. return base::File(base::File::FILE_ERROR_NOT_FOUND);
diff --git a/storage/browser/file_system/native_file_util.h b/storage/browser/file_system/native_file_util.h index a83f51e..15afaa5 100644 --- a/storage/browser/file_system/native_file_util.h +++ b/storage/browser/file_system/native_file_util.h
@@ -42,7 +42,8 @@ const FileSystemURL& dest_url, bool copy); - static base::File CreateOrOpen(const base::FilePath& path, int file_flags); + static base::File CreateOrOpen(const base::FilePath& path, + uint32_t file_flags); static base::File::Error EnsureFileExists(const base::FilePath& path, bool* created); static base::File::Error CreateDirectory(const base::FilePath& path,
diff --git a/storage/browser/file_system/obfuscated_file_util_delegate.h b/storage/browser/file_system/obfuscated_file_util_delegate.h index dd78689..be76291e 100644 --- a/storage/browser/file_system/obfuscated_file_util_delegate.h +++ b/storage/browser/file_system/obfuscated_file_util_delegate.h
@@ -35,7 +35,7 @@ const FileSystemURL& dest_url, bool copy) = 0; virtual base::File CreateOrOpen(const base::FilePath& path, - int file_flags) = 0; + uint32_t file_flags) = 0; virtual base::File::Error EnsureFileExists(const base::FilePath& path, bool* created) = 0; virtual base::File::Error CreateDirectory(const base::FilePath& path,
diff --git a/storage/browser/file_system/obfuscated_file_util_disk_delegate.cc b/storage/browser/file_system/obfuscated_file_util_disk_delegate.cc index fe225cb..6c84d1d 100644 --- a/storage/browser/file_system/obfuscated_file_util_disk_delegate.cc +++ b/storage/browser/file_system/obfuscated_file_util_disk_delegate.cc
@@ -48,7 +48,7 @@ base::File ObfuscatedFileUtilDiskDelegate::CreateOrOpen( const base::FilePath& path, - int file_flags) { + uint32_t file_flags) { return NativeFileUtil::CreateOrOpen(path, file_flags); }
diff --git a/storage/browser/file_system/obfuscated_file_util_disk_delegate.h b/storage/browser/file_system/obfuscated_file_util_disk_delegate.h index afd3be78..61c5439 100644 --- a/storage/browser/file_system/obfuscated_file_util_disk_delegate.h +++ b/storage/browser/file_system/obfuscated_file_util_disk_delegate.h
@@ -35,7 +35,8 @@ NativeFileUtil::CopyOrMoveMode CopyOrMoveModeForDestination( const FileSystemURL& dest_url, bool copy) override; - base::File CreateOrOpen(const base::FilePath& path, int file_flags) override; + base::File CreateOrOpen(const base::FilePath& path, + uint32_t file_flags) override; base::File::Error EnsureFileExists(const base::FilePath& path, bool* created) override; base::File::Error CreateDirectory(const base::FilePath& path,
diff --git a/storage/browser/file_system/obfuscated_file_util_memory_delegate.cc b/storage/browser/file_system/obfuscated_file_util_memory_delegate.cc index a2367972..326e9d85d 100644 --- a/storage/browser/file_system/obfuscated_file_util_memory_delegate.cc +++ b/storage/browser/file_system/obfuscated_file_util_memory_delegate.cc
@@ -234,7 +234,7 @@ base::File ObfuscatedFileUtilMemoryDelegate::CreateOrOpen( const base::FilePath& path, - int file_flags) { + uint32_t file_flags) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO:(https://crbug.com/936722): Once the output of this function is // changed to base::File::Error, it can use CreateOrOpenInternal to perform @@ -244,7 +244,7 @@ void ObfuscatedFileUtilMemoryDelegate::CreateOrOpenInternal( const DecomposedPath& dp, - int file_flags) { + uint32_t file_flags) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!dp.entry) { dp.parent->directory_content.emplace(dp.components.back(), Entry::kFile);
diff --git a/storage/browser/file_system/obfuscated_file_util_memory_delegate.h b/storage/browser/file_system/obfuscated_file_util_memory_delegate.h index 0a0119d..0abf68a3 100644 --- a/storage/browser/file_system/obfuscated_file_util_memory_delegate.h +++ b/storage/browser/file_system/obfuscated_file_util_memory_delegate.h
@@ -58,7 +58,8 @@ NativeFileUtil::CopyOrMoveMode CopyOrMoveModeForDestination( const FileSystemURL& dest_url, bool copy) override; - base::File CreateOrOpen(const base::FilePath& path, int file_flags) override; + base::File CreateOrOpen(const base::FilePath& path, + uint32_t file_flags) override; base::File::Error EnsureFileExists(const base::FilePath& path, bool* created) override; base::File::Error CreateDirectory(const base::FilePath& path, @@ -120,7 +121,7 @@ absl::optional<DecomposedPath> ParsePath(const base::FilePath& path); // Creates or opens a file specified in |dp|. - void CreateOrOpenInternal(const DecomposedPath& dp, int file_flags); + void CreateOrOpenInternal(const DecomposedPath& dp, uint32_t file_flags); // Moves a directory from |src_dp| to |dest_dp|. bool MoveDirectoryInternal(const DecomposedPath& src_dp,
diff --git a/testing/buildbot/chromium.android.fyi.json b/testing/buildbot/chromium.android.fyi.json index 838a8d1e..c8c39001 100644 --- a/testing/buildbot/chromium.android.fyi.json +++ b/testing/buildbot/chromium.android.fyi.json
@@ -7706,6 +7706,17 @@ }, { "isolate_profile_data": true, + "name": "build_junit_tests", + "resultdb": { + "enable": true, + "has_native_resultdb_integration": true + }, + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { + "isolate_profile_data": true, "name": "chrome_java_test_pagecontroller_junit_tests", "resultdb": { "enable": true, @@ -7761,17 +7772,6 @@ }, { "isolate_profile_data": true, - "name": "incremental_javac_junit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { - "isolate_profile_data": true, "name": "junit_unit_tests", "resultdb": { "enable": true,
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index ff6df44..7fe602a8 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1613,6 +1613,12 @@ "test_id_prefix": "ninja://base:base_junit_tests/" }, { + "name": "build_junit_tests", + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { "name": "chrome_java_test_pagecontroller_junit_tests", "swarming": {}, "test": "chrome_java_test_pagecontroller_junit_tests", @@ -1643,12 +1649,6 @@ "test_id_prefix": "ninja://device:device_junit_tests/" }, { - "name": "incremental_javac_junit_tests", - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { "name": "junit_unit_tests", "swarming": {}, "test": "junit_unit_tests", @@ -23491,6 +23491,16 @@ "test_id_prefix": "ninja://base:base_junit_tests/" }, { + "name": "build_junit_tests", + "resultdb": { + "enable": true, + "has_native_resultdb_integration": true + }, + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { "name": "chrome_java_test_pagecontroller_junit_tests", "resultdb": { "enable": true, @@ -23541,16 +23551,6 @@ "test_id_prefix": "ninja://device:device_junit_tests/" }, { - "name": "incremental_javac_junit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { "name": "junit_unit_tests", "resultdb": { "enable": true, @@ -31549,6 +31549,17 @@ }, { "isolate_profile_data": true, + "name": "build_junit_tests", + "resultdb": { + "enable": true, + "has_native_resultdb_integration": true + }, + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { + "isolate_profile_data": true, "name": "chrome_java_test_pagecontroller_junit_tests", "resultdb": { "enable": true, @@ -31607,17 +31618,6 @@ }, { "isolate_profile_data": true, - "name": "incremental_javac_junit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { - "isolate_profile_data": true, "name": "junit_unit_tests", "resultdb": { "enable": true,
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 2d9358b..7590d86 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -8329,6 +8329,16 @@ "test_id_prefix": "ninja://base:base_junit_tests/" }, { + "name": "build_junit_tests", + "resultdb": { + "enable": true, + "has_native_resultdb_integration": true + }, + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { "name": "chrome_java_test_pagecontroller_junit_tests", "resultdb": { "enable": true, @@ -8379,16 +8389,6 @@ "test_id_prefix": "ninja://device:device_junit_tests/" }, { - "name": "incremental_javac_junit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { "name": "junit_unit_tests", "resultdb": { "enable": true,
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index f059ca01..aee181d 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -13968,6 +13968,17 @@ }, { "isolate_profile_data": true, + "name": "build_junit_tests", + "resultdb": { + "enable": true, + "has_native_resultdb_integration": true + }, + "swarming": {}, + "test": "build_junit_tests", + "test_id_prefix": "ninja://build/android:build_junit_tests/" + }, + { + "isolate_profile_data": true, "name": "chrome_java_test_pagecontroller_junit_tests", "resultdb": { "enable": true, @@ -14023,17 +14034,6 @@ }, { "isolate_profile_data": true, - "name": "incremental_javac_junit_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": {}, - "test": "incremental_javac_junit_tests", - "test_id_prefix": "ninja://build/android/test:incremental_javac_junit_tests/" - }, - { - "isolate_profile_data": true, "name": "junit_unit_tests", "resultdb": { "enable": true, @@ -69428,7 +69428,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69480,7 +69480,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69532,7 +69532,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69584,7 +69584,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69636,7 +69636,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69688,7 +69688,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69740,7 +69740,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69792,7 +69792,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69844,7 +69844,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69896,7 +69896,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -69948,7 +69948,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70000,7 +70000,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70052,7 +70052,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70104,7 +70104,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70156,7 +70156,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70209,7 +70209,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70262,7 +70262,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70315,7 +70315,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70368,7 +70368,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70421,7 +70421,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70475,7 +70475,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70529,7 +70529,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70583,7 +70583,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70637,7 +70637,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70691,7 +70691,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70745,7 +70745,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70799,7 +70799,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70853,7 +70853,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70907,7 +70907,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -70961,7 +70961,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71014,7 +71014,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71067,7 +71067,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71120,7 +71120,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71173,7 +71173,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71227,7 +71227,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71281,7 +71281,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71334,7 +71334,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71386,7 +71386,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71438,7 +71438,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71491,7 +71491,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71544,7 +71544,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71597,7 +71597,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71650,7 +71650,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71702,7 +71702,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71754,7 +71754,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71807,7 +71807,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71860,7 +71860,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71913,7 +71913,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -71966,7 +71966,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72019,7 +72019,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72071,7 +72071,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72123,7 +72123,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72175,7 +72175,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72227,7 +72227,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72280,7 +72280,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72333,7 +72333,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72386,7 +72386,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72438,7 +72438,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72490,7 +72490,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72542,7 +72542,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72594,7 +72594,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72646,7 +72646,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72698,7 +72698,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72750,7 +72750,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72802,7 +72802,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72854,7 +72854,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72906,7 +72906,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -72958,7 +72958,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73010,7 +73010,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73062,7 +73062,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73114,7 +73114,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73166,7 +73166,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73218,7 +73218,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73270,7 +73270,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73322,7 +73322,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73374,7 +73374,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73433,7 +73433,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73485,7 +73485,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73537,7 +73537,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73589,7 +73589,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73641,7 +73641,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73693,7 +73693,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73745,7 +73745,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73797,7 +73797,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73849,7 +73849,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73901,7 +73901,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -73953,7 +73953,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74005,7 +74005,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74057,7 +74057,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74109,7 +74109,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74161,7 +74161,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74213,7 +74213,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74265,7 +74265,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74317,7 +74317,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74369,7 +74369,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74421,7 +74421,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74473,7 +74473,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74525,7 +74525,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74577,7 +74577,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74629,7 +74629,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74681,7 +74681,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74733,7 +74733,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74785,7 +74785,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74837,7 +74837,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74890,7 +74890,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74943,7 +74943,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -74996,7 +74996,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75049,7 +75049,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75102,7 +75102,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75155,7 +75155,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75208,7 +75208,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75261,7 +75261,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75314,7 +75314,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75367,7 +75367,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75421,7 +75421,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75475,7 +75475,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75529,7 +75529,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75583,7 +75583,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75637,7 +75637,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75691,7 +75691,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75745,7 +75745,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75799,7 +75799,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75853,7 +75853,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75907,7 +75907,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -75961,7 +75961,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76015,7 +76015,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76069,7 +76069,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76123,7 +76123,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76177,7 +76177,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76231,7 +76231,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76285,7 +76285,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76339,7 +76339,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76393,7 +76393,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76447,7 +76447,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76501,7 +76501,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76555,7 +76555,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76609,7 +76609,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76663,7 +76663,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76717,7 +76717,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76771,7 +76771,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76825,7 +76825,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76878,7 +76878,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76931,7 +76931,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -76984,7 +76984,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77037,7 +77037,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77090,7 +77090,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77143,7 +77143,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77196,7 +77196,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77249,7 +77249,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77302,7 +77302,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77356,7 +77356,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77410,7 +77410,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77464,7 +77464,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77518,7 +77518,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77572,7 +77572,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77626,7 +77626,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77680,7 +77680,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77734,7 +77734,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77787,7 +77787,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77839,7 +77839,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77891,7 +77891,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77943,7 +77943,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -77996,7 +77996,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78049,7 +78049,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78102,7 +78102,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78155,7 +78155,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78208,7 +78208,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78261,7 +78261,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78314,7 +78314,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78367,7 +78367,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78420,7 +78420,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78472,7 +78472,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78524,7 +78524,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78576,7 +78576,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78628,7 +78628,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78681,7 +78681,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78734,7 +78734,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78787,7 +78787,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78839,7 +78839,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78891,7 +78891,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78944,7 +78944,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -78997,7 +78997,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79050,7 +79050,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79103,7 +79103,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79156,7 +79156,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79209,7 +79209,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79262,7 +79262,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79315,7 +79315,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79368,7 +79368,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79420,7 +79420,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79472,7 +79472,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79524,7 +79524,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79576,7 +79576,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79628,7 +79628,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79680,7 +79680,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79732,7 +79732,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79785,7 +79785,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79838,7 +79838,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79891,7 +79891,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79944,7 +79944,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -79997,7 +79997,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80050,7 +80050,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80103,7 +80103,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80156,7 +80156,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80209,7 +80209,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80261,7 +80261,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80313,7 +80313,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80365,7 +80365,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80417,7 +80417,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80469,7 +80469,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80521,7 +80521,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80573,7 +80573,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80625,7 +80625,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80677,7 +80677,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80729,7 +80729,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80781,7 +80781,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80833,7 +80833,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80885,7 +80885,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80937,7 +80937,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -80989,7 +80989,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81041,7 +81041,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81093,7 +81093,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81145,7 +81145,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81197,7 +81197,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81249,7 +81249,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81301,7 +81301,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81353,7 +81353,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81405,7 +81405,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81457,7 +81457,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81509,7 +81509,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81561,7 +81561,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81613,7 +81613,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81665,7 +81665,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81717,7 +81717,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81769,7 +81769,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81821,7 +81821,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [ @@ -81873,7 +81873,7 @@ "dimension_sets": [ { "cpu": "x86-64", - "os": "Mac-11|Mac-10.16" + "os": "Mac-12" } ], "named_caches": [
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index efab7cb..781c591 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -1687,45 +1687,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.mobile", - "--browser=android-chromium" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests_android_chrome", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "resultdb": { - "enable": true, - "has_native_resultdb_integration": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "containment_type": "AUTO", - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests_android_chrome/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=android-chromium", @@ -11476,34 +11437,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "cpu": "arm64", - "display_attached": "1", - "mac_model": "Macmini9,1", - "os": "Mac-11", - "pool": "chromium.tests" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release", @@ -12568,33 +12501,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "cpu": "x86-64", - "display_attached": "1", - "gpu": "8086:3e9b", - "os": "Mac-11.5.2" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release", @@ -15222,35 +15128,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "cpu": "x86-64", - "display_attached": "1", - "gpu": "1002:6821", - "hidpi": "1", - "os": "Mac-12.1", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release", @@ -18441,34 +18318,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop", - "--browser=release_x64" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "gpu": "1002:7340", - "os": "Windows-10", - "pool": "chromium.tests.gpu.experimental" - } - ], - "expiration": 21600, - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release_x64", @@ -19241,33 +19090,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop", - "--browser=release_x64" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "gpu": "8086:5912-26.20.100.8141|8086:3e92-26.20.100.8141", - "os": "Windows-10", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release_x64", @@ -20066,33 +19888,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop", - "--browser=release_x64" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "gpu": "10de:2184-27.21.14.5638", - "os": "Windows-10-18363", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release_x64", @@ -20892,32 +20687,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "gpu": "10de:2184-27.21.14.5638", - "os": "Windows-10-18363", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release",
diff --git a/testing/buildbot/chromium.gpu.json b/testing/buildbot/chromium.gpu.json index b399b0d6..e9cf067a 100644 --- a/testing/buildbot/chromium.gpu.json +++ b/testing/buildbot/chromium.gpu.json
@@ -285,42 +285,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.mobile", - "--browser=android-chromium" - ], - "check_flakiness_for_new_tests": false, - "experiment_percentage": 10, - "isolate_name": "rendering_representative_perf_tests_android_chrome", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "containment_type": "AUTO", - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests_android_chrome/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=android-chromium", @@ -2134,33 +2098,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "cpu": "x86-64", - "display_attached": "1", - "gpu": "8086:3e9b", - "os": "Mac-11.5.2" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release", @@ -3098,35 +3035,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "cpu": "x86-64", - "display_attached": "1", - "gpu": "1002:6821", - "hidpi": "1", - "os": "Mac-12.1", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release", @@ -4079,33 +3987,6 @@ }, { "args": [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop", - "--browser=release_x64" - ], - "check_flakiness_for_new_tests": false, - "isolate_name": "rendering_representative_perf_tests", - "merge": { - "args": [], - "script": "//testing/merge_scripts/standard_isolated_script_merge.py" - }, - "name": "rendering_representative_perf_tests", - "swarming": { - "can_use_on_swarming_builders": true, - "containment_type": "AUTO", - "dimension_sets": [ - { - "gpu": "10de:2184-27.21.14.5638", - "os": "Windows-10-18363", - "pool": "chromium.tests.gpu" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test_id_prefix": "ninja://chrome/test:rendering_representative_perf_tests/" - }, - { - "args": [ "screenshot_sync", "--show-stdout", "--browser=release_x64",
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index 6c33b91..d4766bb6 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -307,6 +307,10 @@ "type": "windowed_test_launcher", "executable": "browser_tests", }, + "build_junit_tests": { + "label": "//build/android:build_junit_tests", + "type": "junit_test", + }, "captured_sites_interactive_tests": { "label": "//chrome/test:captured_sites_interactive_tests", "type": "windowed_test_launcher", @@ -950,10 +954,6 @@ "label": "//headless:headless_unittests", "type": "console_test_launcher", }, - "incremental_javac_junit_tests": { - "label": "//build/android/test:incremental_javac_junit_tests", - "type": "junit_test", - }, "install_static_unittests": { "label": "//chrome/install_static:install_static_unittests", "type": "console_test_launcher", @@ -1551,26 +1551,6 @@ "label": "//remoting:remoting_unittests", "type": "console_test_launcher", }, - "rendering_representative_perf_tests": { - "args": [ - "--output-format=csv", - "--browser=release", - "--upload-results", - ], - "label": "//chrome/test:rendering_representative_perf_tests", - "script": "//testing/scripts/run_rendering_benchmark_with_gated_performance.py", - "type": "script", - }, - "rendering_representative_perf_tests_android_chrome": { - "args": [ - "--output-format=csv", - "--browser=release", - "--upload-results", - ], - "label": "//chrome/test:rendering_representative_perf_tests_android_chrome", - "script": "//testing/scripts/run_rendering_benchmark_with_gated_performance.py", - "type": "script", - }, "resource_sizes_chrome_modern_public_minimal_apks": { "label": "//chrome/android:resource_sizes_chrome_modern_public_minimal_apks", "type": "generated_script",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index c8803192c..889ba60 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -2640,40 +2640,6 @@ }, }, }, - 'rendering_representative_perf_tests': { - 'modifications': { - 'Win10 FYI x64 Exp Release (Intel HD 630)': { - 'args': [ - '--browser=release_x64', - ], - }, - 'Win10 FYI x64 Exp Release (NVIDIA)': { - 'args': [ - '--browser=release_x64', - ], - }, - 'Win10 FYI x64 Release (AMD RX 5500 XT)': { - 'args': [ - '--browser=release_x64', - ], - }, - 'Win10 FYI x64 Release (Intel HD 630)': { - 'args': [ - '--browser=release_x64', - ], - }, - 'Win10 FYI x64 Release (NVIDIA)': { - 'args': [ - '--browser=release_x64', - ], - }, - 'Win10 x64 Release (NVIDIA)': { - 'args': [ - '--browser=release_x64', - ], - }, - }, - }, 'sandbox_linux_unittests': { 'modifications': { 'android-12-x64-rel': {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index e1dfe83d..3e9bb22b 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -982,6 +982,11 @@ 'nougat-x86-emulator', ], }, + 'build_junit_tests':{ + 'remove_mixins': [ + 'nougat-x86-emulator', + ], + }, 'chrome_java_test_pagecontroller_junit_tests': { 'remove_mixins': [ 'nougat-x86-emulator', @@ -1007,11 +1012,6 @@ 'nougat-x86-emulator', ], }, - 'incremental_javac_junit_tests':{ - 'remove_mixins': [ - 'nougat-x86-emulator', - ], - }, 'junit_unit_tests': { 'remove_mixins': [ 'nougat-x86-emulator', @@ -4539,45 +4539,6 @@ }, }, - 'rendering_desktop_representative_perf_tests_isolated_scripts': { - 'rendering_representative_perf_tests': { - 'isolate_name': 'rendering_representative_perf_tests', - 'args': [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.desktop", - ], - 'check_flakiness_for_new_tests': False, - 'swarming': {}, - } - }, - - 'rendering_mobile_representative_perf_tests_isolated_scripts': { - 'rendering_representative_perf_tests': { - 'isolate_name': 'rendering_representative_perf_tests_android_chrome', - 'args': [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.mobile", - "--browser=android-chromium" - ], - 'check_flakiness_for_new_tests': False, - 'swarming': {}, - } - }, - - 'rendering_mobile_representative_perf_tests_isolated_scripts_experimental': { - 'rendering_representative_perf_tests': { - 'isolate_name': 'rendering_representative_perf_tests_android_chrome', - 'args': [ - "../../tools/perf/run_benchmark", - "--benchmarks=rendering.mobile", - "--browser=android-chromium" - ], - 'check_flakiness_for_new_tests': False, - 'swarming': {}, - 'experiment_percentage': 10, - } - }, - 'rust_gtests': { 'base_unittests': {}, 'rust_gtest_interop_unittests': {}, @@ -6291,10 +6252,6 @@ 'gpu_desktop_specific_gtests', ], - 'gpu_desktop_representative_perf_fyi_isolated_scripts': [ - 'rendering_desktop_representative_perf_tests_isolated_scripts', - ], - 'gpu_fuchsia_telemetry_experimental_tests': [ 'gpu_fuchsia_common_telemetry_tests', 'gpu_mediapipe_validating_telemetry_tests', @@ -6521,9 +6478,8 @@ 'gpu_win_intel_specific_telemetry_tests', ], - 'gpu_fyi_win_optional_and_representative_perf_isolated_scripts': [ + 'gpu_fyi_win_optional_isolated_scripts': [ 'gpu_command_buffer_perf_passthrough_isolated_scripts', - 'rendering_desktop_representative_perf_tests_isolated_scripts', ], 'gpu_fyi_win_release_telemetry_tests': [ @@ -6536,10 +6492,6 @@ 'gpu_webgl_conformance_vulkan_passthrough_telemetry_tests', ], - 'gpu_mobile_representative_perf_fyi_isolated_scripts': [ - 'rendering_mobile_representative_perf_tests_isolated_scripts', - ], - 'gpu_nexus5x_telemetry_tests': [ 'gpu_common_and_optional_telemetry_tests', 'gpu_mediapipe_passthrough_telemetry_tests',
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 6653711..1fd98ab3 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -3315,7 +3315,7 @@ ], 'mixins': [ 'has_native_resultdb_integration', - 'mac_11_x64', + 'mac_12_x64', 'mac_toolchain', 'out_dir_arg', 'xcode_13_main', @@ -3333,7 +3333,7 @@ ], 'mixins': [ 'has_native_resultdb_integration', - 'mac_11_x64', + 'mac_12_x64', 'mac_toolchain', 'out_dir_arg', 'xcode_14_beta', @@ -4113,7 +4113,6 @@ ], 'test_suites': { 'gpu_telemetry_tests': 'gpu_common_telemetry_tests', - 'isolated_scripts': 'rendering_mobile_representative_perf_tests_isolated_scripts_experimental', }, }, 'GPU Linux Builder': {}, @@ -4162,7 +4161,6 @@ 'test_suites': { 'gtest_tests': 'gpu_desktop_mac_gtests', 'gpu_telemetry_tests': 'gpu_common_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, 'Mac Retina Debug (AMD)': { @@ -4185,7 +4183,6 @@ 'test_suites': { 'gtest_tests': 'gpu_desktop_passthrough_gtests', 'gpu_telemetry_tests': 'gpu_common_gl_passthrough_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, 'Win10 x64 Debug (NVIDIA)': { @@ -4208,7 +4205,6 @@ 'test_suites': { 'gtest_tests': 'gpu_win_gtests', 'gpu_telemetry_tests': 'gpu_common_win_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, }, @@ -4262,7 +4258,6 @@ ], 'test_suites': { 'gtest_tests': 'gpu_fyi_android_gtests', - 'isolated_scripts': 'gpu_mobile_representative_perf_fyi_isolated_scripts', 'gpu_telemetry_tests': 'gpu_nexus5x_telemetry_tests', 'android_webview_gpu_telemetry_tests': 'android_webview_gpu_telemetry_tests', }, @@ -4551,7 +4546,6 @@ 'test_suites': { 'gtest_tests': 'gpu_fyi_mac_release_gtests', 'gpu_telemetry_tests': 'gpu_fyi_mac_release_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, 'Mac FYI Release (Intel)': { @@ -4563,7 +4557,6 @@ 'test_suites': { 'gtest_tests': 'gpu_fyi_mac_release_gtests', 'gpu_telemetry_tests': 'gpu_fyi_mac_release_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, 'Mac FYI Retina ASAN (AMD)': { @@ -4608,7 +4601,6 @@ 'test_suites': { 'gtest_tests': 'gpu_fyi_mac_amd_release_gtests', 'gpu_telemetry_tests': 'gpu_fyi_mac_amd_release_telemetry_tests', - 'isolated_scripts': 'rendering_desktop_representative_perf_tests_isolated_scripts', }, }, 'Mac FYI Retina Release (NVIDIA)': { @@ -4712,7 +4704,6 @@ ], 'test_suites': { 'gtest_tests': 'gpu_fyi_win_gtests', - 'isolated_scripts': 'gpu_desktop_representative_perf_fyi_isolated_scripts', 'gpu_telemetry_tests': 'gpu_fyi_win_amd_release_telemetry_tests', }, }, @@ -4724,7 +4715,6 @@ ], 'test_suites': { 'gtest_tests': 'gpu_fyi_win_gtests', - 'isolated_scripts': 'gpu_desktop_representative_perf_fyi_isolated_scripts', 'gpu_telemetry_tests': 'gpu_fyi_win_intel_release_telemetry_tests', }, }, @@ -4737,7 +4727,7 @@ 'test_suites': { 'gtest_tests': 'gpu_fyi_win_gtests', 'gpu_telemetry_tests': 'gpu_fyi_win_release_telemetry_tests', - 'isolated_scripts': 'gpu_fyi_win_optional_and_representative_perf_isolated_scripts', + 'isolated_scripts': 'gpu_fyi_win_optional_isolated_scripts', }, }, 'Win10 FYI x64 Release XR Perf (NVIDIA)': { @@ -4758,7 +4748,7 @@ ], 'test_suites': { 'gtest_tests': 'gpu_fyi_win_gtests', - 'isolated_scripts': 'gpu_fyi_win_optional_and_representative_perf_isolated_scripts', + 'isolated_scripts': 'gpu_fyi_win_optional_isolated_scripts', 'gpu_telemetry_tests': 'gpu_fyi_win_release_telemetry_tests', }, },
diff --git a/testing/scripts/representative_perf_test_data/OWNERS b/testing/scripts/representative_perf_test_data/OWNERS deleted file mode 100644 index 2b84d944..0000000 --- a/testing/scripts/representative_perf_test_data/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -behdadb@chromium.org -sadrul@chromium.org
diff --git a/testing/scripts/representative_perf_test_data/platform_specific_tags.json b/testing/scripts/representative_perf_test_data/platform_specific_tags.json deleted file mode 100644 index a95f877..0000000 --- a/testing/scripts/representative_perf_test_data/platform_specific_tags.json +++ /dev/null
@@ -1,37 +0,0 @@ -{ - "mac": { - "benchmark": "desktop", - "tags": [ - { - "buildername": "Mac Release (Intel)", - "builder_group": "chromium.gpu", - "os": "Mac-11.5.2" - }, - { - "buildername": "Mac Retina Release (AMD)", - "builder_group": "chromium.gpu", - "os": "Mac-12.1" - } - ] - }, - "win": { - "benchmark": "desktop", - "tags": [ - { - "buildername": "Win10 x64 Release (NVIDIA)", - "builder_group": "chromium.gpu", - "os": "Windows-10-18363" - } - ] - }, - "android": { - "benchmark": "mobile", - "tags": [ - { - "buildername": "Android FYI Release (Nexus 5X)", - "builder_group": "chromium.gpu.fyi", - "os": "Android" - } - ] - } -} \ No newline at end of file
diff --git a/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json b/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json deleted file mode 100644 index d8f71d1..0000000 --- a/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json +++ /dev/null
@@ -1,218 +0,0 @@ -{ - "win": { - "canvas_to_blob": { - "ci_095": 6.363, - "avg": 28.443, - "cpu_wall_time_ratio": 0.284 - }, - "filter_terrain_svg": { - "ci_095": 0.111, - "avg": 23.175, - "cpu_wall_time_ratio": 0.396 - }, - "web_animation_value_type_transform_complex": { - "ci_095": 0.235, - "avg": 16.669, - "cpu_wall_time_ratio": 0.317 - }, - "runway_2019": { - "ci_095": 0.261, - "avg": 16.664, - "cpu_wall_time_ratio": 0.304 - }, - "css_transitions_inline_style": { - "ci_095": 6.862, - "avg": 23.008, - "cpu_wall_time_ratio": 0.326 - }, - "aquarium_20k_fast_call": { - "ci_095": 2.35, - "_comment": "crbug.com/1241039", - "avg": 101.595, - "cpu_wall_time_ratio": 0.375, - "experimental": true - }, - "aquarium_20k": { - "ci_095": 2.342, - "_comment": "crbug.com/1275735", - "avg": 102.75, - "cpu_wall_time_ratio": 0.387, - "experimental": true - }, - "balls_css_transition_2_properties": { - "ci_095": 6.121, - "_comment": "crbug.com/1226864", - "avg": 83.163, - "cpu_wall_time_ratio": 0.048, - "experimental": true - }, - "cc_poster_circle": { - "ci_095": 0.18, - "avg": 16.665, - "cpu_wall_time_ratio": 0.221 - }, - "js_poster_circle": { - "ci_095": 0.21, - "avg": 16.669, - "cpu_wall_time_ratio": 0.279 - }, - "web_animations_staggered_triggering_page": { - "ci_095": 0.363, - "avg": 16.773, - "cpu_wall_time_ratio": 0.394 - }, - "aquarium": { - "ci_095": 0.187, - "avg": 16.662, - "cpu_wall_time_ratio": 0.34 - }, - "main_30fps_impl_60fps": { - "control": true, - "ci_095": 0.407, - "avg": 16.687, - "cpu_wall_time_ratio": 0.253 - }, - "css_value_type_shadow": { - "ci_095": 0.717, - "avg": 42.191, - "cpu_wall_time_ratio": 0.434 - }, - "nvidia_vertex_buffer_object": { - "ci_095": 0.521, - "avg": 16.774, - "cpu_wall_time_ratio": 0.351 - }, - "many_planets_deep": { - "ci_095": 0.172, - "avg": 16.663, - "cpu_wall_time_ratio": 0.279 - } - }, - "mac": { - "twitch_2018": { - "ci_095": 8.917, - "avg": 19.497, - "cpu_wall_time_ratio": 0.538, - "experimental": true, - "_comment": "crbug.com/1312722" - }, - "balls_javascript_canvas": { - "ci_095": 5.587, - "_comment": "crbug.com/1122037", - "avg": 37.067, - "cpu_wall_time_ratio": 0.591, - "experimental": true - }, - "transform_transitions_js_block": { - "ci_095": 0.351, - "avg": 16.731, - "cpu_wall_time_ratio": 0.278 - }, - "web_animations_staggered_infinite_iterations": { - "ci_095": 1.98, - "avg": 17.099, - "cpu_wall_time_ratio": 0.376 - }, - "fill_shapes": { - "ci_095": 8.587, - "_comment": "crbug.com/1122037", - "avg": 47.9, - "cpu_wall_time_ratio": 0.52, - "experimental": true - }, - "css_value_type_shadow": { - "ci_095": 21.266, - "_comment": "crbug.com/1139155", - "avg": 72.766, - "cpu_wall_time_ratio": 0.217, - "experimental": true - }, - "animometer_webgl_attrib_arrays": { - "ci_095": 0.408, - "avg": 16.671, - "cpu_wall_time_ratio": 0.394 - }, - "canvas_05000_pixels_per_second": { - "ci_095": 0.109, - "avg": 16.672, - "cpu_wall_time_ratio": 0.325 - }, - "main_30fps_impl_60fps": { - "control": true, - "ci_095": 0.273, - "avg": 16.67, - "cpu_wall_time_ratio": 0.188 - }, - "ie_chalkboard": { - "ci_095": 49.911, - "_comment": "crbug.com/1133599", - "avg": 118.192, - "cpu_wall_time_ratio": 0.099, - "experimental": true - }, - "new_tilings": { - "ci_095": 0.166, - "_comment": "Return to 16.692 after crbug.com/1225374", - "avg": 16.671, - "cpu_wall_time_ratio": 0.324 - }, - "chip_tune": { - "ci_095": 0.876, - "avg": 16.702, - "cpu_wall_time_ratio": 0.34 - } - }, - "android": { - "text_10000_pixels_per_second": { - "ci_095": 0.403, - "avg": 16.726, - "cpu_wall_time_ratio": 0.655 - }, - "balls_javascript_canvas": { - "ci_095": 77.076, - "avg": 391.519, - "cpu_wall_time_ratio": 0.579 - }, - "transform_transitions_js_block": { - "ci_095": 0.062, - "avg": 16.66, - "cpu_wall_time_ratio": 0.51 - }, - "web_animations_staggered_infinite_iterations": { - "ci_095": 1.845, - "avg": 36.748, - "cpu_wall_time_ratio": 0.611 - }, - "motion_mark_canvas_fill_shapes": { - "ci_095": 155.321, - "avg": 378.582, - "cpu_wall_time_ratio": 0.573 - }, - "css_value_type_shadow": { - "ci_095": 62.5, - "avg": 290.302, - "cpu_wall_time_ratio": 0.293 - }, - "canvas_05000_pixels_per_second": { - "ci_095": 0.517, - "avg": 16.711, - "cpu_wall_time_ratio": 0.677 - }, - "main_30fps_impl_60fps": { - "control": true, - "ci_095": 0.169, - "avg": 16.656, - "cpu_wall_time_ratio": 0.536 - }, - "new_tilings": { - "ci_095": 1.471, - "avg": 21.522, - "cpu_wall_time_ratio": 0.666 - }, - "extra_large_texture_uploads": { - "ci_095": 49.722, - "avg": 305.43, - "cpu_wall_time_ratio": 0.514 - } - } -} \ No newline at end of file
diff --git a/testing/scripts/run_rendering_benchmark_with_gated_performance.py b/testing/scripts/run_rendering_benchmark_with_gated_performance.py deleted file mode 100755 index 39537a0..0000000 --- a/testing/scripts/run_rendering_benchmark_with_gated_performance.py +++ /dev/null
@@ -1,401 +0,0 @@ -#!/usr/bin/env vpython3 -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Runs telemetry benchmarks on representative story tag. - -This script is a wrapper around run_performance_tests.py to capture the -values of performance metrics and compare them with the acceptable limits -in order to prevent regressions. - -Arguments used for this script are the same as run_performance_tests.py. - -The name and some functionalities of this script should be adjusted for -use with other benchmarks. -""" - -from __future__ import print_function - -import argparse -import csv -import json -import os -import sys -import time - -import numpy as np - -import run_performance_tests - -# Add src/testing/ into sys.path for importing common without pylint errors. -sys.path.append( - os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) -from scripts import common - -# AVG_ERROR_MARGIN determines how much more the value of frame times can be -# compared to the recorded value (multiplier of upper limit). -AVG_ERROR_MARGIN = 1.1 -# CI stands for confidence intervals. "ci_095"s recorded in the data is the -# recorded range between upper and lower CIs. CI_ERROR_MARGIN is the maximum -# acceptable ratio of calculated ci_095 to the recorded ones. -# TODO(behdadb) crbug.com/1052054 -CI_ERROR_MARGIN = 1.5 - -METRIC_NAME = 'frame_times' - -# pylint: disable=useless-object-inheritance - - -class ResultRecorder(object): - def __init__(self): - self.fails = 0 - self.tests = 0 - self.start_time = time.time() - self.output = {} - self.return_code = 0 - self._failed_stories = set() - self._noisy_control_stories = set() - # Set of _noisy_control_stories keeps track of control tests which failed - # because of high noise values. - - def set_tests(self, output): - self.output = output - self.fails = output['num_failures_by_type'].get('FAIL', 0) - self.tests = self.fails + output['num_failures_by_type'].get('PASS', 0) - - def add_failure(self, name, benchmark, is_control=False): - self.output['tests'][benchmark][name]['actual'] = 'FAIL' - self.output['tests'][benchmark][name]['is_unexpected'] = True - self._failed_stories.add(name) - self.fails += 1 - if is_control: - self._noisy_control_stories.add(name) - - def remove_failure(self, name, benchmark, is_control=False, - invalidation_reason=None): - self.output['tests'][benchmark][name]['actual'] = 'PASS' - self.output['tests'][benchmark][name]['is_unexpected'] = False - self._failed_stories.remove(name) - self.fails -= 1 - if is_control: - self._noisy_control_stories.remove(name) - if invalidation_reason: - self.add_invalidation_reason(name, benchmark, invalidation_reason) - - def invalidate_failures(self, benchmark): - # The method is for invalidating the failures in case of noisy control test - for story in self._failed_stories.copy(): - print(story + ' [Invalidated Failure]: The story failed but was ' + - 'invalidated as a result of noisy control test.') - self.remove_failure(story, benchmark, False, 'Noisy control test') - - def add_invalidation_reason(self, name, benchmark, reason): - self.output['tests'][benchmark][name]['invalidation_reason'] = reason - - @property - def failed_stories(self): - return self._failed_stories - - @property - def is_control_stories_noisy(self): - return len(self._noisy_control_stories) > 0 - - def get_output(self, return_code): - self.output['seconds_since_epoch'] = time.time() - self.start_time - self.output['num_failures_by_type']['PASS'] = self.tests - self.fails - self.output['num_failures_by_type']['FAIL'] = self.fails - if return_code == 1: - self.output['interrupted'] = True - - plural = lambda n, s, p: '%d %s' % (n, p if n != 1 else s) - tests = lambda n: plural(n, 'test', 'tests') - - print('[ PASSED ] ' + tests(self.tests - self.fails) + '.') - if self.fails > 0: - print('[ FAILED ] ' + tests(self.fails) + '.') - self.return_code = 1 - - return (self.output, self.return_code) - -class RenderingRepresentativePerfTest(object): - def __init__(self, initialization_for_tests=False): - self.return_code = 0 - # result_recorder for rerun, and non rerun - self.result_recorder = { - True: ResultRecorder(), - False: ResultRecorder() - } - - if initialization_for_tests is True: - return - - self.options = parse_arguments() - print (self.options) - - self.benchmark = self.options.benchmarks - out_dir_path = os.path.dirname(self.options.isolated_script_test_output) - re_run_output_dir = os.path.join(out_dir_path, 're_run_failures') - - self.output_path = { - True: os.path.join( - re_run_output_dir, self.benchmark, 'test_results.json'), - False: os.path.join(out_dir_path, self.benchmark, 'test_results.json') - } - self.results_path = { - True: os.path.join( - re_run_output_dir, self.benchmark, 'perf_results.csv'), - False: os.path.join(out_dir_path, self.benchmark, 'perf_results.csv') - } - - re_run_test_output = os.path.join(re_run_output_dir, - os.path.basename(self.options.isolated_script_test_output)) - - self.set_platform_specific_attributes() - - # The values used as the upper limit are the 99th percentile of the - # avg and ci_095 frame_times recorded by dashboard in the past 200 - # revisions. If the value measured here would be higher than this value at - # least by 10 [AVG_ERROR_MARGIN] percent of upper limit, that would be - # considered a failure. crbug.com/953895 - with open( - os.path.join(os.path.dirname(os.path.abspath(__file__)), - 'representative_perf_test_data', - 'representatives_frame_times_upper_limit.json') - ) as bound_data: - self.upper_limit_data = json.load(bound_data)[self.platform] - - self.args = list(sys.argv) - # The first run uses all stories in the representative story tag, but for - # rerun we use only the failed stories. - self.args.extend(['--story-tag-filter', self.story_tag]) - - self.re_run_args = replace_arg_values(list(sys.argv), [ - ('--isolated-script-test-output', re_run_test_output)]) - - def parse_csv_results(self, csv_obj): - """ Parses the raw CSV data - Convers the csv_obj into an array of valid values for averages and - confidence intervals based on the described upper_limits. - - Args: - csv_obj: An array of rows (dict) describing the CSV results - - Raturns: - A dictionary which has the stories as keys and an array of confidence - intervals and valid averages as data. - """ - values_per_story = {} - for row in csv_obj: - # For now only frame_times is used for testing representatives' - # performance and cpu_wall_time_ratio is used for validation. - if row['name'] != METRIC_NAME and row['name'] != 'cpu_wall_time_ratio': - continue - story_name = row['stories'] - if (story_name not in self.upper_limit_data): - continue - if story_name not in values_per_story: - values_per_story[story_name] = { - 'averages': [], - 'ci_095': [], - 'cpu_wall_time_ratio': [] - } - - if row['name'] == METRIC_NAME and row['avg'] != '' and row['count'] != 0: - values_per_story[story_name]['ci_095'].append(float(row['ci_095'])) - values_per_story[story_name]['averages'].append(float(row['avg'])) - elif row['name'] == 'cpu_wall_time_ratio' and row['avg'] != '': - values_per_story[story_name]['cpu_wall_time_ratio'].append( - float(row['avg'])) - - return values_per_story - - def compare_values(self, values_per_story, rerun=False): - """ Parses the raw CSV data - Compares the values in values_per_story with the upper_limit_data and - determines if the story passes or fails and updates the ResultRecorder. - - Args: - values_per_story: An array of rows (dict) descriving the CSV results - rerun: Is this a rerun or initial run - """ - for story_name in values_per_story: - # The experimental stories will not be considered for failing the tests - if (self.is_experimental_story(story_name)): - continue - if len(values_per_story[story_name]['ci_095']) == 0: - print(('[ FAILED ] {}/{} has no valid values for {}. Check ' + - 'run_benchmark logs for more information.').format( - self.benchmark, story_name, METRIC_NAME)) - self.result_recorder[rerun].add_failure(story_name, self.benchmark) - continue - - upper_limits = self.upper_limit_data - upper_limit_avg = upper_limits[story_name]['avg'] - upper_limit_ci = upper_limits[story_name]['ci_095'] - lower_limit_cpu_ratio = upper_limits[story_name]['cpu_wall_time_ratio'] - measured_avg = np.mean(np.array(values_per_story[story_name]['averages'])) - measured_ci = np.mean(np.array(values_per_story[story_name]['ci_095'])) - measured_cpu_ratio = np.mean(np.array( - values_per_story[story_name]['cpu_wall_time_ratio'])) - - if (measured_ci > upper_limit_ci * CI_ERROR_MARGIN and - self.is_control_story(story_name)): - print(('[ FAILED ] {}/{} {} has higher noise ({:.3f}) ' + - 'compared to upper limit ({:.3f})').format( - self.benchmark, story_name, METRIC_NAME, measured_ci, - upper_limit_ci)) - self.result_recorder[rerun].add_failure( - story_name, self.benchmark, True) - elif (measured_avg > upper_limit_avg * AVG_ERROR_MARGIN): - if (measured_cpu_ratio >= lower_limit_cpu_ratio): - print(('[ FAILED ] {}/{} higher average {}({:.3f}) compared' + - ' to upper limit ({:.3f})').format(self.benchmark, story_name, - METRIC_NAME, measured_avg, upper_limit_avg)) - self.result_recorder[rerun].add_failure(story_name, self.benchmark) - else: - print(('[ OK ] {}/{} higher average {}({:.3f}) compared ' + - 'to upper limit({:.3f}). Invalidated for low cpu_wall_time_ratio' - ).format(self.benchmark, story_name, METRIC_NAME, measured_avg, - upper_limit_avg)) - self.result_recorder[rerun].add_invalidation_reason( - story_name, self.benchmark, 'Low cpu_wall_time_ratio') - else: - print(('[ OK ] {}/{} lower average {}({:.3f}) compared ' + - 'to upper limit({:.3f}).').format(self.benchmark, story_name, - METRIC_NAME, measured_avg, upper_limit_avg)) - - def interpret_run_benchmark_results(self, rerun=False): - with open(self.output_path[rerun], 'r+') as resultsFile: - initialOut = json.load(resultsFile) - self.result_recorder[rerun].set_tests(initialOut) - - with open(self.results_path[rerun]) as csv_file: - csv_obj = csv.DictReader(csv_file) - values_per_story = self.parse_csv_results(csv_obj) - - if not rerun: - # Clearing the result of run_benchmark and write the gated perf results - resultsFile.seek(0) - resultsFile.truncate(0) - - self.compare_values(values_per_story, rerun) - - def run_perf_tests(self): - self.return_code |= run_performance_tests.main(self.args) - self.interpret_run_benchmark_results(False) - - if len(self.result_recorder[False].failed_stories) > 0: - # For failed stories we run_tests again to make sure it's not a false - # positive. - print('============ Re_run the failed tests ============') - all_failed_stories = '('+'|'.join( - self.result_recorder[False].failed_stories)+')' - # TODO(crbug.com/1055893): Remove the extra chrome categories after - # investigation of flakes in representative perf tests. - self.re_run_args.extend( - ['--story-filter', all_failed_stories, '--pageset-repeat=3', - '--extra-chrome-categories=blink,blink_gc,gpu,v8,viz']) - self.return_code |= run_performance_tests.main(self.re_run_args) - self.interpret_run_benchmark_results(True) - - for story_name in self.result_recorder[False].failed_stories.copy(): - if story_name not in self.result_recorder[True].failed_stories: - self.result_recorder[False].remove_failure(story_name, - self.benchmark, self.is_control_story(story_name)) - - if self.result_recorder[False].is_control_stories_noisy: - # In this case all failures are reported as expected, and the number of - # Failed stories in output.json will be zero. - self.result_recorder[False].invalidate_failures(self.benchmark) - - ( - finalOut, - self.return_code - ) = self.result_recorder[False].get_output(self.return_code) - - with open(self.output_path[False], 'r+') as resultsFile: - json.dump(finalOut, resultsFile, indent=4) - with open(self.options.isolated_script_test_output, 'w') as outputFile: - json.dump(finalOut, outputFile, indent=4) - - if self.result_recorder[False].is_control_stories_noisy: - assert self.return_code == 0 - print('Control story has high noise. These runs are not reliable!') - - return self.return_code - - def is_control_story(self, story_name): - # The story tagged as control story in upper_limit_data, will be used to - # identify possible flake and invalidates the results. - return self.story_has_attribute_enabled(story_name, 'control') - - def is_experimental_story(self, story_name): - # The story tagged as experimental story in upper_limit_data, will be used - # to gather the performance results, but the test would not be failed as - # a result of. - return self.story_has_attribute_enabled(story_name, 'experimental') - - def story_has_attribute_enabled(self, story_name, attribute): - return (attribute in self.upper_limit_data[story_name] and - self.upper_limit_data[story_name][attribute] == True) - - - def set_platform_specific_attributes(self): - if self.benchmark == 'rendering.desktop': - # Linux does not have it's own specific representatives - # and uses the representatives chosen for windows. - if sys.platform == 'win32' or sys.platform.startswith('linux'): - self.platform = 'win' - self.story_tag = 'representative_win_desktop' - elif sys.platform == 'darwin': - self.platform = 'mac' - self.story_tag = 'representative_mac_desktop' - else: - self.return_code = 1 - elif self.benchmark == 'rendering.mobile': - self.platform = 'android' - self.story_tag = 'representative_mobile' - else: - self.return_code = 1 - -def replace_arg_values(args, key_value_pairs): - for index in range(0, len(args)): - for (key, value) in key_value_pairs: - if args[index].startswith(key): - if '=' in args[index]: - args[index] = key + '=' + value - else: - args[index+1] = value - return args - -def main(): - test_runner = RenderingRepresentativePerfTest() - if test_runner.return_code == 1: - return 1 - - return test_runner.run_perf_tests() - -def parse_arguments(): - parser = argparse.ArgumentParser() - parser.add_argument('executable', help='The name of the executable to run.') - parser.add_argument( - '--benchmarks', required=True) - parser.add_argument( - '--isolated-script-test-output', required=True) - parser.add_argument( - '--isolated-script-test-perf-output', required=False) - return parser.parse_known_args()[0] - -def main_compile_targets(args): - json.dump([], args.output) - -if __name__ == '__main__': - # Conform minimally to the protocol defined by ScriptTest. - if 'compile_targets' in sys.argv: - funcs = { - 'run': None, - 'compile_targets': main_compile_targets, - } - sys.exit(common.run_script(sys.argv[1:], funcs)) - sys.exit(main())
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 03c1f783..9ed2669 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -7564,7 +7564,7 @@ ], "experiments": [ { - "name": "SideSearchDesktop", + "name": "Stable_Desktop_M102_SideSearchChromeOS_Enabled", "enable_features": [ "SidePanelImprovedClobbering", "SideSearchDSESupport" @@ -8813,6 +8813,11 @@ "experiments": [ { "name": "Vulkan", + "params": { + "BlockListByBoard": "RM67*|RM68*|k68*|mt6*|oppo67*|oppo68*|QM215|rk30sdk|secret|maltose|rosemary|HLTE322E*|lisbon|lancelot|Infinix-X695|g2062upt_v1_gd_sh2_gq_eea_r|cannong|TECNO-CG8", + "disable_by_gl_driver": "324.0|331.0|334.0|378.0|415.0|420.0|444.0", + "disable_by_gl_renderer": "*Mali-G72*|*Mali-G?? M*" + }, "enable_features": [ "Vulkan" ],
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 93c97cd1..68da461 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -1119,7 +1119,7 @@ // Allows read/write of custom formats with unsanitized clipboard content. See // crbug.com/106449. const base::Feature kClipboardCustomFormats{"ClipboardCustomFormats", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Uses page viewport instead of frame viewport in the Largest Contentful Paint // heuristic where images occupying the full viewport are ignored. @@ -1480,5 +1480,8 @@ const base::Feature kWebSQLNonSecureContextAccess{ "WebSQLNonSecureContextAccess", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kFileSystemUrlNavigation{"FileSystemUrlNavigation", + base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features } // namespace blink
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 20a86789..661dd35 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -770,6 +770,10 @@ // If enabled, allows the use of WebSQL in non-secure contexts. BLINK_COMMON_EXPORT extern const base::Feature kWebSQLNonSecureContextAccess; +// Switch to temporary turn back on file system url navigation. +// TODO(https://crbug.com/1332598): Remove this feature. +BLINK_COMMON_EXPORT extern const base::Feature kFileSystemUrlNavigation; + } // namespace features } // namespace blink
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index af57a94..e56d75ff 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -95,10 +95,6 @@ class GpuVideoAcceleratorFactories; } // namespace media -namespace mojo_base { -class BigBuffer; -} - namespace network { namespace mojom { class URLLoaderFactory; @@ -318,39 +314,6 @@ return blink::UserAgentMetadata(); } - // A request to cache code generated by the Renderer for the resource fetched - // from the given URL at the given response time. The cached code can be - // fetched on subsequent loads of the resource to speed up processing. The - // Browser may silently ignore this request if |size| is too large or storage - // isn't available. - virtual void CacheMetadata(blink::mojom::CodeCacheType cache_type, - const WebURL&, - base::Time response_time, - const uint8_t* data, - size_t data_size) {} - - // A request to fetch contents associated with this URL from metadata cache. - using FetchCachedCodeCallback = - base::OnceCallback<void(base::Time, mojo_base::BigBuffer)>; - // A request to fetch previously cached code for the resource fetched from the - // given URL. The code fetch should be made at the same time as the resource - // fetch so the Renderer can bypass code generation for the resource. - virtual void FetchCachedCode(blink::mojom::CodeCacheType cache_type, - const WebURL&, - FetchCachedCodeCallback) {} - virtual void ClearCodeCacheEntry(blink::mojom::CodeCacheType cache_type, - const GURL&) {} - - // A suggestion to cache this metadata in association with this URL which - // resource is in CacheStorage. - virtual void CacheMetadataInCacheStorage( - const WebURL&, - base::Time response_time, - const uint8_t* data, - size_t data_size, - const blink::WebSecurityOrigin& cache_storage_origin, - const WebString& cache_storage_cache_name) {} - // Determines whether it is safe to redirect from |from_url| to |to_url|. virtual bool IsRedirectSafe(const GURL& from_url, const GURL& to_url) { return false;
diff --git a/third_party/blink/public/web/modules/mediastream/media_stream_video_source.h b/third_party/blink/public/web/modules/mediastream/media_stream_video_source.h index cd8f032..e8eeb17 100644 --- a/third_party/blink/public/web/modules/mediastream/media_stream_video_source.h +++ b/third_party/blink/public/web/modules/mediastream/media_stream_video_source.h
@@ -193,6 +193,17 @@ const base::Token& crop_id, uint32_t crop_version, base::OnceCallback<void(media::mojom::CropRequestResult)> callback); + + // If a new |crop_version| can be assigned, returns it. + // Otherwise, returns nullopt. (Can happen if the source does not support + // cropping, or if a change of crop-target is not possible at this time, + // due to technical limitations, e.g. if clones exist.) + // + // For an explanation of what a |crop_version| is, see Crop(). + // + // TODO(crbug.com/1332628): Make the crop-version an implementation detail + // that is not exposed to the entity calling Crop(). + virtual absl::optional<uint32_t> GetNextCropVersion(); #endif // Notifies the source about that the number of encoded sinks have been
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h b/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h index a37ed68..cf987d076 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h +++ b/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h
@@ -75,11 +75,12 @@ kReadableStreamTransferTag = 'r', // index:uint32_t kTransformStreamTransferTag = 'm', // index:uint32_t kWritableStreamTransferTag = 'w', // index:uint32_t - kMediaStreamTrack = 's', // session_id.high:uint64_t, session_id.low:uint64_t, - // kind:WebCoreString, id:WebCoreString, - // label:WebCoreString, enabled:byte, muted:byte, - // contentHint:Uint32Enum, readyState:Uint32Enum - kDOMPointTag = 'Q', // x:Double, y:Double, z:Double, w:Double + kMediaStreamTrack = + 's', // session_id.high:uint64_t, session_id.low:uint64_t, + // kind:WebCoreString, id:WebCoreString, + // label:WebCoreString, enabled:byte, muted:byte, + // contentHint:Uint32Enum, readyState:Uint32Enum + kDOMPointTag = 'Q', // x:Double, y:Double, z:Double, w:Double kDOMPointReadOnlyTag = 'W', // x:Double, y:Double, z:Double, w:Double kDOMRectTag = 'E', // x:Double, y:Double, width:Double, height:Double kDOMRectReadOnlyTag = 'R', // x:Double, y:Double, width:Double, height:Double @@ -113,6 +114,8 @@ kEncodedAudioChunkTag = 'y', // uint32_t -> transferred chunk kEncodedVideoChunkTag = 'z', // uint32_t -> transferred chunk + kCropTargetTag = 'c', // crop_id:WebCoreString + // The following tags were used by the Shape Detection API implementation // between M71 and M81. During these milestones, the API was always behind // a flag. Usage was removed in https://crrev.com/c/2040378.
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc index db01613..64e944a 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc
@@ -19,6 +19,7 @@ #include "third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h" #include "third_party/blink/renderer/modules/filesystem/dom_file_system.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/media_stream_track.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_certificate.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_certificate_generator.h" @@ -94,6 +95,8 @@ return ReadEncodedVideoChunk(); case kMediaStreamTrack: return ReadMediaStreamTrack(); + case kCropTargetTag: + return ReadCropTarget(); default: break; } @@ -559,4 +562,18 @@ .ready_state = DeserializeReadyState(readyState)}); } +CropTarget* V8ScriptValueDeserializerForModules::ReadCropTarget() { + if (!RuntimeEnabledFeatures::RegionCaptureEnabled( + ExecutionContext::From(GetScriptState()))) { + return nullptr; + } + + String crop_id; + if (!ReadUTF8String(&crop_id)) { + return nullptr; + } + + return MakeGarbageCollected<CropTarget>(crop_id); +} + } // namespace blink
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h index af56602e..1d3adbf 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h
@@ -11,6 +11,7 @@ namespace blink { class AudioData; +class CropTarget; class CryptoKey; class EncodedAudioChunk; class EncodedVideoChunk; @@ -57,6 +58,7 @@ EncodedAudioChunk* ReadEncodedAudioChunk(); EncodedVideoChunk* ReadEncodedVideoChunk(); MediaStreamTrack* ReadMediaStreamTrack(); + CropTarget* ReadCropTarget(); }; } // namespace blink
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc index ef8b9f1..906e4c5e 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/bindings/modules/v8/serialization/serialized_track_params.h" #include "third_party/blink/renderer/bindings/modules/v8/serialization/web_crypto_sub_tags.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_data.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_crop_target.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_crypto_key.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_dom_file_system.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_encoded_audio_chunk.h" @@ -31,6 +32,7 @@ #include "third_party/blink/renderer/modules/crypto/crypto_key.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_handle.h" #include "third_party/blink/renderer/modules/filesystem/dom_file_system.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/media_stream_track.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_certificate.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_frame.h" @@ -238,6 +240,18 @@ return WriteMediaStreamTrack(wrappable->ToImpl<MediaStreamTrack>(), exception_state); } + if (wrapper_type_info == V8CropTarget::GetWrapperTypeInfo() && + RuntimeEnabledFeatures::RegionCaptureEnabled( + ExecutionContext::From(GetScriptState()))) { + if (IsForStorage()) { + exception_state.ThrowDOMException( + DOMExceptionCode::kDataCloneError, + "A CropTarget cannot be serialized for storage."); + return false; + } + + return WriteCropTarget(wrappable->ToImpl<CropTarget>()); + } return false; } @@ -526,4 +540,11 @@ return true; } +bool V8ScriptValueSerializerForModules::WriteCropTarget( + CropTarget* crop_target) { + WriteTag(kCropTargetTag); + WriteUTF8String(crop_target->GetCropId()); + return true; +} + } // namespace blink
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.h b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.h index 612a642..85a91b9 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.h +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.h
@@ -17,6 +17,7 @@ namespace blink { +class CropTarget; class FileSystemHandle; class RTCEncodedAudioFrame; class RTCEncodedVideoFrame; @@ -55,6 +56,7 @@ bool for_audio); bool WriteMediaStreamTrack(MediaStreamTrack* track, ExceptionState& exception_state); + bool WriteCropTarget(CropTarget*); }; } // namespace blink
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc index 21b4796a..8fc4d840 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_data.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_audio_data_copy_to_options.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_crop_target.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_crypto_key.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_dom_file_system.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_media_stream_track.h" @@ -33,6 +34,7 @@ #include "third_party/blink/renderer/modules/crypto/crypto_key.h" #include "third_party/blink/renderer/modules/crypto/crypto_result_impl.h" #include "third_party/blink/renderer/modules/filesystem/dom_file_system.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/media_stream_track.h" #include "third_party/blink/renderer/modules/mediastream/media_stream_track_impl.h" #include "third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h" @@ -1282,5 +1284,24 @@ "DataCloneError", scope.GetScriptState(), exception_state)); } +#if !BUILDFLAG(IS_ANDROID) // CropTarget is not exposed on Android. +TEST(V8ScriptValueSerializerForModulesTest, RoundTripCropTarget) { + V8TestingScope scope; + + const String crop_id("8e7e0c22-67a0-4c39-b4dc-a20433262f8e"); + + CropTarget* const crop_target = MakeGarbageCollected<CropTarget>(crop_id); + + v8::Local<v8::Value> wrapper = ToV8(crop_target, scope.GetScriptState()); + v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope); + + ASSERT_TRUE(V8CropTarget::HasInstance(result, scope.GetIsolate())); + + CropTarget* const new_crop_target = + V8CropTarget::ToImpl(result.As<v8::Object>()); + EXPECT_EQ(new_crop_target->GetCropId(), crop_id); +} +#endif + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/controller/blink_initializer.cc b/third_party/blink/renderer/controller/blink_initializer.cc index 79e4ce5..42158513 100644 --- a/third_party/blink/renderer/controller/blink_initializer.cc +++ b/third_party/blink/renderer/controller/blink_initializer.cc
@@ -54,6 +54,7 @@ #include "third_party/blink/renderer/core/execution_context/agent.h" #include "third_party/blink/renderer/core/frame/display_cutout_client_impl.h" #include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/html/parser/literal_buffer.h" #include "third_party/blink/renderer/platform/bindings/microtask.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" #include "third_party/blink/renderer/platform/disk_data_allocator.h" @@ -103,6 +104,11 @@ } }; +// See description of `g_literal_buffer_create_string_with_encoding` in +// LiteralBuffer as to what this controls. +const base::Feature kLiteralBufferCreateStringWithEncoding{ + "LiteralBufferCreateStringWithEncoding", base::FEATURE_DISABLED_BY_DEFAULT}; + Thread::TaskObserver* g_end_of_task_runner = nullptr; BlinkInitializer& GetBlinkInitializer() { @@ -172,6 +178,9 @@ // Initialize performance manager. RendererResourceCoordinatorImpl::MaybeInitialize(); + + g_literal_buffer_create_string_with_encoding = + base::FeatureList::IsEnabled(kLiteralBufferCreateStringWithEncoding); } } // namespace
diff --git a/third_party/blink/renderer/core/html/build.gni b/third_party/blink/renderer/core/html/build.gni index fff4491..c58faf4 100644 --- a/third_party/blink/renderer/core/html/build.gni +++ b/third_party/blink/renderer/core/html/build.gni
@@ -613,6 +613,7 @@ "parser/html_view_source_parser.cc", "parser/html_view_source_parser.h", "parser/input_stream_preprocessor.h", + "parser/literal_buffer.cc", "parser/literal_buffer.h", "parser/markup_tokenizer_inlines.h", "parser/parser_scripting_flag_policy.h",
diff --git a/third_party/blink/renderer/core/html/parser/html_parser_idioms.h b/third_party/blink/renderer/core/html/parser/html_parser_idioms.h index a06c05e..ed47cc7 100644 --- a/third_party/blink/renderer/core/html/parser/html_parser_idioms.h +++ b/third_party/blink/renderer/core/html/parser/html_parser_idioms.h
@@ -133,8 +133,14 @@ template <wtf_size_t inlineCapacity> inline static String AttemptStaticStringCreation( - const LiteralBuffer<UChar, inlineCapacity>& vector, + const UCharLiteralBuffer<inlineCapacity>& vector, CharacterWidth width) { + if (g_literal_buffer_create_string_with_encoding) { + // TODO(sky): once this is made the default, remove `width` parameter. + return AttemptStaticStringCreation( + vector.data(), vector.size(), + vector.Is8Bit() ? kForce8Bit : kForce16Bit); + } return AttemptStaticStringCreation(vector.data(), vector.size(), width); }
diff --git a/third_party/blink/renderer/core/html/parser/html_token.h b/third_party/blink/renderer/core/html/parser/html_token.h index 20e7b20..233c5f2 100644 --- a/third_party/blink/renderer/core/html/parser/html_token.h +++ b/third_party/blink/renderer/core/html/parser/html_token.h
@@ -124,10 +124,14 @@ bool NameIsEmpty() const { return name_.IsEmpty(); } void AppendToName(UChar c) { name_.AddChar(c); } - scoped_refptr<StringImpl> Value8BitIfNecessary() const { - return StringImpl::Create8BitIfPossible(value_.data(), value_.size()); + String Value8BitIfNecessary() const { + // TODO(sky): remove this function and convert callers to Value() once + // `g_literal_buffer_create_string_with_encoding` is removed. + if (!g_literal_buffer_create_string_with_encoding) + return StringImpl::Create8BitIfPossible(value_.data(), value_.size()); + return value_.AsString(); } - String Value() const { return String(value_.data(), value_.size()); } + String Value() const { return value_.AsString(); } void AppendToValue(UChar c) { value_.AddChar(c); } void ClearValue() { value_.clear(); } @@ -140,8 +144,8 @@ private: // TODO(chromium:1204030): Do a more rigorous study and select a // better-informed inline capacity. - LiteralBuffer<UChar, 32> name_; - LiteralBuffer<UChar, 32> value_; + UCharLiteralBuffer<32> name_; + UCharLiteralBuffer<32> value_; Range name_range_; Range value_range_; }; @@ -153,7 +157,7 @@ // around a number of popular web sites on 23 May 2013. // TODO(chromium:1204030): Do a more rigorous study and select a // better-informed inline capacity. - typedef LiteralBuffer<UChar, 256> DataVector; + using DataVector = UCharLiteralBuffer<256>; HTMLToken() { Clear(); } HTMLToken(const HTMLToken&) = delete; @@ -165,7 +169,6 @@ range_.start = 0; base_offset_ = 0; data_.clear(); - or_all_data_ = 0; } bool IsUninitialized() { return type_ == kUninitialized; } @@ -191,7 +194,7 @@ return data_; } - bool IsAll8BitData() const { return (or_all_data_ <= 0xff); } + bool IsAll8BitData() const { return data_.Is8Bit(); } const DataVector& GetName() const { DCHECK(type_ == kStartTag || type_ == kEndTag || type_ == DOCTYPE); @@ -202,7 +205,6 @@ DCHECK(type_ == kStartTag || type_ == kEndTag || type_ == DOCTYPE); DCHECK(character); data_.AddChar(character); - or_all_data_ |= character; } /* DOCTYPE Tokens */ @@ -227,7 +229,6 @@ DCHECK(character); BeginDOCTYPE(); data_.AddChar(character); - or_all_data_ |= character; } // FIXME: Distinguish between a missing public identifer and an empty one. @@ -293,7 +294,6 @@ attributes_.clear(); data_.AddChar(character); - or_all_data_ |= character; } void BeginEndTag(LChar character) { @@ -306,7 +306,7 @@ data_.AddChar(character); } - void BeginEndTag(const LiteralBuffer<LChar, 32>& characters) { + void BeginEndTag(const LCharLiteralBuffer<32>& characters) { DCHECK_EQ(type_, kUninitialized); type_ = kEndTag; self_closing_ = false; @@ -397,10 +397,9 @@ void AppendToCharacter(UChar character) { DCHECK_EQ(type_, kCharacter); data_.AddChar(character); - or_all_data_ |= character; } - void AppendToCharacter(const LiteralBuffer<LChar, 32>& characters) { + void AppendToCharacter(const LCharLiteralBuffer<32>& characters) { DCHECK_EQ(type_, kCharacter); data_.AppendLiteral(characters); } @@ -421,7 +420,6 @@ DCHECK(character); DCHECK_EQ(type_, kComment); data_.AddChar(character); - or_all_data_ |= character; } private: @@ -429,7 +427,6 @@ Attribute::Range range_; // Always starts at zero. int base_offset_; DataVector data_; - UChar or_all_data_; // For StartTag and EndTag bool self_closing_;
diff --git a/third_party/blink/renderer/core/html/parser/html_tokenizer.cc b/third_party/blink/renderer/core/html/parser/html_tokenizer.cc index bed4a53..3b76e97 100644 --- a/third_party/blink/renderer/core/html/parser/html_tokenizer.cc +++ b/third_party/blink/renderer/core/html/parser/html_tokenizer.cc
@@ -119,7 +119,7 @@ return cc | (IsASCIIUpper(cc) ? 0x20 : 0); } -static inline bool VectorEqualsString(const LiteralBuffer<LChar, 32>& vector, +static inline bool VectorEqualsString(const LCharLiteralBuffer<32>& vector, const String& string) { if (vector.size() != string.length()) return false;
diff --git a/third_party/blink/renderer/core/html/parser/html_tokenizer.h b/third_party/blink/renderer/core/html/parser/html_tokenizer.h index 5bce012d..f0c71f6 100644 --- a/third_party/blink/renderer/core/html/parser/html_tokenizer.h +++ b/third_party/blink/renderer/core/html/parser/html_tokenizer.h
@@ -274,15 +274,15 @@ // http://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream InputStreamPreprocessor<HTMLTokenizer> input_stream_preprocessor_; - LiteralBuffer<UChar, 32> appropriate_end_tag_name_; + UCharLiteralBuffer<32> appropriate_end_tag_name_; // http://www.whatwg.org/specs/web-apps/current-work/#temporary-buffer - LiteralBuffer<LChar, 32> temporary_buffer_; + LCharLiteralBuffer<32> temporary_buffer_; // We occationally want to emit both a character token and an end tag // token (e.g., when lexing script). We buffer the name of the end tag // token here so we remember it next time we re-enter the tokenizer. - LiteralBuffer<LChar, 32> buffered_end_tag_name_; + LCharLiteralBuffer<32> buffered_end_tag_name_; HTMLParserOptions options_; };
diff --git a/third_party/blink/renderer/core/html/parser/literal_buffer.cc b/third_party/blink/renderer/core/html/parser/literal_buffer.cc new file mode 100644 index 0000000..c4d0e026 --- /dev/null +++ b/third_party/blink/renderer/core/html/parser/literal_buffer.cc
@@ -0,0 +1,7 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/html/parser/literal_buffer.h" + +bool g_literal_buffer_create_string_with_encoding = true;
diff --git a/third_party/blink/renderer/core/html/parser/literal_buffer.h b/third_party/blink/renderer/core/html/parser/literal_buffer.h index 7de5ea1..941b8251 100644 --- a/third_party/blink/renderer/core/html/parser/literal_buffer.h +++ b/third_party/blink/renderer/core/html/parser/literal_buffer.h
@@ -12,7 +12,9 @@ #include "base/bits.h" #include "base/check_op.h" #include "base/compiler_specific.h" +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" @@ -24,45 +26,81 @@ #define BUFFER_INLINE_CAPACITY kInlineSize #endif -// LiteralBuffer is an optimized version of Vector for LChar and UChar +// Controls whether strings created by LiteralBuffer have an encoding specified. +// Specifying the encoding may avoid unnecessary allocations and checks to +// determine encoding, and allows for a fast path when copying UChars to +// LChars. +CORE_EXPORT extern bool g_literal_buffer_create_string_with_encoding; + +// LiteralBufferBase is an optimized version of Vector for LChar and UChar // characters. In particular `AddChar` is faster than `push_back`, since // it avoids unnecessary register spills. See https://crbug.com/1205338. +// Use one of the concrete implementations: LCharLiteralBuffer or +// UCharLiteralBuffer. template <typename T, wtf_size_t kInlineSize> -class LiteralBuffer { +class LiteralBufferBase { static_assert(std::is_same<LChar, T>::value || std::is_same<UChar, T>::value, "T must be a character type"); public: - LiteralBuffer() = default; - LiteralBuffer(const LiteralBuffer& other) { *this = other; } - LiteralBuffer(LiteralBuffer&& other) { *this = std::move(other); } - - ~LiteralBuffer() { + ~LiteralBufferBase() { if (!is_stored_inline()) WTF::Partitions::BufferFree(begin_); } + ALWAYS_INLINE const T* data() const { return begin_; } + ALWAYS_INLINE wtf_size_t size() const { + return base::checked_cast<wtf_size_t>(end_ - begin_); + } + + ALWAYS_INLINE bool IsEmpty() const { return size() == 0; } + + ALWAYS_INLINE const T& operator[](wtf_size_t index) const { + CHECK_GT(size(), index); + return begin_[index]; + } + + protected: + LiteralBufferBase() = default; + + // Clear without freeing any storage. + ALWAYS_INLINE void ClearImpl() { end_ = begin_; } + + ALWAYS_INLINE void AddCharImpl(T val) { + if (UNLIKELY(end_ == end_of_storage_)) + end_ = Grow(); + *end_++ = val; + } + + template <typename OtherT, wtf_size_t kOtherSize> + void AppendLiteralImpl(const LiteralBufferBase<OtherT, kOtherSize>& val) { + static_assert(sizeof(T) >= sizeof(OtherT), + "T is not big enough to contain OtherT"); + size_t count = val.size(); + size_t new_size = size() + count; + if (capacity() < new_size) + Grow(new_size); + std::copy_n(val.data(), count, end_); + end_ += count; + } + template <wtf_size_t kOtherInlineSize> - LiteralBuffer& operator=(const LiteralBuffer<T, kOtherInlineSize>& other) { - if (this->begin_ == other.data()) - return *this; + void Copy(const LiteralBufferBase<T, kOtherInlineSize>& other) { wtf_size_t other_size = other.size(); if (capacity() < other_size) { // Create large-enough heap-allocated storage. if (!is_stored_inline()) WTF::Partitions::BufferFree(begin_); begin_ = static_cast<T*>(WTF::Partitions::BufferMalloc( - AllocationSize(other_size), "LiteralBuffer")); + AllocationSize(other_size), "LiteralBufferBase")); end_of_storage_ = begin_ + other_size; } std::copy_n(other.data(), other_size, begin_); end_ = begin_ + other_size; - return *this; } - LiteralBuffer& operator=(LiteralBuffer&& other) { - if (this == &other) - return *this; + void Move(LiteralBufferBase&& other) { + DCHECK_NE(this, &other); if (!other.is_stored_inline()) { if (!is_stored_inline()) WTF::Partitions::BufferFree(begin_); @@ -78,62 +116,9 @@ std::copy_n(other.data(), other_size, begin_); end_ = begin_ + other_size; } - return *this; } - ALWAYS_INLINE const T* data() const { return begin_; } - ALWAYS_INLINE wtf_size_t size() const { - return base::checked_cast<wtf_size_t>(end_ - begin_); - } - - ALWAYS_INLINE bool IsEmpty() const { return size() == 0; } - - ALWAYS_INLINE const T& operator[](wtf_size_t index) const { - CHECK_GT(size(), index); - return begin_[index]; - } - - // Clear without freeing any storage. - ALWAYS_INLINE void clear() { end_ = begin_; } - - ALWAYS_INLINE void AddChar(T val) { - if (UNLIKELY(end_ == end_of_storage_)) - end_ = Grow(); - *end_++ = val; - } - - template <typename OtherT, wtf_size_t kOtherSize> - void AppendLiteral(const LiteralBuffer<OtherT, kOtherSize>& val) { - static_assert(sizeof(T) >= sizeof(OtherT), - "T is not big enough to contain OtherT"); - size_t count = val.size(); - size_t new_size = size() + count; - if (capacity() < new_size) - Grow(new_size); - std::copy_n(val.data(), count, end_); - end_ += count; - } - - String AsString() const { return String(data(), size()); } - - String AsString8() const { - if (std::is_same<T, LChar>::value) - return AsString(); - return String::Make8BitFrom16BitSource(data(), size()); - } - - AtomicString AsAtomicString() const { return AtomicString(data(), size()); } - private: - // NOTE: we use pointers to the beginning and the end of the buffer, instead - // of tuple (begin, size, capacity). This makes access of the next characters - // faster when `AddChar` is inlined, since `end_` is readily available in a - // register. - T* begin_ = &inline_storage[0]; - T* end_ = begin_; - T* end_of_storage_ = begin_ + BUFFER_INLINE_CAPACITY; - T inline_storage[BUFFER_INLINE_CAPACITY]; - size_t AllocationSize(size_t capacity) { return WTF::PartitionAllocator::QuantizedSize<T>(capacity); } @@ -165,7 +150,7 @@ size_t new_capacity = RoundUpToPowerOfTwo(std::max(min_capacity, 2 * capacity())); T* new_storage = static_cast<T*>(WTF::Partitions::BufferMalloc( - AllocationSize(new_capacity), "LiteralBuffer")); + AllocationSize(new_capacity), "LiteralBufferBase")); std::copy_n(begin_, in_use, new_storage); if (!is_stored_inline()) WTF::Partitions::BufferFree(begin_); @@ -174,6 +159,119 @@ end_of_storage_ = new_storage + new_capacity; return end_; } + + // NOTE: we use pointers to the beginning and the end of the buffer, instead + // of tuple (begin, size, capacity). This makes access of the next characters + // faster when `AddChar` is inlined, since `end_` is readily available in a + // register. + T* begin_ = &inline_storage[0]; + T* end_ = begin_; + T* end_of_storage_ = begin_ + BUFFER_INLINE_CAPACITY; + T inline_storage[BUFFER_INLINE_CAPACITY]; +}; + +template <wtf_size_t kInlineSize> +class LCharLiteralBuffer : public LiteralBufferBase<UChar, kInlineSize> { + public: + LCharLiteralBuffer() = default; + LCharLiteralBuffer(const LCharLiteralBuffer& other) { *this = other; } + LCharLiteralBuffer(LCharLiteralBuffer&& other) { *this = std::move(other); } + + ~LCharLiteralBuffer() = default; + + template <wtf_size_t kOtherInlineSize> + LCharLiteralBuffer& operator=( + const LCharLiteralBuffer<kOtherInlineSize>& other) { + if (this->data() != other.data()) + this->Copy(other); + return *this; + } + + LCharLiteralBuffer& operator=(LCharLiteralBuffer&& other) { + if (this != &other) + this->Move(std::move(other)); + return *this; + } + + // Clear without freeing any storage. + ALWAYS_INLINE void clear() { this->ClearImpl(); } + + ALWAYS_INLINE void AddChar(LChar val) { this->AddCharImpl(val); } + + String AsString() const { return String(this->data(), this->size()); } +}; + +template <wtf_size_t kInlineSize> +class UCharLiteralBuffer : public LiteralBufferBase<UChar, kInlineSize> { + public: + UCharLiteralBuffer() = default; + UCharLiteralBuffer(const UCharLiteralBuffer& other) { *this = other; } + UCharLiteralBuffer(UCharLiteralBuffer&& other) { *this = std::move(other); } + + ~UCharLiteralBuffer() = default; + + template <wtf_size_t kOtherInlineSize> + UCharLiteralBuffer& operator=( + const UCharLiteralBuffer<kOtherInlineSize>& other) { + if (this->data() == other.data()) + return *this; + this->Copy(other); + or_all_data_ = other.or_all_data_; + return *this; + } + + UCharLiteralBuffer& operator=(UCharLiteralBuffer&& other) { + if (this == &other) + return *this; + const UChar other_or_all_data = other.or_all_data_; + this->Move(std::move(other)); + or_all_data_ = other_or_all_data; + return *this; + } + + // Clear without freeing any storage. + ALWAYS_INLINE void clear() { + this->ClearImpl(); + or_all_data_ = 0; + } + + ALWAYS_INLINE void AddChar(UChar val) { + this->AddCharImpl(val); + or_all_data_ |= val; + } + + template <wtf_size_t kOtherSize> + void AppendLiteral(const LCharLiteralBuffer<kOtherSize>& val) { + this->AppendLiteralImpl(val); + } + + String AsString() const { + if (g_literal_buffer_create_string_with_encoding && Is8Bit()) + return String::Make8BitFrom16BitSource(this->data(), this->size()); + return String(this->data(), this->size()); + } + + String AsString8() const { + return String::Make8BitFrom16BitSource(this->data(), this->size()); + } + + AtomicString AsAtomicString() const { + if (!g_literal_buffer_create_string_with_encoding) + return AtomicString(this->data(), this->size()); + return AtomicString(this->data(), this->size(), + Is8Bit() ? WTF::AtomicStringUCharEncoding::kIs8Bit + : WTF::AtomicStringUCharEncoding::kIs16Bit); + } + + ALWAYS_INLINE bool Is8Bit() const { return or_all_data_ <= 0xFF; } + + private: + // Needed for operator=. + template <wtf_size_t kOtherInlineSize> + friend class UCharLiteralBuffer; + + // Bitwise-or of data added. Used to determine if contains only 8-bit values. + UChar or_all_data_ = 0; }; #undef BUFFER_INLINE_CAPACITY
diff --git a/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc b/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc index 8d428ac8..8193eb9 100644 --- a/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc +++ b/third_party/blink/renderer/core/html/parser/literal_buffer_test.cc
@@ -11,13 +11,13 @@ namespace { TEST(LiteralBufferTest, Empty) { - LiteralBuffer<LChar, 16> buf; + LCharLiteralBuffer<16> buf; EXPECT_TRUE(buf.IsEmpty()); EXPECT_EQ(0ul, buf.size()); } TEST(LiteralBufferTest, AddAndClear) { - LiteralBuffer<LChar, 16> buf; + LCharLiteralBuffer<16> buf; buf.AddChar('a'); buf.AddChar('b'); buf.AddChar('c'); @@ -33,12 +33,12 @@ } TEST(LiteralBufferTest, AppendLiteral) { - LiteralBuffer<LChar, 16> lit; + LCharLiteralBuffer<16> lit; lit.AddChar('a'); lit.AddChar('b'); lit.AddChar('c'); - LiteralBuffer<UChar, 4> buf; + UCharLiteralBuffer<4> buf; buf.AddChar('d'); buf.AddChar('e'); buf.AddChar('f'); @@ -50,12 +50,12 @@ } TEST(LiteralBufferTest, Copy) { - LiteralBuffer<LChar, 16> lit; + LCharLiteralBuffer<16> lit; lit.AddChar('a'); lit.AddChar('b'); lit.AddChar('c'); - LiteralBuffer<LChar, 2> buf; + LCharLiteralBuffer<2> buf; buf = lit; EXPECT_FALSE(buf.IsEmpty()); @@ -74,21 +74,37 @@ } TEST(LiteralBufferTest, Move) { - LiteralBuffer<LChar, 2> lit; + LCharLiteralBuffer<2> lit; lit.AddChar('a'); lit.AddChar('b'); lit.AddChar('c'); - LiteralBuffer<LChar, 2> buf(std::move(lit)); + LCharLiteralBuffer<2> buf(std::move(lit)); EXPECT_FALSE(buf.IsEmpty()); EXPECT_EQ(3ul, buf.size()); EXPECT_EQ(buf[0], 'a'); EXPECT_EQ(buf[1], 'b'); EXPECT_EQ(buf[2], 'c'); +} - EXPECT_TRUE(lit.IsEmpty()); - EXPECT_EQ(0ul, lit.size()); +TEST(LiteralBufferTest, Is8BitAppend) { + UCharLiteralBuffer<16> buf; + EXPECT_TRUE(buf.Is8Bit()); + buf.AddChar('a'); + EXPECT_TRUE(buf.Is8Bit()); + buf.AddChar(U'\x01D6'); + EXPECT_FALSE(buf.Is8Bit()); + buf.clear(); + EXPECT_TRUE(buf.Is8Bit()); +} + +TEST(LiteralBufferTest, Is8BitMove) { + UCharLiteralBuffer<16> buf; + buf.AddChar(U'\x01D6'); + + UCharLiteralBuffer<16> buf2(std::move(buf)); + EXPECT_FALSE(buf2.Is8Bit()); } } // anonymous namespace
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index bec81d2c..54ccee3 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -1561,7 +1561,12 @@ for (NGInlineCursor cursor(container, items); cursor; cursor.MoveToNext()) { if (const NGPhysicalBoxFragment* child = cursor.Current().BoxFragment()) { // Replaced elements and inline blocks need Location() set relative to - // their block container. + // their block container. Similarly for block-in-inline anonymous wrapper + // blocks, but those may actually fragment, so we need to make sure that + // we only do this when at the first fragment. + if (!child->IsFirstForNode()) + continue; + LayoutObject* layout_object = child->GetMutableLayoutObject(); if (!layout_object) continue;
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index 5fdcc5a..3d51c15a 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -660,6 +660,18 @@ if (!AllowRequestForThisFrame(request)) return; + // Block renderer-initiated loads of filesystem: URLs. + if (url.ProtocolIs("filesystem") && + !base::FeatureList::IsEnabled(features::kFileSystemUrlNavigation)) { + frame_->GetDocument()->AddConsoleMessage( + MakeGarbageCollected<ConsoleMessage>( + mojom::blink::ConsoleMessageSource::kSecurity, + mojom::blink::ConsoleMessageLevel::kError, + "Not allowed to navigate to " + url.Protocol() + + " URL: " + url.ElidedString())); + return; + } + // Block renderer-initiated loads of data: and filesystem: URLs in the top // frame (unless they are reload requests). // @@ -677,8 +689,8 @@ network_utils::IsDataURLMimeTypeSupported(url)))) { frame_->GetDocument()->AddConsoleMessage( MakeGarbageCollected<ConsoleMessage>( - mojom::ConsoleMessageSource::kSecurity, - mojom::ConsoleMessageLevel::kError, + mojom::blink::ConsoleMessageSource::kSecurity, + mojom::blink::ConsoleMessageLevel::kError, "Not allowed to navigate top frame to " + url.Protocol() + " URL: " + url.ElidedString())); return;
diff --git a/third_party/blink/renderer/core/timing/window_performance.cc b/third_party/blink/renderer/core/timing/window_performance.cc index 8bef2d82..0fb71fca 100644 --- a/third_party/blink/renderer/core/timing/window_performance.cc +++ b/third_party/blink/renderer/core/timing/window_performance.cc
@@ -494,11 +494,29 @@ input_delay, processing_time, time_to_next_paint, entry->name()); } + // Event Timing + ResponsivenessMetrics::EventTimestamps event_timestamps = { + event_timestamp, presentation_timestamp}; + // The page visibility was changed. In this case, we don't care about + // the time to next paint. + if (last_visibility_change_timestamp_ > event_timestamp && + last_visibility_change_timestamp_ <= presentation_timestamp) { + event_timestamps.end_time -= time_to_next_paint; + } + if (SetInteractionIdAndRecordLatency(entry, key_code, pointer_id, + event_timestamps)) { + NotifyAndAddEventTimingBuffer(entry); + }; + + // First Input if (!first_input_timing_) { if (entry->name() == event_type_names::kPointerdown) { first_pointer_down_event_timing_ = PerformanceEventTiming::CreateFirstInputTiming(entry); - } else if (entry->name() == event_type_names::kPointerup) { + } else if (entry->name() == event_type_names::kPointerup && + first_pointer_down_event_timing_) { + first_pointer_down_event_timing_->SetInteractionId( + entry->interactionId()); DispatchFirstInputTiming(first_pointer_down_event_timing_); } else if (entry->name() == event_type_names::kPointercancel) { first_pointer_down_event_timing_.Clear(); @@ -510,20 +528,6 @@ PerformanceEventTiming::CreateFirstInputTiming(entry)); } } - ResponsivenessMetrics::EventTimestamps event_timestamps = { - event_timestamp, presentation_timestamp}; - // The page visibility was changed. In this case, we don't care about - // the time to next paint. - if (last_visibility_change_timestamp_ > event_timestamp && - last_visibility_change_timestamp_ <= presentation_timestamp) { - event_timestamps.end_time -= time_to_next_paint; - } - if (!SetInteractionIdAndRecordLatency(entry, key_code, pointer_id, - event_timestamps)) { - continue; - } - - NotifyAndAddEventTimingBuffer(entry); } if (RuntimeEnabledFeatures::InteractionIdEnabled(GetExecutionContext())) {
diff --git a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.cc b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.cc index a3ee26a..9ef9b9e 100644 --- a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.cc +++ b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.cc
@@ -152,10 +152,12 @@ ScriptPromise BrowserCaptureMediaStreamTrack::cropTo( ScriptState* script_state, - const String& crop_id, + CropTarget* crop_target, ExceptionState& exception_state) { DCHECK(IsMainThread()); + const String crop_id(crop_target ? crop_target->GetCropId() : String()); + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); @@ -166,8 +168,6 @@ return promise; #else - // TODO(crbug.com/1298159): Reject cropTo() on clones. - const absl::optional<base::Token> crop_id_token = CropIdStringToToken(crop_id); if (!crop_id_token.has_value()) { @@ -177,8 +177,6 @@ return promise; } - pending_promises_.Set(++current_crop_version_, resolver); - // We don't currently instantiate BrowserCaptureMediaStreamTrack for audio // tracks. If we do in the future, we'll have to raise an exception if // cropTo() is called on a non-video track. @@ -190,10 +188,23 @@ MediaStreamVideoSource::GetVideoSource(source); DCHECK(native_source); + // TODO(crbug.com/1332628): Instead of using GetNextCropVersion(), move the + // ownership of the Promises from this->pending_promises_ into native_source. + const absl::optional<uint32_t> crop_version = + native_source->GetNextCropVersion(); + if (!crop_version.has_value()) { + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kOperationError, + "Can't change crop-target while clones exist.")); + return promise; + } + + pending_promises_.Set(crop_version.value(), resolver); + native_source->Crop( - crop_id_token.value(), current_crop_version_, + crop_id_token.value(), crop_version.value(), WTF::Bind(&BrowserCaptureMediaStreamTrack::ResolveCropPromise, - WrapPersistent(this), current_crop_version_)); + WrapPersistent(this), crop_version.value())); return promise; #endif @@ -208,25 +219,12 @@ GetReadyState(), base::DoNothing(), descriptor_id(), /*is_clone=*/true); - // Copy state. + // Copy state. (Note: Invokes FocusableMediaStreamTrack::CloneInternal().) CloneInternal(cloned_track); return cloned_track; } -void BrowserCaptureMediaStreamTrack::CloneInternal( - BrowserCaptureMediaStreamTrack* cloned_track) { - // Clone parent classes' state. - FocusableMediaStreamTrack::CloneInternal(cloned_track); - - // Clone this class's state. -#if !BUILDFLAG(IS_ANDROID) - // Note that cropTo() cannot be called on a clone, but we still copy, - // for completeness' sake. - current_crop_version_ = cloned_track->current_crop_version_; -#endif -} - #if !BUILDFLAG(IS_ANDROID) void BrowserCaptureMediaStreamTrack::ResolveCropPromise( uint32_t crop_version,
diff --git a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.h b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.h index 1b6d28a..05021fa 100644 --- a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.h +++ b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_BROWSER_CAPTURE_MEDIA_STREAM_TRACK_H_ #include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/focusable_media_stream_track.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_hash_map.h" @@ -34,20 +35,11 @@ void Trace(Visitor*) const override; #endif - ScriptPromise cropTo(ScriptState*, const String&, ExceptionState&); + ScriptPromise cropTo(ScriptState*, CropTarget*, ExceptionState&); BrowserCaptureMediaStreamTrack* clone(ScriptState*) override; private: - // Given a partially built MediaStreamTrack, finishes the job of making it - // into a clone of |this|. - // Useful for sub-classes (caveat below), as they need to clone both state - // from this class as well as of their own class. - // Caveat: This class is final, and has no sub-classes. We continue the - // pattern from the parent classes for clarity, and to make things easier - // if we do in the future sub-class further. - void CloneInternal(BrowserCaptureMediaStreamTrack*); - #if !BUILDFLAG(IS_ANDROID) // Resolves the Promise associated with |crop_version|. void ResolveCropPromise(uint32_t crop_version, @@ -63,7 +55,6 @@ // Note that frames before the first call to cropTo() will be associated // with a version of 0, both here and in Viz. HeapHashMap<uint32_t, Member<ScriptPromiseResolver>> pending_promises_; - uint32_t current_crop_version_ = 0; #endif // !BUILDFLAG(IS_ANDROID) };
diff --git a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.idl b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.idl index 267d41e4..6a72080 100644 --- a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.idl +++ b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track.idl
@@ -13,9 +13,9 @@ // Return a Promise that resolves once cropping has been fully initiated // and the browser guarantees all subsequent frames produced on this track // will be cropped. - // 2. If |cropTarget| is empty, stop cropping. + // 2. If |cropTarget| is |undefined|, stop cropping. // Return a Promise that resolves when this instruction has been fully // propagated and subsequent frames are guaranteed to be uncropped. [CallWith = ScriptState, RaisesException, MeasureAs = RegionCapture] - Promise<void> cropTo(DOMString crop_id); + Promise<void> cropTo(CropTarget? crop_id); };
diff --git a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track_test.cc b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track_test.cc index d82ababc..1d49522 100644 --- a/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track_test.cc +++ b/third_party/blink/renderer/modules/mediastream/browser_capture_media_stream_track_test.cc
@@ -9,6 +9,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/web/web_heap.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h" #include "third_party/blink/renderer/platform/region_capture_crop_id.h" @@ -17,6 +18,7 @@ namespace { using ::testing::_; +using ::testing::Return; std::unique_ptr<MockMediaStreamVideoSource> MakeMockMediaStreamVideoSource() { return base::WrapUnique(new MockMediaStreamVideoSource( @@ -58,32 +60,21 @@ std::unique_ptr<MockMediaStreamVideoSource> media_stream_video_source = MakeMockMediaStreamVideoSource(); + EXPECT_CALL(*media_stream_video_source, GetNextCropVersion) + .Times(1) + .WillOnce(Return(absl::optional<uint32_t>(1))); + EXPECT_CALL(*media_stream_video_source, Crop(GUIDToToken(valid_id), _, _)) .Times(1); BrowserCaptureMediaStreamTrack* const track = MakeTrack(v8_scope, std::move(media_stream_video_source)); - const ScriptPromise promise = track->cropTo( - v8_scope.GetScriptState(), WTF::String(valid_id.AsLowercaseString()), - v8_scope.GetExceptionState()); -} - -TEST_F(BrowserCaptureMediaStreamTrackTest, CropToInvalidIdIsRejected) { - V8TestingScope v8_scope; - - std::unique_ptr<MockMediaStreamVideoSource> media_stream_video_source = - MakeMockMediaStreamVideoSource(); - - EXPECT_CALL(*media_stream_video_source, Crop(_, _, _)).Times(0); - - BrowserCaptureMediaStreamTrack* const track = - MakeTrack(v8_scope, std::move(media_stream_video_source)); - const ScriptPromise promise = - track->cropTo(v8_scope.GetScriptState(), WTF::String("INVALID-ID"), + track->cropTo(v8_scope.GetScriptState(), + MakeGarbageCollected<CropTarget>( + WTF::String(valid_id.AsLowercaseString())), v8_scope.GetExceptionState()); - EXPECT_EQ(promise.V8Promise()->State(), v8::Promise::kRejected); } #else @@ -101,9 +92,11 @@ BrowserCaptureMediaStreamTrack* const track = MakeTrack(v8_scope, std::move(media_stream_video_source)); - const ScriptPromise promise = track->cropTo( - v8_scope.GetScriptState(), WTF::String(valid_id.AsLowercaseString()), - v8_scope.GetExceptionState()); + const ScriptPromise promise = + track->cropTo(v8_scope.GetScriptState(), + MakeGarbageCollected<CropTarget>( + WTF::String(valid_id.AsLowercaseString())), + v8_scope.GetExceptionState()); EXPECT_EQ(promise.V8Promise()->State(), v8::Promise::kRejected); } #endif
diff --git a/third_party/blink/renderer/modules/mediastream/crop_target.cc b/third_party/blink/renderer/modules/mediastream/crop_target.cc index 1b0d131f..6586bea 100644 --- a/third_party/blink/renderer/modules/mediastream/crop_target.cc +++ b/third_party/blink/renderer/modules/mediastream/crop_target.cc
@@ -12,8 +12,6 @@ namespace blink { -CropTarget::CropTarget() = default; - ScriptPromise CropTarget::fromElement(ScriptState* script_state, Element* element, ExceptionState& exception_state) { @@ -74,4 +72,8 @@ #endif } +CropTarget::CropTarget(String crop_id) : crop_id_(std::move(crop_id)) { + DCHECK(!crop_id_.IsEmpty()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/mediastream/crop_target.h b/third_party/blink/renderer/modules/mediastream/crop_target.h index 059c540d..723d9a6 100644 --- a/third_party/blink/renderer/modules/mediastream/crop_target.h +++ b/third_party/blink/renderer/modules/mediastream/crop_target.h
@@ -22,8 +22,17 @@ Element* element, ExceptionState& exception_state); + // Not Web-exposed. + explicit CropTarget(String crop_id); + + // The crop-ID is a UUID. CropTarget wraps it and abstracts it away for JS, + // but internally, the implementation is based on this implementation detail. + const String& GetCropId() const { return crop_id_; } + private: - CropTarget(); + // TODO(crbug.com/1332628): Wrap the base::Token instead of wrapping its + // string representation. + const String crop_id_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/mediastream/crop_target.idl b/third_party/blink/renderer/modules/mediastream/crop_target.idl index eac1f9a..0e5f7eac 100644 --- a/third_party/blink/renderer/modules/mediastream/crop_target.idl +++ b/third_party/blink/renderer/modules/mediastream/crop_target.idl
@@ -6,11 +6,10 @@ [Exposed=(Window,Worker), Serializable, RuntimeEnabled = RegionCapture] interface CropTarget { - // TODO(crbug.com/1291140): Change the return-type to Promise<CropTarget>. [ CallWith = ScriptState, RaisesException, MeasureAs = RegionCapture, RuntimeEnabled = RegionCapture - ] static Promise<DOMString> fromElement(Element element); + ] static Promise<CropTarget> fromElement(Element element); };
diff --git a/third_party/blink/renderer/modules/mediastream/media_devices.cc b/third_party/blink/renderer/modules/mediastream/media_devices.cc index e5c75b40..4057d2f 100644 --- a/third_party/blink/renderer/modules/mediastream/media_devices.cc +++ b/third_party/blink/renderer/modules/mediastream/media_devices.cc
@@ -32,6 +32,7 @@ #include "third_party/blink/renderer/core/frame/navigator.h" #include "third_party/blink/renderer/core/frame/web_feature.h" #include "third_party/blink/renderer/core/html/html_element.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/modules/mediastream/identifiability_metrics.h" #include "third_party/blink/renderer/modules/mediastream/input_device_info.h" #include "third_party/blink/renderer/modules/mediastream/media_error_state.h" @@ -118,12 +119,6 @@ #if !BUILDFLAG(IS_ANDROID) // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. -// -// Note: The mismatch between "CropId" and "CropTarget" is due to spec-changes -// as part of the work in the W3C working group. These will be reflected in -// code at a later point. -// TODO(crbug.com/1291140): Remove above explanation once implementation -// is updated to CropTargets. enum class ProduceCropTargetFunctionResult { kPromiseProduced = 0, kGenericError = 1, @@ -440,8 +435,8 @@ DCHECK(!old_crop_id->value().is_zero()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); const ScriptPromise promise = resolver->Promise(); - resolver->Resolve(WTF::String( - blink::TokenToGUID(old_crop_id->value()).AsLowercaseString())); + resolver->Resolve(MakeGarbageCollected<CropTarget>(WTF::String( + blink::TokenToGUID(old_crop_id->value()).AsLowercaseString()))); RecordUma( ProduceCropTargetFunctionResult::kDuplicateCallAfterPromiseResolution); return promise; @@ -787,7 +782,7 @@ DCHECK(guid.is_valid()); element->SetRegionCaptureCropId( std::make_unique<RegionCaptureCropId>(blink::GUIDToToken(guid))); - resolver->Resolve(crop_id); + resolver->Resolve(MakeGarbageCollected<CropTarget>(crop_id)); RecordUma(ProduceCropTargetPromiseResult::kPromiseResolved); } }
diff --git a/third_party/blink/renderer/modules/mediastream/media_devices_test.cc b/third_party/blink/renderer/modules/mediastream/media_devices_test.cc index 0242818..3999cf9 100644 --- a/third_party/blink/renderer/modules/mediastream/media_devices_test.cc +++ b/third_party/blink/renderer/modules/mediastream/media_devices_test.cc
@@ -18,11 +18,13 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_capture_handle_config.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_crop_target.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_media_stream_constraints.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/testing/null_execution_context.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" +#include "third_party/blink/renderer/modules/mediastream/crop_target.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" @@ -874,10 +876,11 @@ EXPECT_TRUE(tester.IsFulfilled()); EXPECT_FALSE(scope.GetExceptionState().HadException()); - WTF::String result; - tester.Value().ToString(result); - EXPECT_TRUE(result.ContainsOnlyASCIIOrEmpty()); - EXPECT_TRUE(base::GUID::ParseLowercase(result.Ascii()).is_valid()); + const CropTarget* const crop_target = + V8CropTarget::ToImpl(tester.Value().V8Value().As<v8::Object>()); + const WTF::String& crop_id = crop_target->GetCropId(); + EXPECT_TRUE(crop_id.ContainsOnlyASCIIOrEmpty()); + EXPECT_TRUE(base::GUID::ParseLowercase(crop_id.Ascii()).is_valid()); } #endif
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.cc b/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.cc index 20ab2d4..a35ef2a 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.cc
@@ -219,6 +219,13 @@ GetMediaStreamDispatcherHost()->Crop(session_id.value(), crop_id, crop_version, std::move(callback)); } + +absl::optional<uint32_t> MediaStreamVideoCapturerSource::GetNextCropVersion() { + if (NumTracks() != 1) { + return absl::nullopt; + } + return ++current_crop_version_; +} #endif base::WeakPtr<MediaStreamVideoSource>
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.h b/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.h index d20d86d..0b0577d 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.h +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_capturer_source.h
@@ -93,6 +93,7 @@ uint32_t crop_version, base::OnceCallback<void(media::mojom::CropRequestResult)> callback) override; + absl::optional<uint32_t> GetNextCropVersion() override; #endif base::WeakPtr<MediaStreamVideoSource> GetWeakPtr() const override; @@ -124,6 +125,17 @@ VideoCaptureDeliverFrameCB frame_callback_; DeviceCapturerFactoryCallback device_capturer_factory_callback_; + // Each time Crop() is called, the source crop version increments. + // Associate each Promise with its crop version, so that Viz can easily stamp + // each frame. When we see the first such frame, or an equivalent message, + // we can resolve the Promise. (An "equivalent message" can be a notification + // of a dropped frame, or a notification that a frame was not produced due + // to consisting of 0 pixels after the crop was applied, or anything similar.) + // + // Note that frames before the first call to cropTo() will be associated + // with a version of 0, both here and in Viz. + uint32_t current_crop_version_ = 0; + base::WeakPtrFactory<MediaStreamVideoSource> weak_factory_{this}; };
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc b/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc index 1cd6ad1..4f00f3ee 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc
@@ -538,6 +538,10 @@ base::OnceCallback<void(media::mojom::CropRequestResult)> callback) { std::move(callback).Run(media::mojom::CropRequestResult::kErrorGeneric); } + +absl::optional<uint32_t> MediaStreamVideoSource::GetNextCropVersion() { + return absl::nullopt; +} #endif VideoCaptureFeedbackCB MediaStreamVideoSource::GetFeedbackCallback() const {
diff --git a/third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h b/third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h index 7e2f087..f2764b6fb 100644 --- a/third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h +++ b/third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h
@@ -37,6 +37,7 @@ void(const base::Token&, uint32_t, base::OnceCallback<void(media::mojom::CropRequestResult)>)); + MOCK_METHOD0(GetNextCropVersion, absl::optional<uint32_t>()); // Simulate that the underlying source start successfully. void StartMockedSource();
diff --git a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc index c0723af9..e15963f8 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc +++ b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc
@@ -19,18 +19,15 @@ #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_picture_in_picture_window_options.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/events/event.h" -#include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" #include "third_party/blink/renderer/core/html/media/html_media_element.h" #include "third_party/blink/renderer/core/html/media/html_video_element.h" #include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_event.h" -#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" @@ -294,6 +291,11 @@ resolver->Resolve(); } +PictureInPictureWindow* PictureInPictureControllerImpl::pictureInPictureWindow() + const { + return picture_in_picture_window_; +} + Element* PictureInPictureControllerImpl::PictureInPictureElement() const { return picture_in_picture_element_; } @@ -412,6 +414,12 @@ auto* local_dom_window = dom_window->ToLocalDOMWindow(); DCHECK(local_dom_window); + // Set the Picture-in-Picture window's base URL to be the same as the opener + // window's so that relative URLs will be resolved in the same way. + DCHECK(local_dom_window->document()); + local_dom_window->document()->SetBaseURLOverride( + opener.document()->BaseURL()); + // TODO(https://crbug.com/1329638): Return a type specific to document pip // instead of a shared interface between the two APIs. picture_in_picture_window_ = MakeGarbageCollected<PictureInPictureWindow>(
diff --git a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h index 46253c0..085ba7c 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h +++ b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h
@@ -7,10 +7,13 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "third_party/blink/public/mojom/picture_in_picture/picture_in_picture.mojom-blink.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_picture_in_picture_window_options.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/picture_in_picture_controller.h" #include "third_party/blink/renderer/core/page/page_visibility_observer.h" #include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_deque.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" @@ -59,6 +62,9 @@ // request Picture-in-Picture. Status IsDocumentAllowed(bool report_failure) const; + // Returns the Picture-in-Picture window if there is any. + PictureInPictureWindow* pictureInPictureWindow() const; + // Returns element currently in Picture-in-Picture if any. Null otherwise. Element* PictureInPictureElement() const; Element* PictureInPictureElement(TreeScope&) const;
diff --git a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc index de17474..d7aa5c58 100644 --- a/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc +++ b/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_test.cc
@@ -14,7 +14,6 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" -#include "third_party/blink/public/mojom/picture_in_picture/picture_in_picture.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" @@ -478,4 +477,59 @@ EXPECT_EQ(Service().source_bounds(), Video()->BoundsInViewport()); } +TEST_F(PictureInPictureControllerTest, CreateDocumentPictureInPictureWindow) { + EXPECT_EQ(nullptr, PictureInPictureControllerImpl::From(GetDocument()) + .pictureInPictureWindow()); + + // Enable the PictureInPictureV2 flag. + ScopedPictureInPictureAPIForTest scoped_dependency(true); + ScopedPictureInPictureV2ForTest scoped_feature(true); + + V8TestingScope scope; + KURL url = KURL("https://example.com/"); + + // Get pass the LocalDOMWindow::isSecureContext() check. + GetFrame().DomWindow()->GetSecurityContext().SetSecurityOriginForTesting( + nullptr); + GetFrame().DomWindow()->GetSecurityContext().SetSecurityOrigin( + SecurityOrigin::Create(url)); + + // Get pass the BindingSecurity::ShouldAllowAccessTo() check. + ScriptState* script_state = + ToScriptStateForMainWorld(GetDocument().GetFrame()); + ScriptState::Scope entered_context_scope(script_state); + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + + // Create the PictureInPictureWindowOptions. + v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate()); + v8_object + ->Set(scope.GetContext(), V8String(scope.GetIsolate(), "width"), + v8::Number::New(scope.GetIsolate(), 640)) + .Check(); + v8_object + ->Set(scope.GetContext(), V8String(scope.GetIsolate(), "height"), + v8::Number::New(scope.GetIsolate(), 320)) + .Check(); + PictureInPictureWindowOptions* options = + PictureInPictureWindowOptions::Create(resolver->Promise().GetIsolate(), + v8_object, + scope.GetExceptionState()); + + // Set a base URL for the opener window. + GetDocument().SetBaseURLOverride(url); + EXPECT_EQ(url.GetString(), GetDocument().BaseURL().GetString()); + + PictureInPictureControllerImpl::From(GetDocument()) + .CreateDocumentPictureInPictureWindow( + script_state, *GetFrame().DomWindow(), options, resolver, + scope.GetExceptionState()); + + PictureInPictureWindow* pictureInPictureWindow = + PictureInPictureControllerImpl::From(GetDocument()) + .pictureInPictureWindow(); + EXPECT_NE(nullptr, pictureInPictureWindow); + EXPECT_EQ(url.GetString(), + pictureInPictureWindow->document()->BaseURL().GetString()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc index 3b00e8a..db71e27f 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -526,14 +526,16 @@ // around all of the effects. SwitchToTransform(effect.LocalTransformSpace().Unalias()); - // We always create separate effect nodes for normal effects and filter - // effects, so we can handle them separately. bool has_filter = !effect.Filter().IsEmpty(); bool has_opacity = effect.Opacity() != 1.f; + // TODO(crbug.com/1334293): Normally backdrop filters should be composited and + // effect.BackdropFilter() should be null, but compositing can be disabled in + // rare cases such as PaintPreview. For now non-composited backdrop filters + // are not supported and are ignored. bool has_other_effects = effect.BlendMode() != SkBlendMode::kSrcOver; + // We always create separate effect nodes for normal effects and filter + // effects, so we can handle them separately. DCHECK(!has_filter || !(has_opacity || has_other_effects)); - // We always composite backdrop filters. - DCHECK(!effect.BackdropFilter()); // Apply effects. cc_list_.StartPaint();
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer_test.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer_test.cc index 1b4e58e..442cad6 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer_test.cc
@@ -1418,5 +1418,25 @@ layer->capture_bounds().bounds().find(kThirdCropId.value())->second); } +TEST_P(PaintChunksToCcLayerTest, NonCompositedBackdropFilter) { + CompositorFilterOperations filter; + filter.AppendBlurFilter(5); + auto e1 = CreateBackdropFilterEffect(e0(), filter); + TestChunks chunks; + chunks.AddChunk(t0(), c0(), *e1, gfx::Rect(0, 0, 50, 50)); + + sk_sp<PaintRecord> output = + PaintChunksToCcLayer::Convert( + chunks.Build(), PropertyTreeState::Root(), gfx::Vector2dF(), + cc::DisplayItemList::kToBeReleasedAsPaintOpBuffer) + ->ReleaseAsRecord(); + // TODO(crbug.com/1334293): For now non-composited backdrop filters are + // ignored. + EXPECT_THAT(*output, + PaintRecordMatcher::Make({cc::PaintOpType::SaveLayerAlpha, + cc::PaintOpType::DrawRecord, + cc::PaintOpType::Restore})); +} + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/cached_metadata_handler.cc b/third_party/blink/renderer/platform/loader/fetch/url_loader/cached_metadata_handler.cc index 0ce5ac47..5ba44b03 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/cached_metadata_handler.cc +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/cached_metadata_handler.cc
@@ -48,18 +48,13 @@ void CachedMetadataSenderImpl::Send(CodeCacheHost* code_cache_host, const uint8_t* data, size_t size) { - if (code_cache_host) { - // TODO(crbug.com/862940): This should use the Blink variant of the - // interface. - code_cache_host->get()->DidGenerateCacheableMetadata( - code_cache_type_, GURL(response_url_), response_time_, - mojo_base::BigBuffer(base::make_span(data, size))); - } else { - // TODO(mythria): Update worklets to use the correct code_cache_host - // interface and remove this path. - Platform::Current()->CacheMetadata(code_cache_type_, response_url_, - response_time_, data, size); - } + if (!code_cache_host) + return; + // TODO(crbug.com/862940): This should use the Blink variant of the + // interface. + code_cache_host->get()->DidGenerateCacheableMetadata( + code_cache_type_, GURL(response_url_), response_time_, + mojo_base::BigBuffer(base::make_span(data, size))); } // This is a CachedMetadataSender implementation that does nothing. @@ -103,18 +98,12 @@ void ServiceWorkerCachedMetadataSender::Send(CodeCacheHost* code_cache_host, const uint8_t* data, size_t size) { - if (code_cache_host) { - code_cache_host->get()->DidGenerateCacheableMetadataInCacheStorage( - GURL(response_url_), response_time_, - mojo_base::BigBuffer(base::make_span(data, size)), - WebSecurityOrigin(security_origin_), cache_storage_cache_name_.Utf8()); - } else { - // TODO(mythria): Update worklets to use the correct code_cache_host - // interface and remove this path. - Platform::Current()->CacheMetadataInCacheStorage( - response_url_, response_time_, data, size, - WebSecurityOrigin(security_origin_), cache_storage_cache_name_); - } + if (!code_cache_host) + return; + code_cache_host->get()->DidGenerateCacheableMetadataInCacheStorage( + GURL(response_url_), response_time_, + mojo_base::BigBuffer(base::make_span(data, size)), + WebSecurityOrigin(security_origin_), cache_storage_cache_name_.Utf8()); } // static @@ -127,28 +116,17 @@ const String& cache_storage_name, const uint8_t* data, size_t size) { - if (code_cache_host) { - if (cache_storage_name.IsNull()) { - code_cache_host->get()->DidGenerateCacheableMetadata( - code_cache_type, GURL(url.Utf8()), response_time, - mojo_base::BigBuffer(base::make_span(data, size))); - } else { - code_cache_host->get()->DidGenerateCacheableMetadataInCacheStorage( - GURL(url.Utf8()), response_time, - mojo_base::BigBuffer(base::make_span(data, size)), - WebSecurityOrigin(origin), cache_storage_name.Utf8()); - } + if (!code_cache_host) + return; + if (cache_storage_name.IsNull()) { + code_cache_host->get()->DidGenerateCacheableMetadata( + code_cache_type, GURL(url.Utf8()), response_time, + mojo_base::BigBuffer(base::make_span(data, size))); } else { - // TODO(mythria): Update worklets to use the correct code_cache_host - // interface and remove this path. - if (cache_storage_name.IsNull()) { - Platform::Current()->CacheMetadata(code_cache_type, KURL(url), - response_time, data, size); - } else { - Platform::Current()->CacheMetadataInCacheStorage( - KURL(url), response_time, data, size, WebSecurityOrigin(origin), - cache_storage_name); - } + code_cache_host->get()->DidGenerateCacheableMetadataInCacheStorage( + GURL(url.Utf8()), response_time, + mojo_base::BigBuffer(base::make_span(data, size)), + WebSecurityOrigin(origin), cache_storage_name.Utf8()); } }
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.cc b/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.cc index 9299c22..defd88a 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.cc +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.cc
@@ -14,44 +14,27 @@ namespace blink { -CodeCacheLoader::CodeCacheLoader(CodeCacheHost* code_cache_host) - : code_cache_host_(code_cache_host ? code_cache_host->GetWeakPtr() - : nullptr) {} +CodeCacheLoader::CodeCacheLoader(CodeCacheHost* code_cache_host) { + DCHECK(code_cache_host); + code_cache_host_ = code_cache_host->GetWeakPtr(); +} CodeCacheLoader::~CodeCacheLoader() = default; void CodeCacheLoader::FetchFromCodeCache(mojom::CodeCacheType cache_type, const WebURL& url, FetchCodeCacheCallback callback) { - if (code_cache_host_) { - code_cache_host_->get()->FetchCachedCode( - cache_type, static_cast<GURL>(static_cast<KURL>(url)), - std::move(callback)); - } else if (ShouldUsePerProcessInterface()) { - // TODO(mythria): This path is required for workers currently. Once we - // update worker requests to go through WorkerHost remove this path. - Platform::Current()->FetchCachedCode(cache_type, url, std::move(callback)); - } + DCHECK(code_cache_host_); + code_cache_host_->get()->FetchCachedCode( + cache_type, static_cast<GURL>(static_cast<KURL>(url)), + std::move(callback)); } void CodeCacheLoader::ClearCodeCacheEntry(mojom::CodeCacheType cache_type, const WebURL& url) { - if (code_cache_host_) { - code_cache_host_->get()->ClearCodeCacheEntry( - cache_type, static_cast<GURL>(static_cast<KURL>(url))); - } else if (ShouldUsePerProcessInterface()) { - // TODO(mythria): This path is required for worklets currently. Once we - // update worker requests to go through WorkerHost remove this path. - Platform::Current()->ClearCodeCacheEntry( - cache_type, static_cast<GURL>(static_cast<KURL>(url))); - } -} - -bool CodeCacheLoader::ShouldUsePerProcessInterface() const { - // If the code cache host is nullptr, and was never invalidated, then it was - // initialised with nullptr. In this case, we should use the per-process - // interface. Otherwise, we should try to use the host. - return !code_cache_host_ && !code_cache_host_.WasInvalidated(); + DCHECK(code_cache_host_); + code_cache_host_->get()->ClearCodeCacheEntry( + cache_type, static_cast<GURL>(static_cast<KURL>(url))); } // static
diff --git a/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.h b/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.h index 9bfb674..f40bc7c2 100644 --- a/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.h +++ b/third_party/blink/renderer/platform/loader/fetch/url_loader/code_cache_loader.h
@@ -20,10 +20,7 @@ class BLINK_PLATFORM_EXPORT CodeCacheLoader : public WebCodeCacheLoader { public: // |code_cache_host| is the per-frame mojo interface that should be used when - // fetching code cache. If this value is nullptr it uses per-process - // interface. - // TODO(mythria): Remove the per-process interface and only expect non nullptr - // for |code_cache_host|. + // fetching code cache. explicit CodeCacheLoader(CodeCacheHost* code_cache_host); ~CodeCacheLoader() override; @@ -36,9 +33,7 @@ const WebURL& url) override; private: - bool ShouldUsePerProcessInterface() const; - - base::WeakPtr<CodeCacheHost> const code_cache_host_; + base::WeakPtr<CodeCacheHost> code_cache_host_; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index f2f3a08..c569bbd7 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -384,7 +384,7 @@ }, { name: "ClipboardCustomFormats", - status: "experimental", + status: "stable", }, { name: "ClipboardSvg",
diff --git a/third_party/blink/renderer/platform/wtf/BUILD.gn b/third_party/blink/renderer/platform/wtf/BUILD.gn index 421ece6..223ad3e 100644 --- a/third_party/blink/renderer/platform/wtf/BUILD.gn +++ b/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -113,6 +113,7 @@ "text/atomic_string.cc", "text/atomic_string.h", "text/atomic_string_cf.cc", + "text/atomic_string_encoding.h", "text/atomic_string_hash.h", "text/atomic_string_table.cc", "text/atomic_string_table.h",
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.cc b/third_party/blink/renderer/platform/wtf/text/atomic_string.cc index aeb20fe5..e80ae33 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.cc +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.cc
@@ -42,13 +42,16 @@ AtomicString::AtomicString(const LChar* chars, unsigned length) : string_(AtomicStringTable::Instance().Add(chars, length)) {} -AtomicString::AtomicString(const UChar* chars, unsigned length) - : string_(AtomicStringTable::Instance().Add(chars, length)) {} +AtomicString::AtomicString(const UChar* chars, + unsigned length, + AtomicStringUCharEncoding encoding) + : string_(AtomicStringTable::Instance().Add(chars, length, encoding)) {} AtomicString::AtomicString(const UChar* chars) : string_(AtomicStringTable::Instance().Add( chars, - chars ? LengthOfNullTerminatedString(chars) : 0)) {} + chars ? LengthOfNullTerminatedString(chars) : 0, + AtomicStringUCharEncoding::kUnknown)) {} scoped_refptr<StringImpl> AtomicString::AddSlowCase( scoped_refptr<StringImpl>&& string) {
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.h b/third_party/blink/renderer/platform/wtf/text/atomic_string.h index 064d53f0..a01ea9a5d 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.h +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.h
@@ -29,6 +29,7 @@ #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h" #include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -74,7 +75,10 @@ AtomicString(const char* chars) : AtomicString(reinterpret_cast<const LChar*>(chars)) {} AtomicString(const LChar* chars, unsigned length); - AtomicString(const UChar* chars, unsigned length); + AtomicString( + const UChar* chars, + unsigned length, + AtomicStringUCharEncoding encoding = AtomicStringUCharEncoding::kUnknown); AtomicString(const UChar* chars); // Constructing an AtomicString from a String / StringImpl can be expensive if
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string_cf.cc b/third_party/blink/renderer/platform/wtf/text/atomic_string_cf.cc index 770d6253..ae0f463b5 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string_cf.cc +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string_cf.cc
@@ -44,14 +44,17 @@ CFStringGetCStringPtr(string, kCFStringEncodingISOLatin1))) return AtomicStringTable::Instance().Add(ptr, length); - if (const UniChar* ptr = CFStringGetCharactersPtr(string)) + if (const UniChar* ptr = CFStringGetCharactersPtr(string)) { return AtomicStringTable::Instance().Add( - reinterpret_cast<const UChar*>(ptr), length); + reinterpret_cast<const UChar*>(ptr), length, + AtomicStringUCharEncoding::kUnknown); + } Vector<UniChar, 1024> uchar_buffer(length); CFStringGetCharacters(string, CFRangeMake(0, length), uchar_buffer.data()); return AtomicStringTable::Instance().Add( - reinterpret_cast<const UChar*>(uchar_buffer.data()), length); + reinterpret_cast<const UChar*>(uchar_buffer.data()), length, + AtomicStringUCharEncoding::kUnknown); } } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h b/third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h new file mode 100644 index 0000000..9b681c3 --- /dev/null +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_ATOMIC_STRING_ENCODING_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_ATOMIC_STRING_ENCODING_H_ + +namespace WTF { + +enum class AtomicStringUCharEncoding { + kUnknown, + + // The string contains only 8-bit characters. + kIs8Bit, + + // The string contains at least one 16-bit character. + kIs16Bit, +}; + +} // namespace WTF + +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_ATOMIC_STRING_ENCODING_H_
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc b/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc index f5f0ebdd..1dd4caf 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc
@@ -13,25 +13,40 @@ namespace { -template <typename CharacterType> -class HashTranslatorCharBuffer { +class UCharBuffer { public: - HashTranslatorCharBuffer(const CharacterType* chars, unsigned len) + UCharBuffer(const UChar* chars, + unsigned len, + AtomicStringUCharEncoding encoding) : characters_(chars), length_(len), - hash_(StringHasher::ComputeHashAndMaskTop8Bits(chars, len)) {} + hash_(StringHasher::ComputeHashAndMaskTop8Bits(chars, len)), + encoding_(encoding) {} - const CharacterType* characters() const { return characters_; } + const UChar* characters() const { return characters_; } unsigned length() const { return length_; } unsigned hash() const { return hash_; } + AtomicStringUCharEncoding encoding() const { return encoding_; } + + scoped_refptr<StringImpl> CreateStringImpl() const { + switch (encoding_) { + case AtomicStringUCharEncoding::kUnknown: + return StringImpl::Create8BitIfPossible(characters_, length_); + case AtomicStringUCharEncoding::kIs8Bit: + return String::Make8BitFrom16BitSource(characters_, length_) + .ReleaseImpl(); + case AtomicStringUCharEncoding::kIs16Bit: + return StringImpl::Create(characters_, length_); + } + } private: - const CharacterType* characters_; - unsigned length_; - unsigned hash_; + const UChar* characters_; + const unsigned length_; + const unsigned hash_; + const AtomicStringUCharEncoding encoding_; }; -typedef HashTranslatorCharBuffer<UChar> UCharBuffer; struct UCharBufferTranslator { static unsigned GetHash(const UCharBuffer& buf) { return buf.hash(); } @@ -42,9 +57,7 @@ static void Translate(StringImpl*& location, const UCharBuffer& buf, unsigned hash) { - auto string = - StringImpl::Create8BitIfPossible(buf.characters(), buf.length()); - location = string.release(); + location = buf.CreateStringImpl().release(); location->SetHash(hash); location->SetIsAtomic(); } @@ -275,19 +288,37 @@ : base::WrapRefCounted(*add_result.stored_value); } -scoped_refptr<StringImpl> AtomicStringTable::Add(const UChar* s, - unsigned length) { +scoped_refptr<StringImpl> AtomicStringTable::Add( + const UChar* s, + unsigned length, + AtomicStringUCharEncoding encoding) { if (!s) return nullptr; if (!length) return StringImpl::empty_; - UCharBuffer buffer(s, length); + UCharBuffer buffer(s, length, encoding); return AddToStringTable<UCharBuffer, UCharBufferTranslator>(buffer); } -typedef HashTranslatorCharBuffer<LChar> LCharBuffer; +class LCharBuffer { + public: + LCharBuffer(const LChar* chars, unsigned len) + : characters_(chars), + length_(len), + hash_(StringHasher::ComputeHashAndMaskTop8Bits(chars, len)) {} + + const LChar* characters() const { return characters_; } + unsigned length() const { return length_; } + unsigned hash() const { return hash_; } + + private: + const LChar* characters_; + const unsigned length_; + const unsigned hash_; +}; + struct LCharBufferTranslator { static unsigned GetHash(const LCharBuffer& buf) { return buf.hash(); }
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string_table.h b/third_party/blink/renderer/platform/wtf/text/atomic_string_table.h index 12fa17df..79afda5d 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string_table.h +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string_table.h
@@ -7,6 +7,7 @@ #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string_encoding.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" #include "third_party/blink/renderer/platform/wtf/threading.h" @@ -39,7 +40,9 @@ scoped_refptr<StringImpl> Add(StringImpl*); scoped_refptr<StringImpl> Add(scoped_refptr<StringImpl>&&); scoped_refptr<StringImpl> Add(const LChar* chars, unsigned length); - scoped_refptr<StringImpl> Add(const UChar* chars, unsigned length); + scoped_refptr<StringImpl> Add(const UChar* chars, + unsigned length, + AtomicStringUCharEncoding encoding); // Adding UTF8. // Returns null if the characters contain invalid utf8 sequences.
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 14a7710..722bc44c 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -336,6 +336,11 @@ crbug.com/1170337 [ Debug Mac11 ] external/wpt/html/canvas/element/drawing-text-to-the-canvas/2d.text.draw.fill.maxWidth.negative.html [ Pass Timeout ] crbug.com/1170337 [ Debug Mac11 ] external/wpt/html/canvas/element/drawing-text-to-the-canvas/2d.text.draw.fill.maxWidth.zero.html [ Pass Timeout ] crbug.com/1170337 [ Mac10.13 ] external/wpt/html/canvas/offscreen/text/2d.text.draw.fill.maxWidth.zero.worker.html [ Skip Timeout ] +crbug.com/1300389 external/wpt/html/canvas/element/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html [ Failure ] +crbug.com/1300389 external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html [ Failure ] +crbug.com/1300389 external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.worker.html [ Failure ] +crbug.com/1300389 virtual/no-alloc-direct-call/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html [ Failure ] +crbug.com/1300389 virtual/no-alloc-direct-call/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.worker.html [ Failure ] crbug.com/1315282 [ Mac ] external/wpt/html/canvas/element/drawing-text-to-the-canvas/direction-inherit-rtl.html [ Failure ] crbug.com/1315282 [ Mac ] external/wpt/html/canvas/element/drawing-text-to-the-canvas/direction-rtl.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html deleted file mode 100644 index f0c3e5eb..0000000 --- a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html +++ /dev/null
@@ -1,45 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>FederatedCredential.revoke() promise resolution</title> -<link rel="author" title="Christian Biesinger" href="mailto:cbiesinger@chromium.org"> -<link rel="help" href="https://wicg.github.io/FedCM/#browser-api-revocation"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> - -<script type="module"> - import {fedcm_test} from './support/fedcm-helper.js'; - - async function getCredential(provider_url) { - const provider = { - url: provider_url || "https://idp.example/", - clientId: "1234", - }; - return await navigator.credentials.get({ - federated: { - providers: [provider], - }, - }); - } - - fedcm_test(async (t, mock) => { - mock.revokeReturn("kSuccess"); - await (await getCredential()).revoke("foo@bar.com"); - }, "Successfully revoking a token should resolve the promise."); - - fedcm_test(async (t, mock) => { - mock.revokeReturn("kError"); - const result = (await getCredential()).revoke("foo@bar.com"); - return promise_rejects_dom(t, "NetworkError", result); - }, "Error should reject the promise."); - - fedcm_test(async (t, mock) => { - mock.revokeReturn("kError"); - const result = (await getCredential()).revoke(""); - return promise_rejects_dom(t, "InvalidStateError", result); - }, "Empty hint should reject the promise."); - - fedcm_test(async (t, mock) => { - const result = getCredential("https://other-idp.example/").then((c) => c.revoke("foo@bar.com")); - return promise_rejects_dom(t, "NetworkError", result); - }, "Provider URL should honor Content-Security-Policy."); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html.headers b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html.headers deleted file mode 100644 index fd82d50..0000000 --- a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.https.html.headers +++ /dev/null
@@ -1 +0,0 @@ -Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src https://idp.example
diff --git a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html new file mode 100644 index 0000000..79a9a87 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html
@@ -0,0 +1,56 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>FederatedCredential.revoke() promise resolution</title> +<link rel="author" title="Christian Biesinger" href="mailto:cbiesinger@chromium.org"> +<link rel="help" href="https://fedidcg.github.io/FedCM/#browser-api-revocation"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<script type="module"> + import {set_fedcm_cookie} from './support/fedcm-helper.js'; + const url_prefix = 'https://{{host}}:{{ports[https][0]}}/credential-management/support/'; + + async function getCredential(provider_url) { + const provider = { + url: provider_url || url_prefix, + clientId: "1234", + }; + return await navigator.credentials.get({ + federated: { + providers: [provider], + }, + }); + } + + promise_test(async t => { + await set_fedcm_cookie(); + await (await getCredential()).login({nonce: '1'}); + await (await getCredential()).revoke("1234"); + + // Second revoke should now fail since the first revoke should revoke + // the permission. + const result = (await getCredential()).revoke("1234"); + return promise_rejects_dom(t, "NetworkError", result); + }, "Successfully revoking a token should resolve the promise."); + + promise_test(async t => { + // Have to first login or the request will be rejected before it reaches + // the server. + await set_fedcm_cookie(); + await (await getCredential()).login({nonce: '1'}); + await (await getCredential()).revoke("1234"); + + const result = (await getCredential()).revoke("fail"); + return promise_rejects_dom(t, "NetworkError", result); + }, "Error should reject the promise."); + + promise_test(async t => { + const result = (await getCredential()).revoke(""); + return promise_rejects_dom(t, "InvalidStateError", result); + }, "Empty hint should reject the promise."); + + promise_test(async t => { + const result = getCredential("https://other-idp.example/").then((c) => c.revoke("foo@bar.com")); + return promise_rejects_dom(t, "NetworkError", result); + }, "Provider URL should honor Content-Security-Policy."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html.sub.headers b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html.sub.headers new file mode 100644 index 0000000..69b5bf33 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/credential-management/fedcm-revoke.sub.https.html.sub.headers
@@ -0,0 +1 @@ +Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src https://{{host}}:{{ports[https][0]}}
diff --git a/third_party/blink/web_tests/external/wpt/credential-management/support/revoke.py b/third_party/blink/web_tests/external/wpt/credential-management/support/revoke.py new file mode 100644 index 0000000..ed6fe00d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/credential-management/support/revoke.py
@@ -0,0 +1,6 @@ +def main(request, response): + if not b"hint" in request.POST: + return (500, [], "Missing hint") + if request.POST[b"hint"] == b"fail": + return (500, [], "Fail requested") + return (204, [], "")
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/offset-top-block-in-inline.html b/third_party/blink/web_tests/external/wpt/css/css-break/offset-top-block-in-inline.html new file mode 100644 index 0000000..72b35087e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/offset-top-block-in-inline.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1332572"> +<div style="columns:2; column-fill:auto; height:100px;"> + <span> + <div id="first" style="height:100px; background:cyan;"></div> + <div id="second" style="height:100px; background:hotpink;"></div> + </span> +</div> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> + test(()=> { + assert_equals(first.offsetTop, second.offsetTop); + }, "offsetTop"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/event-timing/first-input-interactionid-tap.html b/third_party/blink/web_tests/external/wpt/event-timing/first-input-interactionid-tap.html new file mode 100644 index 0000000..c5c6f51 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/event-timing/first-input-interactionid-tap.html
@@ -0,0 +1,56 @@ +<!DOCTYPE html> +<html> +<meta charset=utf-8 /> +<meta name="timeout" content="long"> +<title>Event Timing: first-input-interactionId-tap.</title> +<button id='test'>Tap</button> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src=/resources/testdriver.js></script> +<script src=/resources/testdriver-actions.js></script> +<script src=/resources/testdriver-vendor.js></script> +<script src=resources/event-timing-test-utils.js></script> + +<script> + let firstInputInteractionId = 0; + let eventTimingPointerDownInteractionId = 0; + let hasFirstInputEntry = false; + let hasEventTimingPointerDownEntry = false; + + const isReadyForCheck = () => { + return hasFirstInputEntry && hasEventTimingPointerDownEntry; + } + + async_test(function (t) { + assert_implements(window.PerformanceEventTiming, 'Event Timing is not supported.'); + + new PerformanceObserver(t.step_func(entryList => { + entryList.getEntries().forEach(entry => { + switch (entry.entryType) { + case "first-input": { + firstInputInteractionId = entry.interactionId; + hasFirstInputEntry = true; + break; + } + case "event": { + if ('pointerdown' == entry.name) { + eventTimingPointerDownInteractionId = entry.interactionId; + hasEventTimingPointerDownEntry = true; + } + break; + } + } + }) + + if (isReadyForCheck()) { + assert_greater_than(firstInputInteractionId, 0, 'The first input entry should have a non-trivial interactionId'); + assert_equals(firstInputInteractionId, eventTimingPointerDownInteractionId, 'The first input entry should have the same interactionId as the event timing pointerdown entry'); + t.done(); + } + })).observe({ entryTypes: ["event", "first-input"] }); + + addListenersAndTap(document.getElementById('test'), ['pointerdown', 'pointerup']); + }, "Event Timing: The interactionId of first input should match the event timing pointerdown entry when tap."); +</script> + +</html>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/element/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html b/third_party/blink/web_tests/external/wpt/html/canvas/element/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html new file mode 100644 index 0000000..4101bf4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/element/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html
@@ -0,0 +1,28 @@ +<!DOCTYPE html> +<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> +<title>Canvas test: 2d.fillStyle.get.halftransparent</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/html/canvas/resources/canvas-tests.js"></script> +<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css"> +<body class="show_output"> + +<h1>2d.fillStyle.get.halftransparent</h1> +<p class="desc"></p> + + +<p class="output">Actual output:</p> +<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> + +<ul id="d"></ul> +<script> +var t = async_test(""); +_addTest(function(canvas, ctx) { + +ctx.fillStyle = 'rgba(255,255,255,0.5)'; +_assertSame(ctx.fillStyle, 'rgba(255, 255, 255, 0.5)', "ctx.fillStyle", "'rgba(255, 255, 255, 0.5)'"); + + +}); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html new file mode 100644 index 0000000..47e5555 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> +<title>OffscreenCanvas test: 2d.fillStyle.get.halftransparent</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/html/canvas/resources/canvas-tests.js"></script> + +<h1>2d.fillStyle.get.halftransparent</h1> +<p class="desc"></p> + + +<script> +var t = async_test(""); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var canvas = new OffscreenCanvas(100, 50); +var ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'rgba(255,255,255,0.5)'; +_assertSame(ctx.fillStyle, 'rgba(255, 255, 255, 0.5)', "ctx.fillStyle", "'rgba(255, 255, 255, 0.5)'"); + +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.worker.js new file mode 100644 index 0000000..ec66b586 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/fill-and-stroke-styles/2d.fillStyle.get.halftransparent.worker.js
@@ -0,0 +1,23 @@ +// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.fillStyle.get.halftransparent +// Description: +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/html/canvas/resources/canvas-tests.js"); + +var t = async_test(""); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var canvas = new OffscreenCanvas(100, 50); +var ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'rgba(255,255,255,0.5)'; +_assertSame(ctx.fillStyle, 'rgba(255, 255, 255, 0.5)', "ctx.fillStyle", "'rgba(255, 255, 255, 0.5)'"); + +}); +done();
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml index f52a3e2..16c8aa5 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml
@@ -94,6 +94,14 @@ ctx.fillStyle = 'rgba(255,255,255,0.45)'; @assert ctx.fillStyle =~ /^rgba\(255, 255, 255, 0\.4\d+\)$/; +- name: 2d.fillStyle.get.halftransparent + testing: + - 2d.colours.getcolour + - 2d.serializecolour.transparent + code: | + ctx.fillStyle = 'rgba(255,255,255,0.5)'; + @assert ctx.fillStyle === 'rgba(255, 255, 255, 0.5)'; + - name: 2d.fillStyle.get.transparent testing: - 2d.colours.getcolour
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml index 7a57a47..c70082c 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml
@@ -40,6 +40,15 @@ @assert ctx.fillStyle =~ /^rgba\(255, 255, 255, 0\.4\d+\)$/; t.done(); +- name: 2d.fillStyle.get.halftransparent + testing: + - 2d.colours.getcolour + - 2d.serializecolour.transparent + code: | + ctx.fillStyle = 'rgba(255,255,255,0.5)'; + @assert ctx.fillStyle === 'rgba(255, 255, 255, 0.5)'; + + - name: 2d.fillStyle.get.transparent testing: - 2d.colours.getcolour @@ -1755,4 +1764,3 @@ @assert pixel 1,48 == 0,255,0,255; @assert pixel 98,48 == 0,255,0,255; t.done(); -
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/delay-load-event.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/delay-load-event.html new file mode 100644 index 0000000..5ec6433e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/dynamic-import/delay-load-event.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<title>Dynamic imports don't delay the load event</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +// Dynamic imports don't #delay-the-load-event. +// Therefore, Window load event would be fired +// just after the dynamic import() below starts. +window.loaded = []; +window.addEventListener('load', () => loaded.push('Window load event')); +promise_test(t => { + loaded.push('import start'); + // This 'loading' log is added to detect the previous Chromium behavior + // where the Window load event is delayed until just before script + // element's load event. + t.step_timeout(() => loaded.push('loading'), 1000); + return import("../resources/slow-module.js?pipe=trickle(d2)") + .then(() => { + assert_array_equals( + loaded, + ['import start', 'Window load event', 'loading', 'slow'], + "Window load event shouldn't be delayed by dynamic imports"); + }); +}, "Dynamic imports don't delay the load event."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/mediacapture-region/CropTarget-fromElement.https.html b/third_party/blink/web_tests/external/wpt/mediacapture-region/CropTarget-fromElement.https.html index caf7e27..fb0393b 100644 --- a/third_party/blink/web_tests/external/wpt/mediacapture-region/CropTarget-fromElement.https.html +++ b/third_party/blink/web_tests/external/wpt/mediacapture-region/CropTarget-fromElement.https.html
@@ -23,69 +23,66 @@ <script> "use strict"; - // Regex that matches a Universally Unique IDentifer composed of hex - // characters separated by dashes in the form 8-4-4-4-12 for a total - // of 36 characters. - const GUID_REGEX = /^[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$/; - promise_test(async () => { assert_true(!!CropTarget.fromElement); - const iframe_id = await CropTarget.fromElement( + const crop_target = await CropTarget.fromElement( document.getElementById('test-iframe')); - assert_true(GUID_REGEX.test(iframe_id)); - }, "produces valid IDs for iframe"); + assert_equals(crop_target.constructor.name, 'CropTarget'); + }, "Produces a CropTarget for Elements of subtype iframe."); promise_test(async () => { assert_true(!!CropTarget.fromElement); - const div_id = await CropTarget.fromElement( + const crop_target = await CropTarget.fromElement( document.getElementById('test-div')); - assert_true(GUID_REGEX.test(div_id)); - }, "produces valid id for div"); - - promise_test(async () => { - assert_true(!!CropTarget.fromElement); - const iframe_id = await CropTarget.fromElement( - document.getElementById('test-iframe')); - const second_iframe_id = await CropTarget.fromElement( - document.getElementById('test-iframe')); - assert_equals(iframe_id, second_iframe_id); - }, "repeated calls return the same value"); + assert_equals(crop_target.constructor.name, 'CropTarget'); + }, "Produces a CropTarget for Elements of subtype div."); promise_test(t => { assert_true(!!CropTarget.fromElement); return promise_rejects_js(t, TypeError, CropTarget.fromElement(undefined)); - }, "rejects undefined with a TypeError"); + }, "Rejects undefined with a TypeError."); promise_test(t => { assert_true(!!CropTarget.fromElement); return promise_rejects_js(t, TypeError, CropTarget.fromElement(123)); - }, "rejects a non-element with a TypeError"); + }, "Rejects a non-Element with a TypeError."); promise_test(function (t) { assert_true(!!CropTarget.fromElement); + return promise_rejects_dom(t, "NotSupportedError", CropTarget.fromElement(document.getElementById("test-a"))); - }, "rejects unimplemented Element subtypes with a NotSupportedError"); + }, "Rejects unimplemented Element subtypes with a NotSupportedError"); promise_test(async () => { assert_true(!!CropTarget.fromElement); - const div_id = await CropTarget.fromElement( + + const div_crop_target = await CropTarget.fromElement( document.getElementById('test-div')); - const iframe_id = await CropTarget.fromElement( + assert_equals(div_crop_target.constructor.name, 'CropTarget'); + + const iframe_crop_target = await CropTarget.fromElement( document.getElementById('test-iframe')); - assert_not_equals(div_id, iframe_id); - }, "two elements have different IDs"); + assert_equals(iframe_crop_target.constructor.name, 'CropTarget'); + + assert_not_equals(div_crop_target, iframe_crop_target); + }, "Distinct Elements produce distinct CropTargets."); promise_test(async () => { assert_true(!!CropTarget.fromElement); + const div = document.getElementById('test-div'); - const div_id = await CropTarget.fromElement(div); + const div_crop_target = await CropTarget.fromElement(div); + assert_equals(div_crop_target.constructor.name, 'CropTarget'); + const clone = div.cloneNode(true); document.querySelector('body').appendChild(clone); - const clone_id = await CropTarget.fromElement(clone); - assert_not_equals(div_id, clone_id); - }, "cloned elements have different IDs"); + const clone_crop_target = await CropTarget.fromElement(clone); + assert_equals(clone_crop_target.constructor.name, 'CropTarget'); + + assert_not_equals(div_crop_target, clone_crop_target); + }, "Cloned Elements produce distinct CropTargets."); </script> </body>
diff --git a/third_party/blink/web_tests/fast/events/wheel/mouse-wheel-main-frame-scroll.html b/third_party/blink/web_tests/fast/events/wheel/mouse-wheel-main-frame-scroll.html index 242fae2..667f0f7 100644 --- a/third_party/blink/web_tests/fast/events/wheel/mouse-wheel-main-frame-scroll.html +++ b/third_party/blink/web_tests/fast/events/wheel/mouse-wheel-main-frame-scroll.html
@@ -10,13 +10,16 @@ promise_test(async () => { await mouseMoveTo(50, 50); const pixelsToScrollY = 100; - await percentBasedSmoothScroll( + await smoothScroll( pixelsToScrollY, 50, 50, GestureSourceType.MOUSE_INPUT, 'down', SPEED_INSTANT ); await waitForAnimationEndTimeBased(() => { return window.scrollY; }); - assert_approx_equals(window.scrollY, pixelsToScrollY, 0.2); + const { y: expectedScrollY } = calculateExpectedScroll( + document.scrollingElement, 0, pixelsToScrollY + ); + assert_approx_equals(window.scrollY, expectedScrollY, 0.001); }, "Mouse wheel scrolls properly on main frame."); </script> <body>
diff --git a/third_party/blink/web_tests/fast/events/wheel/wheelevent-basic.html b/third_party/blink/web_tests/fast/events/wheel/wheelevent-basic.html index e0266817..6a2c1661 100644 --- a/third_party/blink/web_tests/fast/events/wheel/wheelevent-basic.html +++ b/third_party/blink/web_tests/fast/events/wheel/wheelevent-basic.html
@@ -43,17 +43,22 @@ var y = testDiv.offsetTop + 5; await mouseMoveTo(x, y); const pixelsToScroll = 40; - await percentBasedSmoothScroll( - pixelsToScroll, x, y, GestureSourceType.MOUSE_INPUT, 'downright', SPEED_INSTANT, - testDiv); + await smoothScroll( + pixelsToScroll, x, y, GestureSourceType.MOUSE_INPUT, 'downright', SPEED_INSTANT + ); if (isPercentBasedScrollingEnabled()) { await waitForAnimationEndTimeBased(() => { return testDiv.scrollTop; }); await waitForAnimationEndTimeBased(() => { return testDiv.scrollLeft; }); + const { + x: expectedScrollLeft, + y: expectedScrollTop, + } = calculateExpectedScroll(testDiv, pixelsToScroll, pixelsToScroll); + // Windows and Linux values appear to be slightly different - assert_approx_equals(testDiv.scrollTop, pixelsToScroll, 0.05); - assert_approx_equals(testDiv.scrollLeft, pixelsToScroll, 0.2); + assert_approx_equals(testDiv.scrollTop, expectedScrollTop, 0.05); + assert_approx_equals(testDiv.scrollLeft, expectedScrollLeft, 0.1); } else { await waitFor( () => { return deltaX > 0 && deltaY > 0 && deltaX == testDiv.scrollLeft &&
diff --git a/third_party/blink/web_tests/fast/events/wheel/wheelevent-in-horizontal-scrollbar-in-rtl.html b/third_party/blink/web_tests/fast/events/wheel/wheelevent-in-horizontal-scrollbar-in-rtl.html index ba322cf..f50b81e 100644 --- a/third_party/blink/web_tests/fast/events/wheel/wheelevent-in-horizontal-scrollbar-in-rtl.html +++ b/third_party/blink/web_tests/fast/events/wheel/wheelevent-in-horizontal-scrollbar-in-rtl.html
@@ -5,12 +5,18 @@ <script src="../../../virtual/percent-based-scrolling/resources/percent-based-util.js"></script> <script> const pixelsToScroll1 = 10; + const { x: pixelsToScrollX1, y: pixelsToScrollY1 } = calculatePixelsToScroll( + document.scrollingElement, pixelsToScroll1, pixelsToScroll1 + ); const pixelsToScroll2 = 30; + const { x: pixelsToScrollX2, y: pixelsToScrollY2 } = calculatePixelsToScroll( + document.scrollingElement, pixelsToScroll2, pixelsToScroll2 + ); const testScrolls = [ - {distance: pixelsToScroll1, expectedX: -90, expectedY: 100, direction: 'right'}, - {distance: pixelsToScroll2, expectedX: -120, expectedY: 100, direction: 'left'}, - {distance: pixelsToScroll1, expectedX: -120, expectedY: 110, direction: 'down'}, - {distance: pixelsToScroll2, expectedX: -120, expectedY: 80, direction: 'up'}, + {distance: pixelsToScrollX1, expectedX: -90, expectedY: 100, direction: 'right'}, + {distance: pixelsToScrollX2, expectedX: -120, expectedY: 100, direction: 'left'}, + {distance: pixelsToScrollY1, expectedX: -120, expectedY: 110, direction: 'down'}, + {distance: pixelsToScrollY2, expectedX: -120, expectedY: 80, direction: 'up'}, ]; var currentTest = -1; @@ -22,7 +28,7 @@ var testCase = testScrolls[currentTest]; promise_test(async () => { await mouseMoveTo(100, 100); - await percentBasedSmoothScroll(testCase.distance, 100, 100, + await smoothScroll(testCase.distance, 100, 100, GestureSourceType.MOUSE_INPUT, testCase.direction, SPEED_INSTANT); await waitForAnimationEndTimeBased(() => { return window.scrollX; }); await waitForAnimationEndTimeBased(() => { return window.scrollY; });
diff --git a/third_party/blink/web_tests/http/tests/security/mixedContent/filesystem-url-in-iframe.html b/third_party/blink/web_tests/http/tests/security/mixedContent/filesystem-url-in-iframe.html deleted file mode 100644 index db86fbd..0000000 --- a/third_party/blink/web_tests/http/tests/security/mixedContent/filesystem-url-in-iframe.html +++ /dev/null
@@ -1,45 +0,0 @@ -<!DOCTYPE html> -<html> -<body> -<iframe></iframe> -<p> - This tests that filesystem URLs created in a secure context are treated as - secure origins. This test passes if the iframe renders PASS correctly, and no - console warning appears. -</p> - -<script> -if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.dumpChildFrames(); - testRunner.waitUntilDone(); -} - -if (location.protocol != 'https:') - location = 'https://127.0.0.1:8443/security/mixedContent/filesystem-url-in-iframe.html'; -else { - var iframe = document.querySelector('iframe'); - iframe.onload = function () { - if (window.testRunner) - testRunner.notifyDone(); - }; - - // Opening a file system with temporary storage - window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { - fs.root.getFile('test.html', {create: true}, function(fileEntry) { - fileEntry.createWriter(function(fileWriter) { - fileWriter.onwriteend = function(e) { - alert('PASS (1/2): File written'); - iframe.src = fileEntry.toURL('text/html'); - }; - - // Create a new Blob and write it to log.txt. - var b = new Blob(['PASS (2/2): File displayed'], { type: 'text/html' }); - fileWriter.write(b); - }); - }); - }); -} -</script> -</body> -</html>
diff --git a/third_party/blink/web_tests/resources/gesture-util.js b/third_party/blink/web_tests/resources/gesture-util.js index 0214887..45cfe8f8 100644 --- a/third_party/blink/web_tests/resources/gesture-util.js +++ b/third_party/blink/web_tests/resources/gesture-util.js
@@ -305,39 +305,6 @@ direction, speed_in_pixels_s, precise_scrolling_deltas, scroll_by_page, cursor_visible, scroll_by_percentage, modifier_keys) { - const {pixels_to_scroll_x, pixels_to_scroll_y} = setPixelsDirection( - pixels_to_scroll, direction); - return smoothScrollWithXY(pixels_to_scroll_x, pixels_to_scroll_y, start_x, - start_y, gesture_source_type, speed_in_pixels_s, - precise_scrolling_deltas, scroll_by_page, - cursor_visible, scroll_by_percentage, modifier_keys, - ""); -} - -// Perform a smooth scroll. If percent based scrolling (PBS) is enabled, swap -// the amount of pixels to scroll for the amount of pixels it needs to scroll -// post PBS calculations to scroll the original intended amount. Note: PBS is -// not as precise as regular scrolling, therefore use assert_aprox_equals when -// using this function. -// Different from "percentScroll" which performs a scroll based on a -// percentage of the container instead of an amount of pixels. -function percentBasedSmoothScroll(pixels_to_scroll, start_x, start_y, gesture_source_type, - direction, speed_in_pixels_s, container) { - let {pixels_to_scroll_x, pixels_to_scroll_y} = setPixelsDirection( - pixels_to_scroll, direction); - // Only mouse inputs are concerned with PBS. - if (gesture_source_type === GestureSourceType.MOUSE_INPUT) { - const pixelsToScroll = calculatePixelsToScroll(container ?? - document.scrollingElement, pixels_to_scroll_x, pixels_to_scroll_y); - pixels_to_scroll_x = pixelsToScroll.x; - pixels_to_scroll_y = pixelsToScroll.y; - } - return smoothScrollWithXY(pixels_to_scroll_x, pixels_to_scroll_y, start_x, - start_y, GestureSourceType.MOUSE_INPUT, - speed_in_pixels_s); -} - -function setPixelsDirection(pixels_to_scroll, direction) { let pixels_to_scroll_x = 0; let pixels_to_scroll_y = 0; if (direction == "down") { @@ -361,7 +328,10 @@ pixels_to_scroll_x = pixels_to_scroll; pixels_to_scroll_y = pixels_to_scroll; } - return {pixels_to_scroll_x, pixels_to_scroll_y}; + return smoothScrollWithXY(pixels_to_scroll_x, pixels_to_scroll_y, start_x, + start_y, gesture_source_type, speed_in_pixels_s, + precise_scrolling_deltas, scroll_by_page, + cursor_visible, scroll_by_percentage, modifier_keys); } // Perform a percent based scroll using smoothScrollWithXY
diff --git a/third_party/blink/web_tests/wpt_internal/content-security-policy/inheritance/filesystem-url-inherits-from-initiator.sub.html b/third_party/blink/web_tests/wpt_internal/content-security-policy/inheritance/filesystem-url-inherits-from-initiator.sub.html deleted file mode 100644 index 966021c..0000000 --- a/third_party/blink/web_tests/wpt_internal/content-security-policy/inheritance/filesystem-url-inherits-from-initiator.sub.html +++ /dev/null
@@ -1,90 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> - -<title>Filesystem URL inherits CSP from initiator.</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<body> - <script> - - // Using the filesystem api, create a file URL which checks if eval is - // allowed. - let filesystem_url = new Promise((resolve, reject) => { - webkitRequestFileSystem(TEMPORARY, 2 ** 10, function(fs) { - fs.root.getFile('test', { create: true }, function(entry) { - entry.createWriter(function(writer) { - const blob_payload = ` - <!doctype html> - <script> - var i = false; - try { - eval('i = true'); - } catch {} - top.postMessage(i ? "eval allowed" : "eval blocked", '*'); - </scr` + `ipt> - `; - writer.write(new Blob([blob_payload], { type: 'text/html' })); - resolve(entry.toURL()); - }); - }); - }); - }); - - // Create `child_with_csp`, a child iframe with CSP disallowing eval. - let child_with_csp = document.createElement('iframe'); - document.body.appendChild(child_with_csp); - let meta = child_with_csp.contentDocument.createElement('meta'); - meta.httpEquiv = "Content-Security-Policy"; - meta.content = "script-src 'unsafe-inline'"; - child_with_csp.contentDocument.head.appendChild(meta); - - - // This first test creates a child iframe of `child_with_csp`. The iframe is - // first navigated to some new URL, then to the filesystem URL. We check - // that in the filesystem URL, eval is blocked. - async_test(t => { - let child = child_with_csp.contentDocument.createElement('iframe'); - - window.addEventListener("message", t.step_func(e => { - if (e.source !== child.contentWindow) return; - assert_equals(e.data, "eval blocked", - "Eval should be blocked by CSP in filesystem URL."); - t.done(); - })); - - child.src = "http://{{hosts[alt][]}}:{{ports[http][0]}}/common/blank.html"; - child.onload = async () => { - child.onload = undefined; - child.src = await filesystem_url; - } - child_with_csp.contentDocument.body.appendChild(child); - }, "Filesystem url in iframe inherits CSPs from parent."); - - - // This test creates a new iframe `target` of the main document, and - // navigates that iframe from `child_with_csp` to the filesystem URL. The - // navigated document should inherit CSPs from the initiator, hence have - // eval blocked. - async_test(t => { - let target = document.createElement('iframe'); - target.name = "target"; - - window.addEventListener("message", t.step_func(e => { - if (e.source !== target.contentWindow) return; - assert_equals(e.data, "eval blocked", - "Eval should be blocked by CSP in filesystem URL."); - t.done(); - })); - - target.src = "http://{{hosts[alt][]}}:{{ports[http][0]}}/common/blank.html"; - target.onload = async () => { - target.onload = undefined; - let script = child_with_csp.contentDocument.createElement('script'); - script.innerHTML = 'window.open("' + await filesystem_url + '", "target");' - child_with_csp.contentDocument.body.appendChild(script); - }; - document.body.appendChild(target); - }, "Filesystem url in iframe inherits CSPs from initiator."); - -</script> -</body>
diff --git a/third_party/webgpu-cts/ts_sources.txt b/third_party/webgpu-cts/ts_sources.txt index 8638197..0f7064df 100644 --- a/third_party/webgpu-cts/ts_sources.txt +++ b/third_party/webgpu-cts/ts_sources.txt
@@ -103,6 +103,8 @@ src/unittests/basic.spec.ts src/unittests/check_contents.spec.ts src/unittests/conversion.spec.ts +src/webgpu/util/f32_interval.ts +src/unittests/f32_interval.spec.ts src/unittests/getStackTrace.spec.ts src/unittests/listing.ts src/unittests/loaders_and_trees.spec.ts
diff --git a/third_party/webxr_test_pages/webxr-samples/gamepad.html b/third_party/webxr_test_pages/webxr-samples/gamepad.html index 1dc2253..d772844 100644 --- a/third_party/webxr_test_pages/webxr-samples/gamepad.html +++ b/third_party/webxr_test_pages/webxr-samples/gamepad.html
@@ -46,9 +46,9 @@ <details open> <summary>Gamepad</summary> <p> - This sample demonstrates using XRInputSource Gamepad button presses - to change box color and joystick/touchpad input to move boxes in 2 - dimensions. + This sample demonstrates XRInputSource Gamepad integration. It shows + one box per available button. Pressing the button toggles the associated + box's color. Use joystick/touchpad input to move boxes in 2 dimensions. <a class="back" href="./index.html">Back</a> </p> </details>
diff --git a/tools/aggregation_service/aggregation_service_tool.cc b/tools/aggregation_service/aggregation_service_tool.cc index 613ad1ff..76ccc5ce 100644 --- a/tools/aggregation_service/aggregation_service_tool.cc +++ b/tools/aggregation_service/aggregation_service_tool.cc
@@ -123,7 +123,8 @@ url::Origin reporting_origin, std::vector<GURL> processing_urls, bool is_debug_mode_enabled, - base::Value::Dict additional_fields) { + base::Value::Dict additional_fields, + std::string api_version) { base::Value::Dict result; absl::optional<content::TestAggregationService::Operation> operation = @@ -160,7 +161,8 @@ content::TestAggregationService::AssembleRequest request( operation.value(), bucket, value, aggregation_mode.value(), std::move(reporting_origin), std::move(processing_urls), - is_debug_mode_enabled, std::move(additional_fields)); + is_debug_mode_enabled, std::move(additional_fields), + std::move(api_version)); base::RunLoop run_loop; agg_service_->AssembleReport(
diff --git a/tools/aggregation_service/aggregation_service_tool.h b/tools/aggregation_service/aggregation_service_tool.h index e941869f..2dc9d0f 100644 --- a/tools/aggregation_service/aggregation_service_tool.h +++ b/tools/aggregation_service/aggregation_service_tool.h
@@ -62,7 +62,8 @@ url::Origin reporting_origin, std::vector<GURL> processing_urls, bool is_debug_mode_enabled, - base::Value::Dict additional_fields); + base::Value::Dict additional_fields, + std::string api_version); // Sends the contents of the aggregatable report to the specified reporting // url `url` and returns whether it's successful.
diff --git a/tools/aggregation_service/aggregation_service_tool_main.cc b/tools/aggregation_service/aggregation_service_tool_main.cc index 0d813e7f..b852116 100644 --- a/tools/aggregation_service/aggregation_service_tool_main.cc +++ b/tools/aggregation_service/aggregation_service_tool_main.cc
@@ -43,6 +43,7 @@ constexpr char kSwitchAdditionalSharedInfoFields[] = "additional-shared-info-fields"; constexpr char kSwitchEnableDebugMode[] = "enable-debug-mode"; +constexpr char kSwitchApiVersion[] = "api-version"; constexpr char kHelpMsg[] = R"( aggregation_service_tool [--operation=<operation>] --bucket=<bucket> @@ -52,13 +53,13 @@ [--output-url=<output_url>] [--disable-payload-encryption] [--additional-fields=<additional_fields>] [--additional-shared-info-fields=<additional_shared_info_fields] - [--debug-mode] + [--debug-mode] [--api-version=<api_version>] Examples: aggregation_service_tool --operation="histogram" --bucket=1234 --value=5 --alternative-aggregation-mode="experimental-poplar" --reporting-origin="https://example.com" --helper-key-urls="https://a.com/keys.json https://b.com/path/to/keys.json" - --output-file="output.json" --enable-debug-mode + --output-file="output.json" --enable-debug-mode --api-version="1.0" --additional-fields= "source_site=https://publisher.example,attribution_destination=https://advertiser.example" or @@ -107,6 +108,7 @@ serialization. --enable-debug-mode = Optional switch. If provided, debug mode is enabled. Otherwise, it is disabled. + --api-version = Optional switch to specify the API version. Default is "". )"; void PrintHelp() { @@ -147,7 +149,8 @@ kSwitchDisablePayloadEncryption, kSwitchAdditionalFields, kSwitchAdditionalSharedInfoFields, - kSwitchEnableDebugMode}; + kSwitchEnableDebugMode, + kSwitchApiVersion}; for (const auto& provided_switch : command_line.GetSwitches()) { if (!base::Contains(kAllowedSwitches, provided_switch.first)) { LOG(ERROR) << "aggregation_service_tool did not expect " @@ -280,12 +283,17 @@ } } + std::string api_version = + command_line.HasSwitch(kSwitchApiVersion) + ? command_line.GetSwitchValueASCII(kSwitchApiVersion) + : ""; + base::Value::Dict report_dict = tool.AssembleReport( std::move(operation), command_line.GetSwitchValueASCII(kSwitchBucket), command_line.GetSwitchValueASCII(kSwitchValue), std::move(aggregation_mode), std::move(reporting_origin), std::move(processing_urls), is_debug_mode_enabled, - std::move(additional_shared_info_fields)); + std::move(additional_shared_info_fields), std::move(api_version)); if (report_dict.empty()) { LOG(ERROR) << "aggregation_service_tool failed to create the aggregatable report.";
diff --git a/tools/mac/power/dtrace_scripts/profile.d b/tools/mac/power/dtrace_scripts/profile.d index ecf8bf45..e25d0e4d 100644 --- a/tools/mac/power/dtrace_scripts/profile.d +++ b/tools/mac/power/dtrace_scripts/profile.d
@@ -19,7 +19,7 @@ // Profile with a high frequency that is prime to avoid unfortunate alignement // with periods of repeating tasks internal to the process. The frequency was // verified as supported by macOS Monterey running on Intel. See -// https://illumos.org/books/dtrace/chp-profile.html#chp-profile-5 for details. +// illumos.org/books/dtrace/chp-profile.html#chp-profile-5 for details. profile-997/(pid == $1 || ppid == $1)/ { @[ustack(512)] = count();
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index bfc1ec7a..3a8b94d 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -340,6 +340,7 @@ 'Libfuzzer Upload Mac ASan': 'libfuzzer_mac_asan_shared_release_bot', 'Libfuzzer Upload Windows ASan': 'libfuzzer_windows_asan_release_bot', 'Linux Builder (j-500) (reclient)': 'gpu_tests_release_bot_reclient', + 'Linux Builder (reclient compare)': 'gpu_tests_release_bot_reclient', 'Linux CFI (reclient shadow)': 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_reclient', 'Linux ChromiumOS MSan Focal': 'chromeos_msan_release_bot', 'Linux MSan Focal': 'msan_release_bot_reclient', @@ -644,7 +645,6 @@ }, 'chromium.reclient.fyi': { - 'Linux Builder (reclient compare)': 'gpu_tests_release_bot_reclient', 'Linux Builder reclient staging': 'gpu_tests_release_bot_reclient', 'Linux Builder reclient test': 'gpu_tests_release_bot_reclient', 'Simple Chrome Builder reclient staging': 'chromeos_amd64-generic-vm_use_fake_dbus_clients_reclient',
diff --git a/tools/mb/mb_config_expectations/chromium.fyi.json b/tools/mb/mb_config_expectations/chromium.fyi.json index 47328e2..1c62ba2 100644 --- a/tools/mb/mb_config_expectations/chromium.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.fyi.json
@@ -296,6 +296,17 @@ "use_remoteexec": true } }, + "Linux Builder (reclient compare)": { + "gn_args": { + "dcheck_always_on": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_rbe": true, + "use_remoteexec": true + } + }, "Linux CFI (reclient shadow)": { "gn_args": { "dcheck_always_on": true,
diff --git a/tools/mb/mb_config_expectations/chromium.reclient.fyi.json b/tools/mb/mb_config_expectations/chromium.reclient.fyi.json index 8bb3033..f5c9360 100644 --- a/tools/mb/mb_config_expectations/chromium.reclient.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.reclient.fyi.json
@@ -1,15 +1,4 @@ { - "Linux Builder (reclient compare)": { - "gn_args": { - "dcheck_always_on": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "use_rbe": true, - "use_remoteexec": true - } - }, "Linux Builder reclient staging": { "gn_args": { "dcheck_always_on": false,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 57dc1a0d..4097405 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -34626,6 +34626,7 @@ <int value="1662" label="SHAREDSTORAGEPRIVATE_REMOVE"/> <int value="1663" label="FILEMANAGERPRIVATEINTERNAL_GETFILESRESTRICTEDBYDLP"/> <int value="1664" label="WMDESKSPRIVATE_GETALLDESKS"/> + <int value="1665" label="AUTOTESTPRIVATE_FORCEAUTOTHEMEMODE"/> </enum> <enum name="ExtensionIconState"> @@ -57499,6 +57500,7 @@ <int value="-291936879" label="UsernameFirstFlowFilling:disabled"/> <int value="-291747397" label="ForceDisableStackedTabs:enabled"/> <int value="-291221380" label="SmartLockUIRevamp:disabled"/> + <int value="-290802690" label="PartialSplit:enabled"/> <int value="-290672626" label="enable-asm-wasm"/> <int value="-290329565" label="CrosVmCupsProxy:disabled"/> <int value="-288316828" label="enable-delegated-renderer"/> @@ -59696,6 +59698,7 @@ <int value="1162693272" label="MacCoreLocationImplementation:disabled"/> <int value="1163255347" label="ash-enable-touch-view-touch-feedback"/> <int value="1163588337" label="CastForceEnableRemotingQuery:enabled"/> + <int value="1164299747" label="PartialSplit:disabled"/> <int value="1164377197" label="SwipingFromLeftEdgeToGoBack:enabled"/> <int value="1164460660" label="AutofillEnableVirtualCard:enabled"/> <int value="1165682330" label="AutofillSaveAndFillVPA:disabled"/>
diff --git a/tools/metrics/histograms/metadata/ash/histograms.xml b/tools/metrics/histograms/metadata/ash/histograms.xml index 3e44cc8..0fa9a69 100644 --- a/tools/metrics/histograms/metadata/ash/histograms.xml +++ b/tools/metrics/histograms/metadata/ash/histograms.xml
@@ -204,6 +204,26 @@ <token key="Theme" variants="AmbientModeThemes"/> </histogram> +<histogram name="Ash.AmbientMode.EngagementTime.{Theme}.{Orientation}" + units="ms" expires_after="2022-12-01"> + <owner>esum@google.com</owner> + <owner>xiaohuic@chromium.org</owner> + <summary> + Among eligible users with ambient mode enabled, records the accumulated + duration spent in {Orientation} mode during a single ambient mode session + rendering the {Theme} UI. For example, say ambient mode starts in landscape + for A ms, switches to portrait for B ms, then back to landscape for C ms + before ambient mode ends. A + C will be emitted for landscape mode, and B + will be emitted for portrait mode. Emitted once per observed orientation + each time the user exits ambient mode. + </summary> + <token key="Orientation"> + <variant name="Landscape" summary="landscape"/> + <variant name="Portrait" summary="portrait"/> + </token> + <token key="Theme" variants="AmbientModeThemes"/> +</histogram> + <histogram name="Ash.AmbientMode.LottieAnimationSmoothness.{Theme}" units="%" expires_after="2022-12-01"> <owner>esum@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/image/histograms.xml b/tools/metrics/histograms/metadata/image/histograms.xml index 3c59ed1f..c5536873 100644 --- a/tools/metrics/histograms/metadata/image/histograms.xml +++ b/tools/metrics/histograms/metadata/image/histograms.xml
@@ -394,7 +394,7 @@ <histogram name="ImageFetcher.ImageLoadFromNetworkAfterCacheHit{ImageFetcherClients}" - units="ms" expires_after="2022-06-01"> + units="ms" expires_after="2023-06-01"> <owner>fgorski@chromium.org</owner> <owner>wylieb@chromium.org</owner> <summary> @@ -407,7 +407,7 @@ </histogram> <histogram name="ImageFetcher.ImageLoadFromNetworkTime{ImageFetcherClients}" - units="ms" expires_after="2022-06-01"> + units="ms" expires_after="2023-06-01"> <owner>fgorski@chromium.org</owner> <owner>wylieb@chromium.org</owner> <summary> @@ -420,7 +420,7 @@ </histogram> <histogram name="ImageFetcher.LoadImageMetadata" units="ms" - expires_after="2022-06-01"> + expires_after="2023-06-01"> <owner>fgorski@chromium.org</owner> <owner>wylieb@chromium.org</owner> <summary> @@ -429,7 +429,7 @@ </histogram> <histogram name="ImageFetcher.RequestStatusCode{ImageFetcherClients}" - enum="CombinedHttpResponseAndNetErrorCode" expires_after="2022-06-01"> + enum="CombinedHttpResponseAndNetErrorCode" expires_after="2023-06-01"> <owner>fgorski@chromium.org</owner> <owner>wylieb@chromium.org</owner> <summary> @@ -443,7 +443,7 @@ </histogram> <histogram name="ImageFetcher.TimeSinceLastCacheLRUEviction" units="ms" - expires_after="2022-06-01"> + expires_after="2023-06-01"> <owner>fgorski@chromium.org</owner> <owner>wylieb@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/ios/histograms.xml b/tools/metrics/histograms/metadata/ios/histograms.xml index d54f7b4..5221996 100644 --- a/tools/metrics/histograms/metadata/ios/histograms.xml +++ b/tools/metrics/histograms/metadata/ios/histograms.xml
@@ -1238,7 +1238,7 @@ </histogram> <histogram name="IOS.ReadingList.PageTooLargeFailure" units="KB" - expires_after="2022-06-11"> + expires_after="2023-06-07"> <owner>olivierrobin@chromium.org</owner> <owner>justincohen@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/navigation/histograms.xml b/tools/metrics/histograms/metadata/navigation/histograms.xml index e431741e..18f40fb 100644 --- a/tools/metrics/histograms/metadata/navigation/histograms.xml +++ b/tools/metrics/histograms/metadata/navigation/histograms.xml
@@ -1276,6 +1276,19 @@ </summary> </histogram> +<histogram name="Navigation.UrlParamFilter.FilteredParamCount" units="count" + expires_after="2023-01-02"> + <owner>mreichhoff@chromium.org</owner> + <owner>wanderview@chromium.org</owner> + <owner>bcl@chromium.org</owner> + <owner>dc-komics@google.com</owner> + <summary> + The number of parameters filtered out of a given request when switching from + normal browsing to incognito. Determined by backend classification of + parameters. + </summary> +</histogram> + <histogram name="Navigation.UrlParamFilter.FilteredParamCountExperimental" units="count" expires_after="2023-01-02"> <owner>mreichhoff@chromium.org</owner> @@ -1285,8 +1298,8 @@ <summary> The number of parameters filtered out of a given request when switching from normal browsing to incognito. Determined by backend classification of - parameters. The filtering is currently experimental; this metric will be - replaced. + parameters. This metric tracks parameters filtered based on experimental + classification heuristics. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index a9038a3..d6814b4 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -1950,6 +1950,7 @@ on Android. This is recorded when destroying the Recent Tabs page if any entires of {RecentlyClosedType} type were shown. </summary> + <token key="RecentlyClosedType" variants="RecentlyClosedType"/> </histogram> <histogram name="Tabs.RecentlyClosed.EntriesShownInPage.{RecentlyClosedType}" @@ -1961,6 +1962,7 @@ {RecentlyClosedType} type shown in one Recent Tabs page session on Android. This is recorded when destroying the Recent Tabs page. </summary> + <token key="RecentlyClosedType" variants="RecentlyClosedType"/> </histogram> <histogram name="Tabs.RecentlyClosed.HistoricalSaverCloseType" @@ -1987,6 +1989,7 @@ session on Android. This is recorded when destroying the Recent Tabs page if any entires of {RecentlyClosedType} type were shown. </summary> + <token key="RecentlyClosedType" variants="RecentlyClosedType"/> </histogram> <histogram name="Tabs.SadTab.Feedback.Event" enum="SadTabEvent"
diff --git a/tools/perf/core/bot_platforms.py b/tools/perf/core/bot_platforms.py index 7ae00ab0..a771755f 100644 --- a/tools/perf/core/bot_platforms.py +++ b/tools/perf/core/bot_platforms.py
@@ -482,12 +482,18 @@ _FUCHSIA_PERF_FYI_BENCHMARK_CONFIGS = PerfSuite([ _GetBenchmarkConfig('system_health.memory_desktop'), _GetBenchmarkConfig('rendering.mobile'), - _GetBenchmarkConfig('media.mobile') + _GetBenchmarkConfig('media.mobile'), + _GetBenchmarkConfig('jetstream2'), + _GetBenchmarkConfig('speedometer2'), + _GetBenchmarkConfig('speedometer') ]) _FUCHSIA_SHERLOCK_PERF_FYI_BENCHMARK_CONFIGS = PerfSuite([ _GetBenchmarkConfig('system_health.memory_desktop'), _GetBenchmarkConfig('rendering.mobile'), - _GetBenchmarkConfig('media.mobile') + _GetBenchmarkConfig('media.mobile'), + _GetBenchmarkConfig('jetstream2'), + _GetBenchmarkConfig('speedometer2'), + _GetBenchmarkConfig('speedometer') ]) _FUCHSIA_ATLAS_PERF_FYI_BENCHMARK_CONFIGS = PerfSuite([ _GetBenchmarkConfig('system_health.common_desktop'),
diff --git a/tools/perf/core/shard_maps/fuchsia-perf-fyi_map.json b/tools/perf/core/shard_maps/fuchsia-perf-fyi_map.json index a4b47e59..04d9f8f 100644 --- a/tools/perf/core/shard_maps/fuchsia-perf-fyi_map.json +++ b/tools/perf/core/shard_maps/fuchsia-perf-fyi_map.json
@@ -1,11 +1,14 @@ { "0": { "benchmarks": { + "jetstream2": { + "abridged": false + }, "media.mobile": { "abridged": false }, "rendering.mobile": { - "end": 9, + "end": 17, "abridged": false } }, @@ -25,8 +28,8 @@ "1": { "benchmarks": { "rendering.mobile": { - "begin": 9, - "end": 63, + "begin": 17, + "end": 67, "abridged": false } } @@ -34,8 +37,8 @@ "2": { "benchmarks": { "rendering.mobile": { - "begin": 63, - "end": 122, + "begin": 67, + "end": 113, "abridged": false } } @@ -43,8 +46,8 @@ "3": { "benchmarks": { "rendering.mobile": { - "begin": 122, - "end": 195, + "begin": 113, + "end": 198, "abridged": false } } @@ -52,8 +55,8 @@ "4": { "benchmarks": { "rendering.mobile": { - "begin": 195, - "end": 297, + "begin": 198, + "end": 299, "abridged": false } } @@ -61,8 +64,8 @@ "5": { "benchmarks": { "rendering.mobile": { - "begin": 297, - "end": 356, + "begin": 299, + "end": 358, "abridged": false } } @@ -70,8 +73,8 @@ "6": { "benchmarks": { "rendering.mobile": { - "begin": 356, - "end": 410, + "begin": 358, + "end": 406, "abridged": false } } @@ -79,11 +82,17 @@ "7": { "benchmarks": { "rendering.mobile": { - "begin": 410, + "begin": 406, + "abridged": false + }, + "speedometer": { + "abridged": false + }, + "speedometer2": { "abridged": false }, "system_health.memory_desktop": { - "end": 26, + "end": 27, "abridged": false } } @@ -91,7 +100,7 @@ "8": { "benchmarks": { "system_health.memory_desktop": { - "begin": 26, + "begin": 27, "end": 50, "abridged": false } @@ -106,20 +115,20 @@ } }, "extra_infos": { - "num_stories": 519, - "predicted_min_shard_time": 1417.0, - "predicted_min_shard_index": 6, - "predicted_max_shard_time": 1444.0, - "predicted_max_shard_index": 9, - "shard #0": 1420.0, - "shard #1": 1427.0, - "shard #2": 1429.0, - "shard #3": 1426.0, - "shard #4": 1443.0, - "shard #5": 1422.0, - "shard #6": 1417.0, - "shard #7": 1427.0, - "shard #8": 1419.0, - "shard #9": 1444.0 + "num_stories": 522, + "predicted_min_shard_time": 1662.0, + "predicted_min_shard_index": 9, + "predicted_max_shard_time": 1707.0, + "predicted_max_shard_index": 7, + "shard #0": 1688.0, + "shard #1": 1700.0, + "shard #2": 1694.0, + "shard #3": 1702.0, + "shard #4": 1690.0, + "shard #5": 1697.0, + "shard #6": 1670.0, + "shard #7": 1707.0, + "shard #8": 1689.0, + "shard #9": 1662.0 } } \ No newline at end of file
diff --git a/tools/perf/core/shard_maps/fuchsia-perf-sherlock-fyi_map.json b/tools/perf/core/shard_maps/fuchsia-perf-sherlock-fyi_map.json index 5f3107d..db8a7d7 100644 --- a/tools/perf/core/shard_maps/fuchsia-perf-sherlock-fyi_map.json +++ b/tools/perf/core/shard_maps/fuchsia-perf-sherlock-fyi_map.json
@@ -1,11 +1,14 @@ { "0": { "benchmarks": { + "jetstream2": { + "abridged": false + }, "media.mobile": { "abridged": false }, "rendering.mobile": { - "end": 43, + "end": 37, "abridged": false } }, @@ -25,8 +28,8 @@ "1": { "benchmarks": { "rendering.mobile": { - "begin": 43, - "end": 153, + "begin": 37, + "end": 121, "abridged": false } } @@ -34,8 +37,8 @@ "2": { "benchmarks": { "rendering.mobile": { - "begin": 153, - "end": 313, + "begin": 121, + "end": 250, "abridged": false } } @@ -43,8 +46,8 @@ "3": { "benchmarks": { "rendering.mobile": { - "begin": 313, - "end": 396, + "begin": 250, + "end": 346, "abridged": false } } @@ -52,34 +55,40 @@ "4": { "benchmarks": { "rendering.mobile": { - "begin": 396, - "abridged": false - }, - "system_health.memory_desktop": { - "end": 34, + "begin": 346, + "end": 420, "abridged": false } } }, "5": { "benchmarks": { + "rendering.mobile": { + "begin": 420, + "abridged": false + }, + "speedometer": { + "abridged": false + }, + "speedometer2": { + "abridged": false + }, "system_health.memory_desktop": { - "begin": 34, "abridged": false } } }, "extra_infos": { - "num_stories": 519, - "predicted_min_shard_time": 2109.0, - "predicted_min_shard_index": 4, - "predicted_max_shard_time": 2192.0, + "num_stories": 522, + "predicted_min_shard_time": 1945.0, + "predicted_min_shard_index": 3, + "predicted_max_shard_time": 1977.0, "predicted_max_shard_index": 5, - "shard #0": 2144.0, - "shard #1": 2157.0, - "shard #2": 2161.0, - "shard #3": 2155.0, - "shard #4": 2109.0, - "shard #5": 2192.0 + "shard #0": 1965.0, + "shard #1": 1964.0, + "shard #2": 1959.0, + "shard #3": 1945.0, + "shard #4": 1964.0, + "shard #5": 1977.0 } } \ No newline at end of file
diff --git a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-fyi_timing.json b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-fyi_timing.json index 19386d1..b9bbdef 100644 --- a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-fyi_timing.json +++ b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-fyi_timing.json
@@ -1,14 +1,14 @@ [ { - "duration": "11.0", + "duration": "10.0", "name": "media.mobile/mse.html?media=aac_audio.mp4" }, { - "duration": "13.0", + "duration": "12.0", "name": "media.mobile/mse.html?media=aac_audio.mp4,h264_video.mp4" }, { - "duration": "12.0", + "duration": "11.0", "name": "media.mobile/mse.html?media=h264_video.mp4" }, { @@ -36,7 +36,7 @@ "name": "media.mobile/video.html?src=tulip2.mp3&type=audio&seek" }, { - "duration": "26.0", + "duration": "27.0", "name": "media.mobile/video.html?src=tulip2.mp4" }, { @@ -48,7 +48,7 @@ "name": "media.mobile/video.html?src=tulip2.ogg&type=audio" }, { - "duration": "13.0", + "duration": "7.0", "name": "media.mobile/video.html?src=tulip2.ogg&type=audio&seek" }, { @@ -56,7 +56,7 @@ "name": "media.mobile/video.html?src=tulip2.vp9.webm" }, { - "duration": "4.0", + "duration": "3.0", "name": "media.mobile/video.html?src=tulip2.vp9.webm&background" }, { @@ -64,11 +64,11 @@ "name": "media.mobile/video.html?src=tulip2.vp9.webm_WiFi" }, { - "duration": "42.0", + "duration": "41.0", "name": "rendering.mobile/accu_weather_2018" }, { - "duration": "11.0", + "duration": "10.0", "name": "rendering.mobile/accu_weather_mobile_pinch_2018" }, { @@ -76,1263 +76,1263 @@ "name": "rendering.mobile/amazon_2018" }, { - "duration": "34.0", + "duration": "32.0", "name": "rendering.mobile/amazon_mobile_2018" }, { - "duration": "24.0", + "duration": "23.0", "name": "rendering.mobile/analog_clock_svg" }, { - "duration": "50.0", + "duration": "49.0", "name": "rendering.mobile/androidpolice_mobile_2018" }, { - "duration": "31.0", + "duration": "29.0", "name": "rendering.mobile/animometer_webgl" }, { - "duration": "27.0", + "duration": "26.0", "name": "rendering.mobile/animometer_webgl_attrib_arrays" }, { - "duration": "27.0", + "duration": "34.0", "name": "rendering.mobile/animometer_webgl_multi_draw" }, { - "duration": "33.0", + "duration": "41.0", "name": "rendering.mobile/aquarium" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/aquarium_20k" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/background_color_animation" }, { - "duration": "24.0", + "duration": "31.0", "name": "rendering.mobile/background_color_animation_with_gradient" }, { - "duration": "23.0", + "duration": "34.0", "name": "rendering.mobile/baidu_mobile_2018" }, { - "duration": "31.0", + "duration": "38.0", "name": "rendering.mobile/balls_css_key_frame_animations" }, { - "duration": "36.0", + "duration": "43.0", "name": "rendering.mobile/balls_css_key_frame_animations_composited_transform" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/balls_css_transition_2_properties" }, { - "duration": "26.0", + "duration": "32.0", "name": "rendering.mobile/balls_css_transition_40_properties" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/balls_css_transition_all_properties" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/balls_javascript_canvas" }, { - "duration": "27.0", + "duration": "34.0", "name": "rendering.mobile/balls_javascript_css" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/balls_svg_animations" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/basic_stream" }, { - "duration": "24.0", + "duration": "31.0", "name": "rendering.mobile/bing_mobile_2018" }, { - "duration": "29.0", + "duration": "36.0", "name": "rendering.mobile/blob" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/blogspot_2018" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/blogspot_mobile_2018" }, { - "duration": "20.0", + "duration": "27.0", "name": "rendering.mobile/blur_rotating_background" }, { - "duration": "39.0", + "duration": "45.0", "name": "rendering.mobile/boingboing_mobile_2018" }, { - "duration": "33.0", + "duration": "44.0", "name": "rendering.mobile/booking.com_2018" }, { - "duration": "30.0", + "duration": "38.0", "name": "rendering.mobile/booking.com_mobile_2018" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/bouncing_balls_15" }, { - "duration": "39.0", + "duration": "46.0", "name": "rendering.mobile/bouncing_balls_shadow" }, { - "duration": "26.0", + "duration": "33.0", "name": "rendering.mobile/bouncing_clipped_rectangles" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/bouncing_gradient_circles" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/bouncing_png_images" }, { - "duration": "31.0", + "duration": "38.0", "name": "rendering.mobile/bouncing_svg_images" }, { - "duration": "26.0", + "duration": "33.0", "name": "rendering.mobile/camera_to_webgl" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/canvas2d_to_texture.html" }, { - "duration": "34.0", + "duration": "38.0", "name": "rendering.mobile/canvas_05000_pixels_per_second" }, { - "duration": "34.0", + "duration": "44.0", "name": "rendering.mobile/canvas_10000_pixels_per_second" }, { - "duration": "28.0", + "duration": "33.0", "name": "rendering.mobile/canvas_20000_pixels_per_second" }, { - "duration": "28.0", + "duration": "33.0", "name": "rendering.mobile/canvas_40000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/canvas_60000_pixels_per_second" }, { - "duration": "28.0", + "duration": "32.0", "name": "rendering.mobile/canvas_75000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/canvas_90000_pixels_per_second" }, { - "duration": "24.0", + "duration": "31.0", "name": "rendering.mobile/canvas_animation_no_clear" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/canvas_arcs" }, { - "duration": "27.0", + "duration": "34.0", "name": "rendering.mobile/canvas_font_cycler" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/canvas_lines" }, { - "duration": "26.0", + "duration": "33.0", "name": "rendering.mobile/canvas_to_blob" }, { - "duration": "24.0", + "duration": "31.0", "name": "rendering.mobile/canvas_to_canvas_draw" }, { - "duration": "37.0", + "duration": "44.0", "name": "rendering.mobile/capitolvolkswagen_mobile_2018" }, { - "duration": "13.0", + "duration": "17.0", "name": "rendering.mobile/card_expansion" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/card_expansion_animated" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/card_expansion_images_text" }, { - "duration": "13.0", + "duration": "17.0", "name": "rendering.mobile/card_flying" }, { - "duration": "28.0", + "duration": "35.0", "name": "rendering.mobile/cc_poster_circle" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/cc_scroll_text_only" }, { - "duration": "28.0", + "duration": "35.0", "name": "rendering.mobile/chip_tune" }, { - "duration": "54.0", + "duration": "64.0", "name": "rendering.mobile/cnn_2018" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/cnn_article_mobile_2018" }, { - "duration": "52.0", + "duration": "60.0", "name": "rendering.mobile/cnn_mobile_2018" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/cnn_mobile_pinch_2018" }, { - "duration": "49.0", + "duration": "55.0", "name": "rendering.mobile/cnn_pathological_2018" }, { - "duration": "24.0", + "duration": "32.0", "name": "rendering.mobile/compositor_heavy_animation" }, { - "duration": "15.0", + "duration": "19.0", "name": "rendering.mobile/coordinated_animation" }, { - "duration": "25.0", + "duration": "32.0", "name": "rendering.mobile/crafty_mind" }, { - "duration": "32.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_many_keyframes" }, { - "duration": "26.0", + "duration": "43.0", "name": "rendering.mobile/css_animations_simultaneous_inline_style" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_animations_simultaneous_new_element" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_animations_simultaneous_style_element" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_animations_simultaneous_updating_class" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_animations_staggered_infinite_iterations" }, { - "duration": "27.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_staggered_inline_style" }, { - "duration": "27.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_staggered_new_element" }, { - "duration": "28.0", + "duration": "40.0", "name": "rendering.mobile/css_animations_staggered_style_element" }, { - "duration": "27.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_staggered_updating_class" }, { - "duration": "28.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_triggered_inline_style" }, { - "duration": "27.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_triggered_new_element" }, { - "duration": "27.0", + "duration": "38.0", "name": "rendering.mobile/css_animations_triggered_style_element" }, { - "duration": "28.0", + "duration": "39.0", "name": "rendering.mobile/css_animations_triggered_updating_class" }, { - "duration": "27.0", + "duration": "34.0", "name": "rendering.mobile/css_opacity_plus_n_layers_0" }, { - "duration": "28.0", + "duration": "35.0", "name": "rendering.mobile/css_opacity_plus_n_layers_75" }, { - "duration": "29.0", + "duration": "37.0", "name": "rendering.mobile/css_opacity_plus_n_layers_99" }, { - "duration": "25.0", + "duration": "37.0", "name": "rendering.mobile/css_transitions_inline_style" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_transitions_new_element" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_staggered_inline_style" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_staggered_new_element" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_staggered_style_element" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_staggered_updating_class" }, { - "duration": "25.0", + "duration": "37.0", "name": "rendering.mobile/css_transitions_style_element" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_triggered_inline_style" }, { - "duration": "27.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_triggered_new_element" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_transitions_triggered_style_element" }, { - "duration": "26.0", + "duration": "38.0", "name": "rendering.mobile/css_transitions_triggered_updating_class" }, { - "duration": "25.0", + "duration": "37.0", "name": "rendering.mobile/css_transitions_updating_class" }, { - "duration": "24.0", + "duration": "36.0", "name": "rendering.mobile/css_value_type_color" }, { - "duration": "24.0", + "duration": "36.0", "name": "rendering.mobile/css_value_type_filter" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_value_type_length" }, { - "duration": "24.0", + "duration": "36.0", "name": "rendering.mobile/css_value_type_length_complex" }, { - "duration": "24.0", + "duration": "36.0", "name": "rendering.mobile/css_value_type_length_simple" }, { - "duration": "24.0", + "duration": "36.0", "name": "rendering.mobile/css_value_type_path" }, { - "duration": "24.0", + "duration": "35.0", "name": "rendering.mobile/css_value_type_shadow" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/css_value_type_transform_complex" }, { - "duration": "27.0", + "duration": "37.0", "name": "rendering.mobile/css_value_type_transform_simple" }, { - "duration": "27.0", + "duration": "42.0", "name": "rendering.mobile/deviantart_mobile_2018" }, { - "duration": "11.0", + "duration": "22.0", "name": "rendering.mobile/digg_mobile_2018" }, { - "duration": "11.0", + "duration": "22.0", "name": "rendering.mobile/docs_paper.html" }, { - "duration": "25.0", + "duration": "36.0", "name": "rendering.mobile/docs_resume.html" }, { - "duration": "25.0", + "duration": "36.0", "name": "rendering.mobile/docs_table.html" }, { - "duration": "25.0", + "duration": "36.0", "name": "rendering.mobile/draw_image" }, { - "duration": "25.0", + "duration": "36.0", "name": "rendering.mobile/draw_image_not_pixel_aligned" }, { - "duration": "25.0", + "duration": "36.0", "name": "rendering.mobile/dynamic_canvas_to_hw_accelerated_canvas.html" }, { - "duration": "27.0", + "duration": "41.0", "name": "rendering.mobile/dynamic_cube_map" }, { - "duration": "28.0", + "duration": "36.0", "name": "rendering.mobile/dynamic_webgl_to_hw_accelerated_canvas.html" }, { - "duration": "24.0", + "duration": "39.0", "name": "rendering.mobile/earth" }, { - "duration": "27.0", + "duration": "43.0", "name": "rendering.mobile/ebay_2018" }, { - "duration": "20.0", + "duration": "34.0", "name": "rendering.mobile/ebay_mobile_2018" }, { - "duration": "8.0", + "duration": "22.0", "name": "rendering.mobile/ebay_mobile_pinch_2018" }, { - "duration": "26.0", + "duration": "30.0", "name": "rendering.mobile/ebay_scroll_2018" }, { - "duration": "26.0", + "duration": "40.0", "name": "rendering.mobile/effect_games" }, { - "duration": "8.0", + "duration": "22.0", "name": "rendering.mobile/espn_2018" }, { - "duration": "54.0", + "duration": "65.0", "name": "rendering.mobile/espn_mobile_2018" }, { - "duration": "25.0", + "duration": "40.0", "name": "rendering.mobile/espn_pathological_2018" }, { - "duration": "23.0", + "duration": "37.0", "name": "rendering.mobile/extra_large_texture_uploads" }, { - "duration": "8.0", + "duration": "22.0", "name": "rendering.mobile/facebook_2018" }, { - "duration": "8.0", + "duration": "22.0", "name": "rendering.mobile/facebook_mobile_2018" }, { - "duration": "21.0", + "duration": "36.0", "name": "rendering.mobile/falling_particle_simulation_cpu.html" }, { - "duration": "22.0", + "duration": "36.0", "name": "rendering.mobile/falling_particle_simulation_gpu.html" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/famo_us_twitter_demo" }, { - "duration": "22.0", + "duration": "36.0", "name": "rendering.mobile/fill_clear_rect.html" }, { - "duration": "22.0", + "duration": "36.0", "name": "rendering.mobile/fill_shapes" }, { - "duration": "20.0", + "duration": "18.0", "name": "rendering.mobile/filter_terrain_svg" }, { - "duration": "26.0", + "duration": "30.0", "name": "rendering.mobile/flickr_scroll_2018" }, { - "duration": "15.0", + "duration": "19.0", "name": "rendering.mobile/font_wipe" }, { - "duration": "17.0", + "duration": "19.0", "name": "rendering.mobile/forecast.io_mobile_2018" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/get_image_data_cpu.html" }, { - "duration": "22.0", + "duration": "19.0", "name": "rendering.mobile/get_image_data_gpu.html" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/gmail_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/google_calendar_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/google_docs_2018" }, { - "duration": "20.0", + "duration": "21.0", "name": "rendering.mobile/google_image_search_2018" }, { - "duration": "19.0", + "duration": "17.0", "name": "rendering.mobile/google_image_search_mobile_2018" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/google_news_ios" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/google_news_mobile_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/google_plus_2018" }, { - "duration": "14.0", + "duration": "12.0", "name": "rendering.mobile/google_plus_mobile_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/google_search_mobile_pinch_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/google_web_search_2018" }, { - "duration": "17.0", + "duration": "15.0", "name": "rendering.mobile/google_web_search_mobile_2018" }, { - "duration": "32.0", + "duration": "23.0", "name": "rendering.mobile/gpu_bound_shader.html" }, { - "duration": "32.0", + "duration": "30.0", "name": "rendering.mobile/gsp.ro_mobile_2018" }, { - "duration": "25.0", + "duration": "18.0", "name": "rendering.mobile/guardian_pathological_2018" }, { - "duration": "22.0", + "duration": "20.0", "name": "rendering.mobile/guimark_vector_chart" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/gws_boogie_expansion" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/gws_google_expansion" }, { - "duration": "24.0", + "duration": "23.0", "name": "rendering.mobile/hakim" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/horizontal_vertical_expansion" }, { - "duration": "22.0", + "duration": "20.0", "name": "rendering.mobile/hw_accelerated_canvas_to_sw_canvas.html" }, { - "duration": "11.0", + "duration": "10.0", "name": "rendering.mobile/idle_power_animated_gif" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/idle_power_blank" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/idle_power_css_animation" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/idle_power_request_animation_frame" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/idle_power_set_timeout_long" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/idle_power_set_timetout" }, { - "duration": "11.0", + "duration": "18.0", "name": "rendering.mobile/ie_chalkboard" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/ie_pirate_mark" }, { - "duration": "24.0", + "duration": "21.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_0" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_75" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_99" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_0" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_75" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_99" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_0" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_75" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_99" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/infinite_scrolling" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/jarro_doverson" }, { - "duration": "15.0", + "duration": "13.0", "name": "rendering.mobile/jpeg_decoding_rgb_and_gpu_rasterization" }, { - "duration": "15.0", + "duration": "13.0", "name": "rendering.mobile/jpeg_decoding_yuv_and_gpu_rasterization" }, { - "duration": "27.0", + "duration": "25.0", "name": "rendering.mobile/js_full_screen_invalidation" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/js_opacity_plus_n_layers_0" }, { - "duration": "26.0", + "duration": "24.0", "name": "rendering.mobile/js_opacity_plus_n_layers_75" }, { - "duration": "28.0", + "duration": "26.0", "name": "rendering.mobile/js_opacity_plus_n_layers_99" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/js_paint_plus_n_layers_0" }, { - "duration": "26.0", + "duration": "24.0", "name": "rendering.mobile/js_paint_plus_n_layers_75" }, { - "duration": "28.0", + "duration": "26.0", "name": "rendering.mobile/js_paint_plus_n_layers_99" }, { - "duration": "26.0", + "duration": "24.0", "name": "rendering.mobile/js_poster_circle" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/js_scroll_text_only" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/kevs_3d" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/keyframed_animations" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/large_texture_uploads" }, { - "duration": "31.0", + "duration": "32.0", "name": "rendering.mobile/latimes_pathological_2018" }, { - "duration": "17.0", + "duration": "14.0", "name": "rendering.mobile/linkedin_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/linkedin_mobile_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/linkedin_mobile_pinch_2018" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/linkedin_pathological_2018" }, { - "duration": "12.0", + "duration": "16.0", "name": "rendering.mobile/list_animation_simple" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/list_recycle_transform" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_0fps_impl_60fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_0fps_impl_60fps_no_update" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_0fps_impl_60fps_no_update_jank" }, { - "duration": "21.0", + "duration": "18.0", "name": "rendering.mobile/main_0fps_with_jank_impl_0fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_15fps_impl_0fps" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_15fps_with_jank_impl_0fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_30fps_impl_0fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_30fps_impl_60fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_60fps_impl_0fps" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_60fps_impl_60fps" }, { - "duration": "21.0", + "duration": "19.0", "name": "rendering.mobile/main_60fps_impl_60fps_no_update" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_60fps_impl_60fps_no_update_jank" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_60fps_with_extreme_jank_impl_0fps" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_60fps_with_jank_and_delay_impl_60fps" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_60fps_with_jank_impl_0fps" }, { - "duration": "8.0", + "duration": "6.0", "name": "rendering.mobile/main_animations_half_presented" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/man_in_blue" }, { - "duration": "30.0", + "duration": "36.0", "name": "rendering.mobile/many_images" }, { - "duration": "25.0", + "duration": "27.0", "name": "rendering.mobile/many_planets_deep" }, { - "duration": "29.0", + "duration": "31.0", "name": "rendering.mobile/maps_perf_test" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/mask_transition_animation" }, { - "duration": "20.0", + "duration": "21.0", "name": "rendering.mobile/masonry" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/medium_texture_uploads" }, { - "duration": "21.0", + "duration": "24.0", "name": "rendering.mobile/megi_dish" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/microgame_fps" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_asteroid_belt" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/microsoft_fireflies" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_fish_ie_tank" }, { - "duration": "21.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_performance" }, { - "duration": "21.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_snow" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_speed_reading" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_tweet_map" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_video_city" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/microsoft_worker_fountains" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/mix_10k" }, { - "duration": "21.0", + "duration": "23.0", "name": "rendering.mobile/mix_blend_mode_animation_difference" }, { - "duration": "21.0", + "duration": "23.0", "name": "rendering.mobile/mix_blend_mode_animation_hue" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/mix_blend_mode_animation_propagating_isolation" }, { - "duration": "21.0", + "duration": "23.0", "name": "rendering.mobile/mix_blend_mode_animation_screen" }, { - "duration": "49.0", + "duration": "51.0", "name": "rendering.mobile/mlb_mobile_2018" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/mobile_news_sandbox" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/motion_mark_canvas_fill_shapes" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/motion_mark_canvas_stroke_shapes" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_design_15" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_focus_25" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_images_50" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_leaves_250" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_multiply_175" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_anim_suits_125" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_composited_transforms_125" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_blend_circles_25" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_circles_250" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_clipped_rects_100" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_filter_circles_15" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_gradient_circles_250" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_svg_images_50" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_css_bouncing_tagged_images_225" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_dom_particles_svg_masks_25" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_focus_20_15" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_html_leaves_20_50" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_canvas_arcs" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_canvas_lines" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_design" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_images" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_leaves" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_multiply" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_paths" }, { - "duration": "8.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_ramp_suits" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_svg_bouncing_circles_250" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_svg_bouncing_clipped_rects_100" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_svg_bouncing_gradient_circles_200" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_svg_bouncing_png_images_200" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/motionmark_svg_bouncing_svg_images_50" }, { - "duration": "23.0", + "duration": "27.0", "name": "rendering.mobile/new_tilings" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/no_op_raf" }, { - "duration": "15.0", + "duration": "20.0", "name": "rendering.mobile/no_op_scroll" }, { - "duration": "14.0", + "duration": "19.0", "name": "rendering.mobile/no_op_settimeout" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/no_op_touch_handler" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/no_update_compositor_animation_with_janky_main_animation" }, { - "duration": "31.0", + "duration": "35.0", "name": "rendering.mobile/non_opaque_background_compositor_thread_scrolling_00050_pixels_per_second" }, { - "duration": "31.0", + "duration": "35.0", "name": "rendering.mobile/non_opaque_background_main_thread_scrolling_00050_pixels_per_second" }, { - "duration": "22.0", + "duration": "25.0", "name": "rendering.mobile/nvidia_vertex_buffer_object" }, { - "duration": "26.0", + "duration": "30.0", "name": "rendering.mobile/nyc_gov_scroll_2018" }, { - "duration": "58.0", + "duration": "54.0", "name": "rendering.mobile/nytimes_mobile_2018" }, { - "duration": "49.0", + "duration": "47.0", "name": "rendering.mobile/nytimes_scroll_2018" }, { - "duration": "18.0", + "duration": "22.0", "name": "rendering.mobile/off_screen_main_60fps" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/off_screen_main_60fps_jank" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/offscreen_animation_no_damage" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/overlay_background_color_css_transitions_page" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/paint_worklet" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/parallax_effect" }, { - "duration": "22.0", + "duration": "26.0", "name": "rendering.mobile/particles" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/pbs_pathological_2018" }, { - "duration": "12.0", + "duration": "16.0", "name": "rendering.mobile/physical_simulation" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/pinterest_2018" }, { - "duration": "14.0", + "duration": "16.0", "name": "rendering.mobile/pinterest_mobile_2018" }, { - "duration": "22.0", + "duration": "26.0", "name": "rendering.mobile/put_and_create_imagebitmap_from_imagedata" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/put_get_image_data" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/put_image_data.html" }, { - "duration": "16.0", + "duration": "21.0", "name": "rendering.mobile/raf" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/raf_animation" }, { - "duration": "16.0", + "duration": "21.0", "name": "rendering.mobile/raf_canvas" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/raf_touch_animation" }, { - "duration": "34.0", + "duration": "40.0", "name": "rendering.mobile/recode_pathological_2018" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/reddit_mobile_2018" }, { - "duration": "20.0", + "duration": "25.0", "name": "rendering.mobile/runway_2019" }, { - "duration": "23.0", + "duration": "28.0", "name": "rendering.mobile/san_angeles" }, { - "duration": "10.0", + "duration": "14.0", "name": "rendering.mobile/second_batch_js_heavy" }, { - "duration": "10.0", + "duration": "14.0", "name": "rendering.mobile/second_batch_js_light" }, { - "duration": "9.0", + "duration": "14.0", "name": "rendering.mobile/second_batch_js_medium" }, { - "duration": "52.0", + "duration": "62.0", "name": "rendering.mobile/sfgate_mobile_2018" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/sheets_render.html" }, { - "duration": "21.0", + "duration": "25.0", "name": "rendering.mobile/silk_finance" }, { - "duration": "27.0", + "duration": "20.0", "name": "rendering.mobile/simple_text_page" }, { - "duration": "17.0", + "duration": "26.0", "name": "rendering.mobile/simple_touch_drag" }, { - "duration": "63.0", + "duration": "62.0", "name": "rendering.mobile/skelebuddies_wasm_2020" }, { - "duration": "37.0", + "duration": "32.0", "name": "rendering.mobile/slashdot_mobile_2018" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/small_texture_uploads" }, { @@ -1340,371 +1340,375 @@ "name": "rendering.mobile/smash_cat" }, { - "duration": "26.0", + "duration": "24.0", "name": "rendering.mobile/spielzeugz" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/static_canvas_to_hw_accelerated_canvas.html" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/static_webgl_to_hw_accelerated_canvas.html" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/sticky_using_webkit" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/stroke_shapes" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/svg_icon_raster" }, { - "duration": "13.0", + "duration": "17.0", "name": "rendering.mobile/swipe_to_dismiss" }, { - "duration": "21.0", + "duration": "35.0", "name": "rendering.mobile/sync_scroll_offset" }, { - "duration": "48.0", + "duration": "58.0", "name": "rendering.mobile/techcrunch_2018" }, { - "duration": "44.0", + "duration": "58.0", "name": "rendering.mobile/techcrunch_mobile_2018" }, { - "duration": "32.0", + "duration": "37.0", "name": "rendering.mobile/text_05000_pixels_per_second" }, { - "duration": "33.0", + "duration": "37.0", "name": "rendering.mobile/text_10000_pixels_per_second" }, { - "duration": "27.0", + "duration": "33.0", "name": "rendering.mobile/text_20000_pixels_per_second" }, { - "duration": "28.0", + "duration": "32.0", "name": "rendering.mobile/text_40000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_60000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/text_75000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_90000_pixels_per_second" }, { - "duration": "28.0", + "duration": "32.0", "name": "rendering.mobile/text_constant_full_page_raster_05000_pixels_per_second" }, { - "duration": "28.0", + "duration": "32.0", "name": "rendering.mobile/text_constant_full_page_raster_10000_pixels_per_second" }, { - "duration": "29.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_20000_pixels_per_second" }, { - "duration": "26.0", + "duration": "31.0", "name": "rendering.mobile/text_constant_full_page_raster_40000_pixels_per_second" }, { - "duration": "28.0", + "duration": "32.0", "name": "rendering.mobile/text_constant_full_page_raster_60000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_constant_full_page_raster_75000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_constant_full_page_raster_90000_pixels_per_second" }, { - "duration": "29.0", + "duration": "33.0", + "name": "rendering.mobile/text_fling_05000_pixels_per_second" + }, + { + "duration": "26.0", "name": "rendering.mobile/text_fling_10000_pixels_per_second" }, { - "duration": "30.0", + "duration": "28.0", "name": "rendering.mobile/text_fling_20000_pixels_per_second" }, { - "duration": "32.0", + "duration": "37.0", "name": "rendering.mobile/text_hover_05000_pixels_per_second" }, { - "duration": "33.0", + "duration": "37.0", "name": "rendering.mobile/text_hover_10000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/text_hover_20000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/text_hover_40000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_hover_60000_pixels_per_second" }, { - "duration": "27.0", + "duration": "32.0", "name": "rendering.mobile/text_hover_75000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_hover_90000_pixels_per_second" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/text_scrollbar_100_pixels_per_second" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/text_scrollbar_1200_pixels_per_second" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/text_scrollbar_200_pixels_per_second" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/text_scrollbar_2300_pixels_per_second" }, { - "duration": "5.0", + "duration": "9.0", "name": "rendering.mobile/text_scrollbar_700_pixels_per_second" }, { - "duration": "40.0", + "duration": "47.0", "name": "rendering.mobile/theverge_article_mobile_2018" }, { - "duration": "42.0", + "duration": "52.0", "name": "rendering.mobile/theverge_mobile_2018" }, { - "duration": "29.0", + "duration": "38.0", "name": "rendering.mobile/throughput_scrolling_active_handler" }, { - "duration": "29.0", + "duration": "38.0", "name": "rendering.mobile/throughput_scrolling_composited" }, { - "duration": "29.0", + "duration": "38.0", "name": "rendering.mobile/throughput_scrolling_passive_handler" }, { - "duration": "30.0", + "duration": "39.0", "name": "rendering.mobile/throughput_scrolling_uncomposited" }, { - "duration": "59.0", + "duration": "72.0", "name": "rendering.mobile/tiny_racing_v3_wasm_2020" }, { - "duration": "25.0", + "duration": "34.0", "name": "rendering.mobile/toBlob_duration.html" }, { - "duration": "26.0", + "duration": "34.0", "name": "rendering.mobile/toBlob_duration_jpeg.html" }, { - "duration": "28.0", + "duration": "36.0", "name": "rendering.mobile/toBlob_small_canvas_in_worker.html" }, { - "duration": "21.0", + "duration": "30.0", "name": "rendering.mobile/touch_handler_scrolling" }, { - "duration": "24.0", + "duration": "33.0", "name": "rendering.mobile/transfer_from_imageBitmap.html" }, { - "duration": "25.0", + "duration": "33.0", "name": "rendering.mobile/transform_transitions" }, { - "duration": "24.0", + "duration": "33.0", "name": "rendering.mobile/transform_transitions_js_block" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/twitch_2018" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/twitch_mobile_pinch_2018" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/twitter_2018" }, { - "duration": "26.0", + "duration": "37.0", "name": "rendering.mobile/twitter_mobile_2018" }, { - "duration": "22.0", + "duration": "30.0", "name": "rendering.mobile/update_history_state" }, { - "duration": "40.0", + "duration": "50.0", "name": "rendering.mobile/usatoday_mobile_2018" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/vertical_expansion" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/video_to_hw_accelerated_canvas" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/video_to_sub_texture" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/video_to_sub_texture_flip_and_premultiply" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/video_to_sub_texture_flip_y" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/video_to_sub_texture_premultiply" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/video_to_texture" }, { - "duration": "25.0", + "duration": "33.0", "name": "rendering.mobile/web_animation_value_type_color" }, { - "duration": "27.0", + "duration": "35.0", "name": "rendering.mobile/web_animation_value_type_length_3d" }, { - "duration": "25.0", + "duration": "33.0", "name": "rendering.mobile/web_animation_value_type_length_complex" }, { - "duration": "25.0", + "duration": "33.0", "name": "rendering.mobile/web_animation_value_type_length_simple" }, { - "duration": "25.0", + "duration": "33.0", "name": "rendering.mobile/web_animation_value_type_path" }, { - "duration": "24.0", + "duration": "33.0", "name": "rendering.mobile/web_animation_value_type_shadow" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/web_animation_value_type_transform_complex" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/web_animation_value_type_transform_simple" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/web_animations_many_keyframes" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/web_animations_set_current_time" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/web_animations_simultaneous" }, { - "duration": "27.0", + "duration": "36.0", "name": "rendering.mobile/web_animations_staggered_chaining" }, { - "duration": "26.0", + "duration": "35.0", "name": "rendering.mobile/web_animations_staggered_infinite_iterations" }, { - "duration": "28.0", + "duration": "37.0", "name": "rendering.mobile/web_animations_staggered_triggering_page" }, { - "duration": "25.0", + "duration": "34.0", "name": "rendering.mobile/webgl_to_texture" }, { - "duration": "19.0", + "duration": "27.0", "name": "rendering.mobile/webp_decoding_rgb_and_gpu_rasterization" }, { - "duration": "19.0", + "duration": "27.0", "name": "rendering.mobile/webp_decoding_yuv_and_gpu_rasterization" }, { - "duration": "32.0", + "duration": "40.0", "name": "rendering.mobile/wikipedia_2018" }, { - "duration": "31.0", + "duration": "40.0", "name": "rendering.mobile/wikipedia_delayed_scroll_start_2018" }, { - "duration": "27.0", + "duration": "36.0", "name": "rendering.mobile/wikipedia_mobile_2018" }, { - "duration": "11.0", + "duration": "20.0", "name": "rendering.mobile/wordpress_2018" }, { - "duration": "31.0", + "duration": "40.0", "name": "rendering.mobile/wordpress_mobile_2018" }, { - "duration": "39.0", + "duration": "48.0", "name": "rendering.mobile/worldjournal_mobile_2018" }, { - "duration": "46.0", + "duration": "49.0", "name": "rendering.mobile/wow_wiki_pathological_2018" }, { - "duration": "67.0", + "duration": "74.0", "name": "rendering.mobile/wowwiki_mobile_2018" }, { - "duration": "73.0", + "duration": "81.0", "name": "rendering.mobile/wsj_mobile_2018" }, { - "duration": "37.0", + "duration": "47.0", "name": "rendering.mobile/yahoo_answers_2018" }, { @@ -1716,15 +1720,15 @@ "name": "rendering.mobile/yahoo_news_2018" }, { - "duration": "35.0", + "duration": "33.0", "name": "rendering.mobile/yahoo_news_mobile_2018" }, { - "duration": "43.0", + "duration": "40.0", "name": "rendering.mobile/yahoo_sports_2018" }, { - "duration": "42.0", + "duration": "40.0", "name": "rendering.mobile/yahoo_sports_pathological_2018" }, { @@ -1736,11 +1740,11 @@ "name": "rendering.mobile/youtube_mobile_2018" }, { - "duration": "40.0", + "duration": "41.0", "name": "rendering.mobile/zdnet_pathological_2018" }, { - "duration": "13.0", + "duration": "17.0", "name": "rendering.mobile/zoom_in_animation" }, { @@ -1752,23 +1756,23 @@ "name": "system_health.memory_desktop/browse:media:imgur" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:media:pinterest:2018" }, { - "duration": "2.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:media:tumblr:2018" }, { - "duration": "86.0", + "duration": "91.0", "name": "system_health.memory_desktop/browse:media:youtube:2019" }, { - "duration": "2.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:media:youtubetv:2019" }, { - "duration": "2.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:media:youtubetv_watch:2020" }, { @@ -1776,19 +1780,19 @@ "name": "system_health.memory_desktop/browse:news:cnn:2021" }, { - "duration": "58.0", + "duration": "57.0", "name": "system_health.memory_desktop/browse:news:flipboard:2020" }, { - "duration": "64.0", + "duration": "69.0", "name": "system_health.memory_desktop/browse:news:hackernews:2020" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:news:nytimes:2020" }, { - "duration": "2.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:news:reddit:2020" }, { @@ -1804,14 +1808,18 @@ "name": "system_health.memory_desktop/browse:social:facebook_infinite_scroll:2018" }, { - "duration": "66.0", + "duration": "68.0", "name": "system_health.memory_desktop/browse:social:tumblr_infinite_scroll:2018" }, { - "duration": "2.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:social:twitter:2018" }, { + "duration": "5.0", + "name": "system_health.memory_desktop/browse:social:twitter_infinite_scroll:2018" + }, + { "duration": "1.0", "name": "system_health.memory_desktop/browse:tech:discourse_infinite_scroll:2018" }, @@ -1820,7 +1828,7 @@ "name": "system_health.memory_desktop/browse:tools:autocad:2021" }, { - "duration": "38.0", + "duration": "39.0", "name": "system_health.memory_desktop/browse:tools:docs_scrolling" }, { @@ -1844,11 +1852,11 @@ "name": "system_health.memory_desktop/browse:tools:maps:2019" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:tools:photoshop:2021" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/browse:tools:photoshop_warm:2021" }, { @@ -1856,7 +1864,7 @@ "name": "system_health.memory_desktop/browse:tools:sheets:2019" }, { - "duration": "35.0", + "duration": "36.0", "name": "system_health.memory_desktop/browse_accessibility:media:youtube" }, { @@ -1864,123 +1872,123 @@ "name": "system_health.memory_desktop/browse_accessibility:tech:codesearch:2018" }, { - "duration": "12.0", + "duration": "13.0", "name": "system_health.memory_desktop/load:chrome:blank" }, { - "duration": "20.0", + "duration": "19.0", "name": "system_health.memory_desktop/load:games:alphabetty:2018" }, { - "duration": "15.0", + "duration": "20.0", "name": "system_health.memory_desktop/load:games:bubbles:2020" }, { - "duration": "17.0", + "duration": "22.0", "name": "system_health.memory_desktop/load:games:lazors" }, { - "duration": "25.0", + "duration": "30.0", "name": "system_health.memory_desktop/load:games:miniclip:2018" }, { - "duration": "3.0", + "duration": "4.0", "name": "system_health.memory_desktop/load:games:spychase:2018" }, { - "duration": "31.0", + "duration": "28.0", "name": "system_health.memory_desktop/load:media:9gag" }, { - "duration": "25.0", + "duration": "30.0", "name": "system_health.memory_desktop/load:media:dailymotion:2019" }, { - "duration": "2.0", + "duration": "7.0", "name": "system_health.memory_desktop/load:media:facebook_feed:desktop:2020" }, { - "duration": "16.0", + "duration": "20.0", "name": "system_health.memory_desktop/load:media:facebook_photos:2018" }, { - "duration": "2.0", + "duration": "7.0", "name": "system_health.memory_desktop/load:media:facebook_photos:desktop:2020" }, { - "duration": "23.0", + "duration": "28.0", "name": "system_health.memory_desktop/load:media:flickr:2018" }, { - "duration": "18.0", + "duration": "22.0", "name": "system_health.memory_desktop/load:media:google_images:2018" }, { - "duration": "43.0", + "duration": "63.0", "name": "system_health.memory_desktop/load:media:imgur:2018" }, { - "duration": "27.0", + "duration": "29.0", "name": "system_health.memory_desktop/load:media:soundcloud:2018" }, { - "duration": "27.0", + "duration": "30.0", "name": "system_health.memory_desktop/load:media:youtube:2018" }, { - "duration": "16.0", + "duration": "19.0", "name": "system_health.memory_desktop/load:media:youtubelivingroom:2020" }, { - "duration": "19.0", + "duration": "24.0", "name": "system_health.memory_desktop/load:news:bbc:2018" }, { - "duration": "3.0", + "duration": "7.0", "name": "system_health.memory_desktop/load:news:cnn:2020" }, { - "duration": "22.0", + "duration": "25.0", "name": "system_health.memory_desktop/load:news:flipboard" }, { - "duration": "14.0", + "duration": "18.0", "name": "system_health.memory_desktop/load:news:hackernews:2018" }, { - "duration": "46.0", + "duration": "45.0", "name": "system_health.memory_desktop/load:news:nytimes:2018" }, { - "duration": "29.0", + "duration": "27.0", "name": "system_health.memory_desktop/load:news:qq:2018" }, { - "duration": "3.0", + "duration": "4.0", "name": "system_health.memory_desktop/load:news:reddit:2018" }, { - "duration": "19.0", + "duration": "20.0", "name": "system_health.memory_desktop/load:news:wikipedia:2018" }, { - "duration": "24.0", + "duration": "23.0", "name": "system_health.memory_desktop/load:search:amazon:2018" }, { - "duration": "27.0", + "duration": "30.0", "name": "system_health.memory_desktop/load:search:baidu:2018" }, { - "duration": "30.0", + "duration": "32.0", "name": "system_health.memory_desktop/load:search:ebay:2018" }, { - "duration": "30.0", + "duration": "39.0", "name": "system_health.memory_desktop/load:search:flipkart:2018" }, { - "duration": "16.0", + "duration": "21.0", "name": "system_health.memory_desktop/load:search:google:2018" }, { @@ -1988,71 +1996,71 @@ "name": "system_health.memory_desktop/load:search:taobao:2018" }, { - "duration": "15.0", + "duration": "18.0", "name": "system_health.memory_desktop/load:search:yahoo:2018" }, { - "duration": "16.0", + "duration": "19.0", "name": "system_health.memory_desktop/load:search:yandex:2018" }, { - "duration": "15.0", + "duration": "20.0", "name": "system_health.memory_desktop/load:social:instagram:2018" }, { - "duration": "14.0", + "duration": "16.0", "name": "system_health.memory_desktop/load:social:pinterest:2019" }, { - "duration": "20.0", + "duration": "23.0", "name": "system_health.memory_desktop/load:social:vk:2018" }, { - "duration": "3.0", + "duration": "7.0", "name": "system_health.memory_desktop/load:tools:chat:2020" }, { - "duration": "43.0", + "duration": "47.0", "name": "system_health.memory_desktop/load:tools:docs:2019" }, { - "duration": "17.0", + "duration": "22.0", "name": "system_health.memory_desktop/load:tools:drive:2019" }, { - "duration": "2.0", + "duration": "7.0", "name": "system_health.memory_desktop/load:tools:gmail:2019" }, { - "duration": "23.0", + "duration": "25.0", "name": "system_health.memory_desktop/load:tools:stackoverflow:2018" }, { - "duration": "25.0", + "duration": "30.0", "name": "system_health.memory_desktop/load:tools:weather:2019" }, { - "duration": "16.0", + "duration": "17.0", "name": "system_health.memory_desktop/load_accessibility:media:wikipedia:2018" }, { - "duration": "36.0", + "duration": "37.0", "name": "system_health.memory_desktop/load_accessibility:shopping:amazon:2018" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/long_running:tools:gmail-background" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/long_running:tools:gmail-foreground" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/multitab:misc:typical24" }, { - "duration": "1.0", + "duration": "4.0", "name": "system_health.memory_desktop/multitab:misc:typical24:2018" }, { @@ -2060,7 +2068,7 @@ "name": "system_health.memory_desktop/play:media:google_play_music" }, { - "duration": "47.0", + "duration": "50.0", "name": "system_health.memory_desktop/play:media:soundcloud:2018" }, {
diff --git a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-sherlock-fyi_timing.json b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-sherlock-fyi_timing.json index 034b1371..13968f7 100644 --- a/tools/perf/core/shard_maps/timing_data/fuchsia-perf-sherlock-fyi_timing.json +++ b/tools/perf/core/shard_maps/timing_data/fuchsia-perf-sherlock-fyi_timing.json
@@ -1,14 +1,14 @@ [ { - "duration": "17.0", + "duration": "10.0", "name": "media.mobile/mse.html?media=aac_audio.mp4" }, { - "duration": "10.0", + "duration": "11.0", "name": "media.mobile/mse.html?media=aac_audio.mp4,h264_video.mp4" }, { - "duration": "14.0", + "duration": "10.0", "name": "media.mobile/mse.html?media=h264_video.mp4" }, { @@ -32,11 +32,11 @@ "name": "media.mobile/video.html?src=tulip2.mp3&type=audio" }, { - "duration": "6.0", + "duration": "7.0", "name": "media.mobile/video.html?src=tulip2.mp3&type=audio&seek" }, { - "duration": "24.0", + "duration": "25.0", "name": "media.mobile/video.html?src=tulip2.mp4" }, { @@ -64,7 +64,7 @@ "name": "media.mobile/video.html?src=tulip2.vp9.webm_WiFi" }, { - "duration": "32.0", + "duration": "31.0", "name": "rendering.mobile/accu_weather_2018" }, { @@ -76,7 +76,7 @@ "name": "rendering.mobile/amazon_2018" }, { - "duration": "30.0", + "duration": "29.0", "name": "rendering.mobile/amazon_mobile_2018" }, { @@ -84,7 +84,7 @@ "name": "rendering.mobile/analog_clock_svg" }, { - "duration": "38.0", + "duration": "37.0", "name": "rendering.mobile/androidpolice_mobile_2018" }, { @@ -92,15 +92,15 @@ "name": "rendering.mobile/animometer_webgl" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/animometer_webgl_attrib_arrays" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/animometer_webgl_multi_draw" }, { - "duration": "29.0", + "duration": "28.0", "name": "rendering.mobile/aquarium" }, { @@ -108,35 +108,35 @@ "name": "rendering.mobile/aquarium_20k" }, { - "duration": "24.0", + "duration": "23.0", "name": "rendering.mobile/background_color_animation" }, { - "duration": "22.0", + "duration": "21.0", "name": "rendering.mobile/background_color_animation_with_gradient" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/baidu_mobile_2018" }, { - "duration": "28.0", + "duration": "27.0", "name": "rendering.mobile/balls_css_key_frame_animations" }, { - "duration": "33.0", + "duration": "32.0", "name": "rendering.mobile/balls_css_key_frame_animations_composited_transform" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/balls_css_transition_2_properties" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/balls_css_transition_40_properties" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/balls_css_transition_all_properties" }, { @@ -152,7 +152,7 @@ "name": "rendering.mobile/balls_svg_animations" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/basic_stream" }, { @@ -168,7 +168,7 @@ "name": "rendering.mobile/blogspot_2018" }, { - "duration": "20.0", + "duration": "19.0", "name": "rendering.mobile/blogspot_mobile_2018" }, { @@ -176,7 +176,7 @@ "name": "rendering.mobile/blur_rotating_background" }, { - "duration": "35.0", + "duration": "36.0", "name": "rendering.mobile/boingboing_mobile_2018" }, { @@ -188,7 +188,7 @@ "name": "rendering.mobile/booking.com_mobile_2018" }, { - "duration": "22.0", + "duration": "21.0", "name": "rendering.mobile/bouncing_balls_15" }, { @@ -204,7 +204,7 @@ "name": "rendering.mobile/bouncing_gradient_circles" }, { - "duration": "22.0", + "duration": "21.0", "name": "rendering.mobile/bouncing_png_images" }, { @@ -212,83 +212,83 @@ "name": "rendering.mobile/bouncing_svg_images" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/camera_to_webgl" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/canvas2d_to_texture.html" }, { - "duration": "37.0", + "duration": "33.0", "name": "rendering.mobile/canvas_05000_pixels_per_second" }, { - "duration": "38.0", + "duration": "31.0", "name": "rendering.mobile/canvas_10000_pixels_per_second" }, { - "duration": "32.0", + "duration": "28.0", "name": "rendering.mobile/canvas_20000_pixels_per_second" }, { - "duration": "31.0", + "duration": "27.0", "name": "rendering.mobile/canvas_40000_pixels_per_second" }, { - "duration": "31.0", + "duration": "27.0", "name": "rendering.mobile/canvas_60000_pixels_per_second" }, { - "duration": "31.0", + "duration": "36.0", "name": "rendering.mobile/canvas_75000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/canvas_90000_pixels_per_second" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/canvas_animation_no_clear" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/canvas_arcs" }, { - "duration": "27.0", + "duration": "28.0", "name": "rendering.mobile/canvas_font_cycler" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/canvas_lines" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/canvas_to_blob" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/canvas_to_canvas_draw" }, { - "duration": "30.0", + "duration": "37.0", "name": "rendering.mobile/capitolvolkswagen_mobile_2018" }, { - "duration": "11.0", + "duration": "12.0", "name": "rendering.mobile/card_expansion" }, { - "duration": "12.0", + "duration": "13.0", "name": "rendering.mobile/card_expansion_animated" }, { - "duration": "12.0", + "duration": "13.0", "name": "rendering.mobile/card_expansion_images_text" }, { - "duration": "11.0", + "duration": "12.0", "name": "rendering.mobile/card_flying" }, { @@ -296,263 +296,263 @@ "name": "rendering.mobile/cc_poster_circle" }, { - "duration": "20.0", + "duration": "19.0", "name": "rendering.mobile/cc_scroll_text_only" }, { - "duration": "25.0", + "duration": "27.0", "name": "rendering.mobile/chip_tune" }, { - "duration": "43.0", + "duration": "42.0", "name": "rendering.mobile/cnn_2018" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/cnn_article_mobile_2018" }, { - "duration": "41.0", + "duration": "42.0", "name": "rendering.mobile/cnn_mobile_2018" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/cnn_mobile_pinch_2018" }, { - "duration": "39.0", + "duration": "40.0", "name": "rendering.mobile/cnn_pathological_2018" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/compositor_heavy_animation" }, { - "duration": "13.0", + "duration": "14.0", "name": "rendering.mobile/coordinated_animation" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/crafty_mind" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/css_animations_many_keyframes" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_animations_simultaneous_inline_style" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_animations_simultaneous_new_element" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_animations_simultaneous_style_element" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_animations_simultaneous_updating_class" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_animations_staggered_infinite_iterations" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_staggered_inline_style" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_staggered_new_element" }, { - "duration": "25.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_staggered_style_element" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_staggered_updating_class" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_triggered_inline_style" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/css_animations_triggered_new_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_animations_triggered_style_element" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/css_animations_triggered_updating_class" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/css_opacity_plus_n_layers_0" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/css_opacity_plus_n_layers_75" }, { - "duration": "26.0", + "duration": "30.0", "name": "rendering.mobile/css_opacity_plus_n_layers_99" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/css_transitions_inline_style" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/css_transitions_new_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_staggered_inline_style" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_staggered_new_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_staggered_style_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_staggered_updating_class" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/css_transitions_style_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_triggered_inline_style" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_triggered_new_element" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_transitions_triggered_style_element" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/css_transitions_triggered_updating_class" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/css_transitions_updating_class" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_color" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_filter" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/css_value_type_length" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_length_complex" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_length_simple" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_path" }, { - "duration": "21.0", + "duration": "23.0", "name": "rendering.mobile/css_value_type_shadow" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/css_value_type_transform_complex" }, { - "duration": "22.0", + "duration": "24.0", "name": "rendering.mobile/css_value_type_transform_simple" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/deviantart_mobile_2018" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/digg_mobile_2018" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/docs_paper.html" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/docs_resume.html" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/docs_table.html" }, { - "duration": "20.0", + "duration": "23.0", "name": "rendering.mobile/draw_image" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/draw_image_not_pixel_aligned" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/dynamic_canvas_to_hw_accelerated_canvas.html" }, { - "duration": "24.0", + "duration": "27.0", "name": "rendering.mobile/dynamic_cube_map" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/dynamic_webgl_to_hw_accelerated_canvas.html" }, { - "duration": "22.0", + "duration": "26.0", "name": "rendering.mobile/earth" }, { - "duration": "23.0", + "duration": "27.0", "name": "rendering.mobile/ebay_2018" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/ebay_mobile_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/ebay_mobile_pinch_2018" }, { - "duration": "29.0", + "duration": "31.0", "name": "rendering.mobile/ebay_scroll_2018" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/effect_games" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/espn_2018" }, { @@ -560,147 +560,147 @@ "name": "rendering.mobile/espn_mobile_2018" }, { - "duration": "23.0", + "duration": "26.0", "name": "rendering.mobile/espn_pathological_2018" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/extra_large_texture_uploads" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/facebook_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/facebook_mobile_2018" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/falling_particle_simulation_cpu.html" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/falling_particle_simulation_gpu.html" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/famo_us_twitter_demo" }, { - "duration": "20.0", + "duration": "23.0", "name": "rendering.mobile/fill_clear_rect.html" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/fill_shapes" }, { - "duration": "19.0", + "duration": "22.0", "name": "rendering.mobile/filter_terrain_svg" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/flickr_scroll_2018" }, { - "duration": "13.0", + "duration": "14.0", "name": "rendering.mobile/font_wipe" }, { - "duration": "14.0", + "duration": "17.0", "name": "rendering.mobile/forecast.io_mobile_2018" }, { - "duration": "19.0", + "duration": "23.0", "name": "rendering.mobile/get_image_data_cpu.html" }, { - "duration": "20.0", + "duration": "23.0", "name": "rendering.mobile/get_image_data_gpu.html" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/gmail_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/google_calendar_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/google_docs_2018" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/google_image_search_2018" }, { - "duration": "16.0", + "duration": "20.0", "name": "rendering.mobile/google_image_search_mobile_2018" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/google_news_ios" }, { - "duration": "20.0", + "duration": "23.0", "name": "rendering.mobile/google_news_mobile_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/google_plus_2018" }, { - "duration": "12.0", + "duration": "15.0", "name": "rendering.mobile/google_plus_mobile_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/google_search_mobile_pinch_2018" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/google_web_search_2018" }, { - "duration": "14.0", + "duration": "18.0", "name": "rendering.mobile/google_web_search_mobile_2018" }, { - "duration": "27.0", + "duration": "30.0", "name": "rendering.mobile/gpu_bound_shader.html" }, { - "duration": "26.0", + "duration": "30.0", "name": "rendering.mobile/gsp.ro_mobile_2018" }, { - "duration": "17.0", + "duration": "19.0", "name": "rendering.mobile/guardian_pathological_2018" }, { - "duration": "20.0", + "duration": "24.0", "name": "rendering.mobile/guimark_vector_chart" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/gws_boogie_expansion" }, { - "duration": "6.0", + "duration": "10.0", "name": "rendering.mobile/gws_google_expansion" }, { - "duration": "21.0", + "duration": "25.0", "name": "rendering.mobile/hakim" }, { - "duration": "12.0", + "duration": "13.0", "name": "rendering.mobile/horizontal_vertical_expansion" }, { - "duration": "20.0", + "duration": "23.0", "name": "rendering.mobile/hw_accelerated_canvas_to_sw_canvas.html" }, { @@ -712,67 +712,67 @@ "name": "rendering.mobile/idle_power_blank" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/idle_power_css_animation" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/idle_power_request_animation_frame" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/idle_power_set_timeout_long" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/idle_power_set_timetout" }, { - "duration": "8.0", + "duration": "10.0", "name": "rendering.mobile/ie_chalkboard" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/ie_pirate_mark" }, { - "duration": "22.0", + "duration": "25.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_0" }, { - "duration": "22.0", + "duration": "26.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_75" }, { - "duration": "23.0", + "duration": "27.0", "name": "rendering.mobile/infinite_scroll_element_n_layers_99" }, { - "duration": "21.0", + "duration": "25.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_0" }, { - "duration": "22.0", + "duration": "26.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_75" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/infinite_scroll_root_fixed_n_layers_99" }, { - "duration": "21.0", + "duration": "20.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_0" }, { - "duration": "22.0", + "duration": "20.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_75" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/infinite_scroll_root_n_layers_99" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/infinite_scrolling" }, { @@ -780,59 +780,59 @@ "name": "rendering.mobile/jarro_doverson" }, { - "duration": "13.0", + "duration": "12.0", "name": "rendering.mobile/jpeg_decoding_rgb_and_gpu_rasterization" }, { - "duration": "14.0", + "duration": "12.0", "name": "rendering.mobile/jpeg_decoding_yuv_and_gpu_rasterization" }, { - "duration": "24.0", + "duration": "23.0", "name": "rendering.mobile/js_full_screen_invalidation" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/js_opacity_plus_n_layers_0" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/js_opacity_plus_n_layers_75" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/js_opacity_plus_n_layers_99" }, { - "duration": "23.0", + "duration": "22.0", "name": "rendering.mobile/js_paint_plus_n_layers_0" }, { - "duration": "24.0", + "duration": "22.0", "name": "rendering.mobile/js_paint_plus_n_layers_75" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/js_paint_plus_n_layers_99" }, { - "duration": "24.0", + "duration": "23.0", "name": "rendering.mobile/js_poster_circle" }, { - "duration": "22.0", + "duration": "21.0", "name": "rendering.mobile/js_scroll_text_only" }, { - "duration": "22.0", + "duration": "20.0", "name": "rendering.mobile/kevs_3d" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/keyframed_animations" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/large_texture_uploads" }, { @@ -840,99 +840,99 @@ "name": "rendering.mobile/latimes_pathological_2018" }, { - "duration": "14.0", + "duration": "13.0", "name": "rendering.mobile/linkedin_2018" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/linkedin_mobile_2018" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/linkedin_mobile_pinch_2018" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/linkedin_pathological_2018" }, { - "duration": "10.0", + "duration": "12.0", "name": "rendering.mobile/list_animation_simple" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/list_recycle_transform" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_0fps_impl_60fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_0fps_impl_60fps_no_update" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_0fps_impl_60fps_no_update_jank" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_0fps_with_jank_impl_0fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_15fps_impl_0fps" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_15fps_with_jank_impl_0fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_30fps_impl_0fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_30fps_impl_60fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_60fps_impl_0fps" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_60fps_impl_60fps" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/main_60fps_impl_60fps_no_update" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_60fps_impl_60fps_no_update_jank" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_60fps_with_extreme_jank_impl_0fps" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_60fps_with_jank_and_delay_impl_60fps" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_60fps_with_jank_impl_0fps" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/main_animations_half_presented" }, { - "duration": "23.0", + "duration": "21.0", "name": "rendering.mobile/man_in_blue" }, { - "duration": "25.0", + "duration": "23.0", "name": "rendering.mobile/many_images" }, { @@ -940,251 +940,251 @@ "name": "rendering.mobile/many_planets_deep" }, { - "duration": "25.0", + "duration": "24.0", "name": "rendering.mobile/maps_perf_test" }, { - "duration": "12.0", + "duration": "13.0", "name": "rendering.mobile/mask_transition_animation" }, { - "duration": "17.0", + "duration": "16.0", "name": "rendering.mobile/masonry" }, { - "duration": "20.0", + "duration": "18.0", "name": "rendering.mobile/medium_texture_uploads" }, { - "duration": "19.0", + "duration": "17.0", "name": "rendering.mobile/megi_dish" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/microgame_fps" }, { - "duration": "19.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_asteroid_belt" }, { - "duration": "6.0", + "duration": "5.0", "name": "rendering.mobile/microsoft_fireflies" }, { - "duration": "18.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_fish_ie_tank" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_performance" }, { - "duration": "18.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_snow" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_speed_reading" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_tweet_map" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_video_city" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/microsoft_worker_fountains" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/mix_10k" }, { - "duration": "16.0", + "duration": "18.0", "name": "rendering.mobile/mix_blend_mode_animation_difference" }, { - "duration": "16.0", + "duration": "18.0", "name": "rendering.mobile/mix_blend_mode_animation_hue" }, { - "duration": "19.0", + "duration": "18.0", "name": "rendering.mobile/mix_blend_mode_animation_propagating_isolation" }, { - "duration": "16.0", + "duration": "18.0", "name": "rendering.mobile/mix_blend_mode_animation_screen" }, { - "duration": "46.0", + "duration": "51.0", "name": "rendering.mobile/mlb_mobile_2018" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/mobile_news_sandbox" }, { - "duration": "18.0", + "duration": "19.0", "name": "rendering.mobile/motion_mark_canvas_fill_shapes" }, { - "duration": "17.0", + "duration": "19.0", "name": "rendering.mobile/motion_mark_canvas_stroke_shapes" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_design_15" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_focus_25" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_images_50" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_leaves_250" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_multiply_175" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_anim_suits_125" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_composited_transforms_125" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_blend_circles_25" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_circles_250" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_clipped_rects_100" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_filter_circles_15" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_gradient_circles_250" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_svg_images_50" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_css_bouncing_tagged_images_225" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_dom_particles_svg_masks_25" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_focus_20_15" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_html_leaves_20_50" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_canvas_arcs" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_canvas_lines" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_design" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_images" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_leaves" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_multiply" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_paths" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_ramp_suits" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_svg_bouncing_circles_250" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_svg_bouncing_clipped_rects_100" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_svg_bouncing_gradient_circles_200" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_svg_bouncing_png_images_200" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/motionmark_svg_bouncing_svg_images_50" }, { - "duration": "21.0", + "duration": "23.0", "name": "rendering.mobile/new_tilings" }, { - "duration": "15.0", + "duration": "16.0", "name": "rendering.mobile/no_op_raf" }, { - "duration": "13.0", + "duration": "15.0", "name": "rendering.mobile/no_op_scroll" }, { - "duration": "12.0", + "duration": "14.0", "name": "rendering.mobile/no_op_settimeout" }, { - "duration": "14.0", + "duration": "15.0", "name": "rendering.mobile/no_op_touch_handler" }, { - "duration": "16.0", + "duration": "18.0", "name": "rendering.mobile/no_update_compositor_animation_with_janky_main_animation" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/non_opaque_background_compositor_thread_scrolling_00050_pixels_per_second" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/non_opaque_background_main_thread_scrolling_00050_pixels_per_second" }, { @@ -1192,451 +1192,455 @@ "name": "rendering.mobile/nvidia_vertex_buffer_object" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/nyc_gov_scroll_2018" }, { - "duration": "37.0", + "duration": "33.0", "name": "rendering.mobile/nytimes_mobile_2018" }, { - "duration": "38.0", + "duration": "40.0", "name": "rendering.mobile/nytimes_scroll_2018" }, { - "duration": "16.0", + "duration": "17.0", "name": "rendering.mobile/off_screen_main_60fps" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/off_screen_main_60fps_jank" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/offscreen_animation_no_damage" }, { - "duration": "17.0", + "duration": "18.0", "name": "rendering.mobile/overlay_background_color_css_transitions_page" }, { - "duration": "17.0", + "duration": "18.0", "name": "rendering.mobile/paint_worklet" }, { - "duration": "12.0", + "duration": "13.0", "name": "rendering.mobile/parallax_effect" }, { - "duration": "20.0", + "duration": "21.0", "name": "rendering.mobile/particles" }, { - "duration": "22.0", + "duration": "23.0", "name": "rendering.mobile/pbs_pathological_2018" }, { - "duration": "10.0", + "duration": "11.0", "name": "rendering.mobile/physical_simulation" }, { - "duration": "18.0", + "duration": "19.0", "name": "rendering.mobile/pinterest_2018" }, { - "duration": "12.0", + "duration": "14.0", "name": "rendering.mobile/pinterest_mobile_2018" }, { - "duration": "20.0", + "duration": "21.0", "name": "rendering.mobile/put_and_create_imagebitmap_from_imagedata" }, { - "duration": "18.0", + "duration": "19.0", "name": "rendering.mobile/put_get_image_data" }, { - "duration": "17.0", + "duration": "19.0", "name": "rendering.mobile/put_image_data.html" }, { - "duration": "14.0", + "duration": "15.0", "name": "rendering.mobile/raf" }, { - "duration": "14.0", + "duration": "16.0", "name": "rendering.mobile/raf_animation" }, { - "duration": "14.0", + "duration": "15.0", "name": "rendering.mobile/raf_canvas" }, { - "duration": "14.0", + "duration": "15.0", "name": "rendering.mobile/raf_touch_animation" }, { - "duration": "25.0", + "duration": "26.0", "name": "rendering.mobile/recode_pathological_2018" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/reddit_mobile_2018" }, { - "duration": "18.0", + "duration": "19.0", "name": "rendering.mobile/runway_2019" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/san_angeles" }, { - "duration": "14.0", + "duration": "16.0", "name": "rendering.mobile/second_batch_js_heavy" }, { - "duration": "14.0", + "duration": "16.0", "name": "rendering.mobile/second_batch_js_light" }, { - "duration": "14.0", + "duration": "16.0", "name": "rendering.mobile/second_batch_js_medium" }, { - "duration": "41.0", + "duration": "43.0", "name": "rendering.mobile/sfgate_mobile_2018" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/sheets_render.html" }, { - "duration": "25.0", + "duration": "27.0", "name": "rendering.mobile/silk_finance" }, { - "duration": "19.0", + "duration": "22.0", "name": "rendering.mobile/simple_text_page" }, { - "duration": "15.0", + "duration": "17.0", "name": "rendering.mobile/simple_touch_drag" }, { - "duration": "62.0", + "duration": "64.0", "name": "rendering.mobile/skelebuddies_wasm_2020" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/slashdot_mobile_2018" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/small_texture_uploads" }, { - "duration": "26.0", + "duration": "29.0", "name": "rendering.mobile/smash_cat" }, { - "duration": "23.0", + "duration": "26.0", "name": "rendering.mobile/spielzeugz" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/static_canvas_to_hw_accelerated_canvas.html" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/static_webgl_to_hw_accelerated_canvas.html" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/sticky_using_webkit" }, { - "duration": "23.0", + "duration": "26.0", "name": "rendering.mobile/stroke_shapes" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/svg_icon_raster" }, { - "duration": "11.0", + "duration": "12.0", "name": "rendering.mobile/swipe_to_dismiss" }, { - "duration": "19.0", + "duration": "21.0", "name": "rendering.mobile/sync_scroll_offset" }, { - "duration": "41.0", + "duration": "45.0", "name": "rendering.mobile/techcrunch_2018" }, { - "duration": "37.0", + "duration": "41.0", "name": "rendering.mobile/techcrunch_mobile_2018" }, { - "duration": "36.0", + "duration": "38.0", "name": "rendering.mobile/text_05000_pixels_per_second" }, { - "duration": "35.0", + "duration": "37.0", "name": "rendering.mobile/text_10000_pixels_per_second" }, { - "duration": "32.0", + "duration": "34.0", "name": "rendering.mobile/text_20000_pixels_per_second" }, { - "duration": "30.0", + "duration": "33.0", "name": "rendering.mobile/text_40000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_60000_pixels_per_second" }, { - "duration": "30.0", + "duration": "33.0", "name": "rendering.mobile/text_75000_pixels_per_second" }, { - "duration": "30.0", + "duration": "33.0", "name": "rendering.mobile/text_90000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_05000_pixels_per_second" }, { - "duration": "34.0", + "duration": "37.0", "name": "rendering.mobile/text_constant_full_page_raster_10000_pixels_per_second" }, { - "duration": "32.0", + "duration": "35.0", "name": "rendering.mobile/text_constant_full_page_raster_20000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_40000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_60000_pixels_per_second" }, { - "duration": "30.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_75000_pixels_per_second" }, { - "duration": "30.0", + "duration": "33.0", "name": "rendering.mobile/text_constant_full_page_raster_90000_pixels_per_second" }, { - "duration": "26.0", + "duration": "31.0", + "name": "rendering.mobile/text_fling_05000_pixels_per_second" + }, + { + "duration": "30.0", "name": "rendering.mobile/text_fling_10000_pixels_per_second" }, { - "duration": "27.0", + "duration": "31.0", "name": "rendering.mobile/text_fling_20000_pixels_per_second" }, { - "duration": "36.0", + "duration": "38.0", "name": "rendering.mobile/text_hover_05000_pixels_per_second" }, { - "duration": "35.0", + "duration": "37.0", "name": "rendering.mobile/text_hover_10000_pixels_per_second" }, { - "duration": "32.0", + "duration": "34.0", "name": "rendering.mobile/text_hover_20000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_hover_40000_pixels_per_second" }, { - "duration": "31.0", + "duration": "33.0", "name": "rendering.mobile/text_hover_60000_pixels_per_second" }, { - "duration": "30.0", + "duration": "32.0", "name": "rendering.mobile/text_hover_75000_pixels_per_second" }, { - "duration": "30.0", + "duration": "32.0", "name": "rendering.mobile/text_hover_90000_pixels_per_second" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/text_scrollbar_100_pixels_per_second" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/text_scrollbar_1200_pixels_per_second" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/text_scrollbar_200_pixels_per_second" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/text_scrollbar_2300_pixels_per_second" }, { - "duration": "3.0", + "duration": "5.0", "name": "rendering.mobile/text_scrollbar_700_pixels_per_second" }, { - "duration": "33.0", + "duration": "35.0", "name": "rendering.mobile/theverge_article_mobile_2018" }, { - "duration": "34.0", + "duration": "36.0", "name": "rendering.mobile/theverge_mobile_2018" }, { - "duration": "27.0", + "duration": "29.0", "name": "rendering.mobile/throughput_scrolling_active_handler" }, { - "duration": "27.0", + "duration": "29.0", "name": "rendering.mobile/throughput_scrolling_composited" }, { - "duration": "27.0", + "duration": "29.0", "name": "rendering.mobile/throughput_scrolling_passive_handler" }, { - "duration": "28.0", + "duration": "30.0", "name": "rendering.mobile/throughput_scrolling_uncomposited" }, { - "duration": "59.0", + "duration": "61.0", "name": "rendering.mobile/tiny_racing_v3_wasm_2020" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/toBlob_duration.html" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/toBlob_duration_jpeg.html" }, { - "duration": "25.0", + "duration": "27.0", "name": "rendering.mobile/toBlob_small_canvas_in_worker.html" }, { - "duration": "19.0", + "duration": "22.0", "name": "rendering.mobile/touch_handler_scrolling" }, { - "duration": "22.0", + "duration": "25.0", "name": "rendering.mobile/transfer_from_imageBitmap.html" }, { - "duration": "22.0", + "duration": "25.0", "name": "rendering.mobile/transform_transitions" }, { - "duration": "22.0", + "duration": "25.0", "name": "rendering.mobile/transform_transitions_js_block" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/twitch_2018" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/twitch_mobile_pinch_2018" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/twitter_2018" }, { - "duration": "21.0", + "duration": "24.0", "name": "rendering.mobile/twitter_mobile_2018" }, { - "duration": "20.0", + "duration": "22.0", "name": "rendering.mobile/update_history_state" }, { - "duration": "33.0", + "duration": "36.0", "name": "rendering.mobile/usatoday_mobile_2018" }, { - "duration": "12.0", + "duration": "14.0", "name": "rendering.mobile/vertical_expansion" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/video_to_hw_accelerated_canvas" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/video_to_sub_texture" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/video_to_sub_texture_flip_and_premultiply" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/video_to_sub_texture_flip_y" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/video_to_sub_texture_premultiply" }, { - "duration": "9.0", + "duration": "12.0", "name": "rendering.mobile/video_to_texture" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/web_animation_value_type_color" }, { - "duration": "24.0", + "duration": "27.0", "name": "rendering.mobile/web_animation_value_type_length_3d" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/web_animation_value_type_length_complex" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/web_animation_value_type_length_simple" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/web_animation_value_type_path" }, { - "duration": "23.0", + "duration": "25.0", "name": "rendering.mobile/web_animation_value_type_shadow" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/web_animation_value_type_transform_complex" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/web_animation_value_type_transform_simple" }, { - "duration": "9.0", + "duration": "10.0", "name": "rendering.mobile/web_animations_many_keyframes" }, { - "duration": "24.0", + "duration": "27.0", "name": "rendering.mobile/web_animations_set_current_time" }, { @@ -1644,11 +1648,11 @@ "name": "rendering.mobile/web_animations_simultaneous" }, { - "duration": "25.0", + "duration": "26.0", "name": "rendering.mobile/web_animations_staggered_chaining" }, { - "duration": "24.0", + "duration": "26.0", "name": "rendering.mobile/web_animations_staggered_infinite_iterations" }, { @@ -1656,7 +1660,7 @@ "name": "rendering.mobile/web_animations_staggered_triggering_page" }, { - "duration": "23.0", + "duration": "24.0", "name": "rendering.mobile/webgl_to_texture" }, { @@ -1668,27 +1672,27 @@ "name": "rendering.mobile/webp_decoding_yuv_and_gpu_rasterization" }, { - "duration": "29.0", + "duration": "33.0", "name": "rendering.mobile/wikipedia_2018" }, { - "duration": "28.0", + "duration": "33.0", "name": "rendering.mobile/wikipedia_delayed_scroll_start_2018" }, { - "duration": "25.0", + "duration": "27.0", "name": "rendering.mobile/wikipedia_mobile_2018" }, { - "duration": "9.0", + "duration": "10.0", "name": "rendering.mobile/wordpress_2018" }, { - "duration": "27.0", + "duration": "28.0", "name": "rendering.mobile/wordpress_mobile_2018" }, { - "duration": "32.0", + "duration": "33.0", "name": "rendering.mobile/worldjournal_mobile_2018" }, { @@ -1696,51 +1700,51 @@ "name": "rendering.mobile/wow_wiki_pathological_2018" }, { - "duration": "58.0", + "duration": "59.0", "name": "rendering.mobile/wowwiki_mobile_2018" }, { - "duration": "58.0", + "duration": "59.0", "name": "rendering.mobile/wsj_mobile_2018" }, { - "duration": "38.0", + "duration": "32.0", "name": "rendering.mobile/yahoo_answers_2018" }, { - "duration": "11.0", + "duration": "10.0", "name": "rendering.mobile/yahoo_answers_mobile_2018" }, { - "duration": "28.0", + "duration": "26.0", "name": "rendering.mobile/yahoo_news_2018" }, { - "duration": "32.0", + "duration": "26.0", "name": "rendering.mobile/yahoo_news_mobile_2018" }, { - "duration": "34.0", + "duration": "32.0", "name": "rendering.mobile/yahoo_sports_2018" }, { - "duration": "34.0", + "duration": "31.0", "name": "rendering.mobile/yahoo_sports_pathological_2018" }, { - "duration": "11.0", + "duration": "10.0", "name": "rendering.mobile/youtube_2018" }, { - "duration": "11.0", + "duration": "10.0", "name": "rendering.mobile/youtube_mobile_2018" }, { - "duration": "34.0", + "duration": "32.0", "name": "rendering.mobile/zdnet_pathological_2018" }, { - "duration": "11.0", + "duration": "12.0", "name": "rendering.mobile/zoom_in_animation" }, { @@ -1753,46 +1757,18 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:media:pinterest:2018" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:media:tumblr:2018" - }, - { - "duration": "76.0", - "name": "system_health.memory_desktop/browse:media:youtube:2019" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:media:youtubetv:2019" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:media:youtubetv_watch:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:news:cnn:2021" }, { - "duration": "58.0", + "duration": "59.0", "name": "system_health.memory_desktop/browse:news:flipboard:2020" }, { - "duration": "63.0", + "duration": "64.0", "name": "system_health.memory_desktop/browse:news:hackernews:2020" }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:news:nytimes:2020" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:news:reddit:2020" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:search:google:2020" }, { @@ -1804,14 +1780,6 @@ "name": "system_health.memory_desktop/browse:social:facebook_infinite_scroll:2018" }, { - "duration": "60.0", - "name": "system_health.memory_desktop/browse:social:tumblr_infinite_scroll:2018" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:social:twitter:2018" - }, - { "duration": "2.0", "name": "system_health.memory_desktop/browse:tech:discourse_infinite_scroll:2018" }, @@ -1845,18 +1813,10 @@ }, { "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:photoshop:2021" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/browse:tools:photoshop_warm:2021" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/browse:tools:sheets:2019" }, { - "duration": "34.0", + "duration": "33.0", "name": "system_health.memory_desktop/browse_accessibility:media:youtube" }, { @@ -1876,18 +1836,6 @@ "name": "system_health.memory_desktop/load:games:bubbles:2020" }, { - "duration": "14.0", - "name": "system_health.memory_desktop/load:games:lazors" - }, - { - "duration": "21.0", - "name": "system_health.memory_desktop/load:games:miniclip:2018" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/load:games:spychase:2018" - }, - { "duration": "22.0", "name": "system_health.memory_desktop/load:media:9gag" }, @@ -1896,42 +1844,6 @@ "name": "system_health.memory_desktop/load:media:dailymotion:2019" }, { - "duration": "2.0", - "name": "system_health.memory_desktop/load:media:facebook_feed:desktop:2020" - }, - { - "duration": "15.0", - "name": "system_health.memory_desktop/load:media:facebook_photos:2018" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/load:media:facebook_photos:desktop:2020" - }, - { - "duration": "21.0", - "name": "system_health.memory_desktop/load:media:flickr:2018" - }, - { - "duration": "17.0", - "name": "system_health.memory_desktop/load:media:google_images:2018" - }, - { - "duration": "34.0", - "name": "system_health.memory_desktop/load:media:imgur:2018" - }, - { - "duration": "24.0", - "name": "system_health.memory_desktop/load:media:soundcloud:2018" - }, - { - "duration": "26.0", - "name": "system_health.memory_desktop/load:media:youtube:2018" - }, - { - "duration": "16.0", - "name": "system_health.memory_desktop/load:media:youtubelivingroom:2020" - }, - { "duration": "18.0", "name": "system_health.memory_desktop/load:news:bbc:2018" }, @@ -1940,75 +1852,19 @@ "name": "system_health.memory_desktop/load:news:cnn:2020" }, { - "duration": "19.0", - "name": "system_health.memory_desktop/load:news:flipboard" - }, - { - "duration": "13.0", - "name": "system_health.memory_desktop/load:news:hackernews:2018" - }, - { - "duration": "30.0", - "name": "system_health.memory_desktop/load:news:nytimes:2018" - }, - { - "duration": "26.0", - "name": "system_health.memory_desktop/load:news:qq:2018" - }, - { - "duration": "16.0", - "name": "system_health.memory_desktop/load:news:wikipedia:2018" - }, - { - "duration": "20.0", + "duration": "21.0", "name": "system_health.memory_desktop/load:search:amazon:2018" }, { - "duration": "28.0", + "duration": "23.0", "name": "system_health.memory_desktop/load:search:baidu:2018" }, { - "duration": "28.0", - "name": "system_health.memory_desktop/load:search:ebay:2018" - }, - { - "duration": "29.0", - "name": "system_health.memory_desktop/load:search:flipkart:2018" - }, - { - "duration": "16.0", - "name": "system_health.memory_desktop/load:search:google:2018" - }, - { - "duration": "22.0", - "name": "system_health.memory_desktop/load:search:taobao:2018" - }, - { - "duration": "14.0", - "name": "system_health.memory_desktop/load:search:yahoo:2018" - }, - { - "duration": "16.0", - "name": "system_health.memory_desktop/load:search:yandex:2018" - }, - { - "duration": "15.0", - "name": "system_health.memory_desktop/load:social:instagram:2018" - }, - { - "duration": "13.0", - "name": "system_health.memory_desktop/load:social:pinterest:2019" - }, - { - "duration": "20.0", - "name": "system_health.memory_desktop/load:social:vk:2018" - }, - { "duration": "2.0", "name": "system_health.memory_desktop/load:tools:chat:2020" }, { - "duration": "38.0", + "duration": "37.0", "name": "system_health.memory_desktop/load:tools:docs:2019" }, { @@ -2016,50 +1872,18 @@ "name": "system_health.memory_desktop/load:tools:drive:2019" }, { - "duration": "2.0", - "name": "system_health.memory_desktop/load:tools:gmail:2019" - }, - { - "duration": "20.0", - "name": "system_health.memory_desktop/load:tools:stackoverflow:2018" - }, - { - "duration": "23.0", - "name": "system_health.memory_desktop/load:tools:weather:2019" - }, - { "duration": "17.0", "name": "system_health.memory_desktop/load_accessibility:media:wikipedia:2018" }, { - "duration": "31.0", + "duration": "32.0", "name": "system_health.memory_desktop/load_accessibility:shopping:amazon:2018" }, { "duration": "2.0", - "name": "system_health.memory_desktop/long_running:tools:gmail-background" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/long_running:tools:gmail-foreground" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/multitab:misc:typical24" - }, - { - "duration": "2.0", - "name": "system_health.memory_desktop/multitab:misc:typical24:2018" - }, - { - "duration": "2.0", "name": "system_health.memory_desktop/play:media:google_play_music" }, { - "duration": "46.0", - "name": "system_health.memory_desktop/play:media:soundcloud:2018" - }, - { "duration": "900.0", "name": "base_perftests/_gtest_" }
diff --git a/tools/perf/experimental/representative_perf_test_limit_adjuster/OWNERS b/tools/perf/experimental/representative_perf_test_limit_adjuster/OWNERS deleted file mode 100644 index 2b84d944..0000000 --- a/tools/perf/experimental/representative_perf_test_limit_adjuster/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -behdadb@chromium.org -sadrul@chromium.org
diff --git a/tools/perf/experimental/representative_perf_test_limit_adjuster/__init__.py b/tools/perf/experimental/representative_perf_test_limit_adjuster/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/tools/perf/experimental/representative_perf_test_limit_adjuster/__init__.py +++ /dev/null
diff --git a/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits.py b/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits.py deleted file mode 100644 index 989bfa8c..0000000 --- a/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits.py +++ /dev/null
@@ -1,243 +0,0 @@ -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -from __future__ import print_function - -import json -import os -import sys -import shutil -import subprocess -import tempfile - -CHROMIUM_PATH = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..') -TOOLS_PERF_PATH = os.path.join(CHROMIUM_PATH, 'tools', 'perf') -sys.path.insert(1, TOOLS_PERF_PATH) - -from core.external_modules import pandas - -RUNS_USED_FOR_LIMIT_UPDATE = 50 -CHANGE_PERCENTAGE_LIMIT = 0.01 - -SWARMING_PATH = os.path.join(CHROMIUM_PATH, 'tools', 'luci-go', 'swarming') -UPPER_LIMITS_DATA_DIR = os.path.join( - CHROMIUM_PATH, 'testing', 'scripts', 'representative_perf_test_data') - - -def FetchItemIds(tags, limit): - """Fetches the item id of tasks described by the tags. - - Args: - tags: The tags which describe the task such as OS, builder_group and buildername. - limit: The number of runs to look at. - - Returns: - A list containing the item Id of the tasks. - """ - - query = [ - SWARMING_PATH, 'tasks', '-S', 'chromium-swarm.appspot.com', '-limit', - str(limit), '-state=COMPLETED', '-field', 'items(task_id)', '-tag', - 'builder_group:{builder_group}'.format(**tags), '-tag', - 'os:{os}'.format(**tags), '-tag', - 'name:rendering_representative_perf_tests', '-tag', - 'buildername:{buildername}'.format(**tags) - ] - return json.loads(subprocess.check_output(query)) - - -def FetchItemData(task_id, benchmark, index, temp_dir): - """Fetches the performance values (AVG & CI ranges) of tasks. - - Args: - task_id: The list of item Ids to fetch dat for. - benchmark: The benchmark these task are on (desktop/mobile). - index: The index field of the data_frame - temp_dir: The temp directory to store task data in. - - Returns: - A data_frame containing the averages and confidence interval ranges. - """ - query = [ - SWARMING_PATH, 'collect', '-S', 'chromium-swarm.appspot.com', - '-output-dir', temp_dir, '-perf', task_id - ] - try: - subprocess.check_output(query) - except Exception as e: - print(e) - - result_file_path = os.path.join(temp_dir, task_id, 'rendering.' + benchmark, - 'perf_results.csv') - - try: - df = pandas.read_csv(result_file_path) - df_frame_times = df.loc[df['name'] == 'frame_times'] - df_frame_times = df_frame_times[['stories', 'avg', 'ci_095']] - - df_cpu_wall = df.loc[df['name'] == 'cpu_wall_time_ratio'] - df_cpu_wall = df_cpu_wall[['stories', 'avg']] - df_cpu_wall = df_cpu_wall.rename(columns={'avg': 'cpu_wall_time_ratio'}) - - df = pandas.merge(df_frame_times, df_cpu_wall, on='stories') - df['index'] = index - return df - except: - print("CSV results were not produced!") - - -def CreateDataframe(benchmark, tags, limit): - """Creates the dataframe of values recorded in recent runs. - - Given the tags, benchmark this function fetches the data of last {limit} - runs, and returns a dataframe of values for focused metrics such as - frame_times and CPU_wall_time_ratio. - - Args: - benchmark: The benchmark these task are on (desktop/mobile). - tags: The tags which describe the tasks such as OS and buildername. - limit: The number of runs to look at. - - Returns: - A dataframe with averages and confidence interval of frame_times, and - average value of CPU_wall_time_ratio of each story of each run. - """ - items = [] - for tag_set in tags: - items.extend(FetchItemIds(tag_set, limit)) - - dfs = [] - try: - temp_dir = tempfile.mkdtemp('perf_csvs') - for idx, item in enumerate(items): - dfs.append(FetchItemData(item['task_id'], benchmark, idx, temp_dir)) - idx += 1 - finally: - shutil.rmtree(temp_dir) - return pandas.concat(dfs, ignore_index=True) - - -def GetPercentileValues(data_frame, percentile): - """Get the percentile value of each metric for recorded values in dataframe. - - Args: - data_frame: The dataframe with averages and confidence intervals of each - story of each run. - percentile: the percentile to use for determining the upper limits. - - Returns: - A dictionary with averages and confidence interval ranges calculated - from the percentile of recent runs. - """ - - if not data_frame.empty: - avg_df = data_frame.pivot(index='stories', columns='index', values='avg') - upper_limit = avg_df.quantile(percentile, axis = 1) - ci_df = data_frame.pivot(index='stories', columns='index', values='ci_095') - upper_limit_ci = ci_df.quantile(percentile, axis = 1) - cpu_wall_df = data_frame.pivot(index='stories', - columns='index', - values='cpu_wall_time_ratio') - upper_limit_cpu_wall = cpu_wall_df.quantile(1 - percentile, axis=1) - - results = {} - for index in avg_df.index: - results[index] = { - 'avg': round(upper_limit[index], 3), - 'ci_095': round(upper_limit_ci[index], 3), - 'cpu_wall_time_ratio': round(upper_limit_cpu_wall[index], 3) - } - return results - - -def MeasureNewUpperLimit(old_value, new_value, att_name, max_change): - change_pct = 0.0 - if old_value > 0: - change_pct = (new_value - old_value) / old_value - - print( - ' {}:\t\t {} -> {} \t({:.2f}%)'.format( - att_name, old_value, new_value, change_pct * 100)) - if new_value < 0.01: - print('WARNING: New selected value is close to 0.') - return ( - round(new_value, 3), - max(max_change, abs(change_pct)) - ) - - -def RecalculateUpperLimits(data_point_count): - """Recalculates the upper limits using the data of recent runs. - - This method replaces the existing JSON file which contains the upper limits - used by representative perf tests if the changes of upper limits are - significant. - - Args: - data_point_count: The number of runs to use for recalculation. - """ - with open(os.path.join(UPPER_LIMITS_DATA_DIR, - 'platform_specific_tags.json')) as tags_data: - platform_specific_tags = json.load(tags_data) - - with open( - os.path.join( - UPPER_LIMITS_DATA_DIR, - 'representatives_frame_times_upper_limit.json')) as current_data: - current_upper_limits = json.load(current_data) - - max_change = 0.0 - results = {} - for platform in platform_specific_tags: - platform_data = platform_specific_tags[platform] - print('\n- Processing data ({})'.format(platform)) - - dataframe = CreateDataframe(platform_data['benchmark'], - platform_data['tags'], data_point_count) - results[platform] = GetPercentileValues(dataframe, 0.95) - - # Loop over results and adjust base on current values. - for story in results[platform]: - if story in current_upper_limits[platform]: - print(story, ':') - new_avg, max_change = MeasureNewUpperLimit( - current_upper_limits[platform][story]['avg'], - results[platform][story]['avg'], 'AVG', max_change) - results[platform][story]['avg'] = new_avg - - new_ci, max_change = MeasureNewUpperLimit( - current_upper_limits[platform][story]['ci_095'], - results[platform][story]['ci_095'], 'CI', max_change) - results[platform][story]['ci_095'] = new_ci - - new_cpu_ratio, max_change = MeasureNewUpperLimit( - current_upper_limits[platform][story]['cpu_wall_time_ratio'], - results[platform][story]['cpu_wall_time_ratio'], - 'CPU_wall_time_ratio', max_change) - results[platform][story]['cpu_wall_time_ratio'] = new_cpu_ratio - - if current_upper_limits[platform][story].get('control', False): - results[platform][story]['control'] = True - if current_upper_limits[platform][story].get('experimental', False): - results[platform][story]['experimental'] = True - comment = current_upper_limits[platform][story].get('_comment', False) - if not comment == False: - results[platform][story]['_comment'] = comment - - if max_change > CHANGE_PERCENTAGE_LIMIT: - with open( - os.path.join( - UPPER_LIMITS_DATA_DIR, - 'representatives_frame_times_upper_limit.json' - ), 'w') as outfile: - json.dump(results, outfile, separators=(',', ': '), indent=2) - print( - 'Upper limits were updated on ' - 'representatives_frame_times_upper_limit.json') - else: - print('Changes are small, no need for new limits') - - -if __name__ == '__main__': - sys.exit(RecalculateUpperLimits(RUNS_USED_FOR_LIMIT_UPDATE))
diff --git a/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits_unittest.py b/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits_unittest.py deleted file mode 100644 index 65579b9..0000000 --- a/tools/perf/experimental/representative_perf_test_limit_adjuster/adjust_upper_limits_unittest.py +++ /dev/null
@@ -1,47 +0,0 @@ -# Copyright 2020 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import pandas as pd -import os -import sys -import unittest - -from experimental.representative_perf_test_limit_adjuster import ( - adjust_upper_limits) - - -def create_sample_dataframe(story_name, count, avg_start, avg_step, ci_start, - ci_step, cpu_wal_start, cpu_wall_step): - cols = ['stories', 'avg', 'ci_095', 'cpu_wall_time_ratio', 'index'] - df = pd.DataFrame(columns=cols) - for idx in range(count): - avg = avg_start + idx * avg_step - ci = ci_start + idx * ci_step - cpu_wall = cpu_wal_start + idx * cpu_wall_step - df = df.append( - { - 'stories': story_name, - 'avg': avg, - 'ci_095': ci, - 'cpu_wall_time_ratio': cpu_wall, - 'index': idx - }, - ignore_index=True) - return df - - -class TestAdjustUpperLimits(unittest.TestCase): - def test_get_percentile_values(self): - dataframe = create_sample_dataframe('story_name', 21, 16.0, 0.5, 0.2, 0.01, - 0.2, 0.01) - limits = adjust_upper_limits.GetPercentileValues(dataframe, 0.95) - - # Given values for avg: [16, 16.5, 17, ..., 25.5, 26] - self.assertEquals(limits['story_name']['avg'], 25.5) - - # Given values for ci_095: [0.2, 0.21, 0.22, ..., 0.39, 0.4] - self.assertEquals(limits['story_name']['ci_095'], 0.39) - - # Given values for cpu_wall_time_ratio: [0.2, 0.21, 0.22, ..., 0.39, 0.4] - self.assertEquals(limits['story_name']['cpu_wall_time_ratio'], 0.21)
diff --git a/tools/perf/run_rendering_benchmark_with_gated_performance_unittest.py b/tools/perf/run_rendering_benchmark_with_gated_performance_unittest.py deleted file mode 100644 index 15ff117..0000000 --- a/tools/perf/run_rendering_benchmark_with_gated_performance_unittest.py +++ /dev/null
@@ -1,355 +0,0 @@ -# Copyright 2020 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import os -import sys -import unittest - -# Add src/testing/ into sys.path for importing representative perf test script. -PERF_TEST_SCRIPTS_DIR = os.path.join( - os.path.dirname(__file__), '..', '..', 'testing', 'scripts') -sys.path.append(PERF_TEST_SCRIPTS_DIR) -import run_rendering_benchmark_with_gated_performance as perf_tests # pylint: disable=wrong-import-position,import-error - - -BENCHMARK = 'rendering.desktop' - -UPPER_LIMIT_DATA_SAMPLE = { - 'story_1': { - 'ci_095': 10, - 'avg': 20, - 'cpu_wall_time_ratio': 0.4, - }, - 'story_2': { - 'ci_095': 10, - 'avg': 16, - 'cpu_wall_time_ratio': 0.3, - }, - 'story_3': { - 'ci_095': 10, - 'avg': 10, - 'cpu_wall_time_ratio': 0.5, - }, - 'story_4': { - 'ci_095': 10, - 'avg': 10, - 'cpu_wall_time_ratio': 0.5, - 'control': True, - }, - 'story_5': { - 'ci_095': 20, - 'avg': 10, - 'cpu_wall_time_ratio': 0.5, - }, - 'story_6': { - 'ci_095': 20, - 'avg': 10, - 'cpu_wall_time_ratio': 0.5, - }, - 'story_7': { - 'ci_095': 20, - 'avg': 10, - 'cpu_wall_time_ratio': 0.5, - 'experimental': True, - }, -} - - -def create_sample_input(record_list): - # Coverts an array of arrays in to an array of dicts with keys of - # stories, name, avg, count, ci_095 for the unittests. - keys = ['stories', 'name', 'avg', 'count', 'ci_095'] - result = [] - for row in record_list: - result.append(dict(zip(keys, row))) - return result - - -def create_sample_perf_results(passed_stories, failed_stories, benchmark): - perf_results = { - 'tests': {}, - 'num_failures_by_type': { - 'FAIL': len(failed_stories), - 'PASS': len(passed_stories) - } - } - perf_results['tests'][benchmark] = {} - for story in passed_stories: - perf_results['tests'][benchmark][story] = { - 'actual': 'PASS', - 'is_unexpected': False, - 'expected': 'PASS' - } - for story in failed_stories: - perf_results['tests'][benchmark][story] = { - 'actual': 'FAIL', - 'is_unexpected': True, - 'expected': 'PASS' - } - - return perf_results - - -def perf_test_initializer(): - perf_test = perf_tests.RenderingRepresentativePerfTest(True) - perf_test.benchmark = BENCHMARK - perf_test.upper_limit_data = UPPER_LIMIT_DATA_SAMPLE - perf_test.set_platform_specific_attributes() - return perf_test - - -class TestRepresentativePerfScript(unittest.TestCase): - def test_parse_csv_results(self): - csv_obj = create_sample_input([ - ['story_1', 'frame_times', 16, 10, 1.5], - ['story_1', 'cpu_wall_time_ratio', 0.5, 1, 1], - ['story_2', 'latency', 10, 8, 4], # Record for a different metric. - ['story_3', 'frame_times', 8, 20, 2], - ['story_3', 'frame_times', 7, 20, 15], - ['story_3', 'frame_times', 12, 20, 16], - ['story_3', 'cpu_wall_time_ratio', 0.3, 1, 1], - ['story_3', 'cpu_wall_time_ratio', 0.7, 1, 1], - ['story_3', 'cpu_wall_time_ratio', '', 0, 1], - ['story_4', 'frame_times', '', 10, 1], # Record with no avg. - ['story_5', 'frame_times', 12, 0, 3], # Record with count of 0. - ['story_6', 'frame_times', 12, 40, 40], # High noise record. - ['story_8', 'frame_times', 12, 40, 4], - ]) - - perf_test = perf_test_initializer() - - values_per_story = perf_test.parse_csv_results(csv_obj) - # Existing Frame_times stories in upper_limits should be listed. - # All stories but story_2 & story_8. - self.assertEquals(len(values_per_story), 5) - self.assertEquals(values_per_story['story_1']['averages'], [16.0]) - self.assertEquals(values_per_story['story_1']['ci_095'], [1.5]) - self.assertEquals(values_per_story['story_1']['cpu_wall_time_ratio'], [0.5]) - - # Record with avg 12 has high noise. - self.assertEquals(values_per_story['story_3']['averages'], [8.0, 7.0, 12.0]) - self.assertEquals(values_per_story['story_3']['ci_095'], [2.0, 15.0, 16.0]) - self.assertEquals(values_per_story['story_3']['cpu_wall_time_ratio'], - [0.3, 0.7]) - - self.assertEquals(len(values_per_story['story_4']['averages']), 0) - self.assertEquals(len(values_per_story['story_4']['ci_095']), 0) - self.assertEquals(len(values_per_story['story_5']['averages']), 0) - self.assertEquals(len(values_per_story['story_5']['ci_095']), 0) - self.assertEquals(values_per_story['story_6']['averages'], [12.0]) - self.assertEquals(values_per_story['story_6']['ci_095'], [40.0]) - - def test_compare_values_1(self): - values_per_story = { - 'story_1': { - 'averages': [16.0, 17.0, 21.0], - 'ci_095': [2.0, 15.0, 16.0], - 'cpu_wall_time_ratio': [0.5, 0.52, 0.57] - }, - 'story_2': { - 'averages': [16.0, 17.0, 22.0], - 'ci_095': [1.0, 1.4, 1.2], - 'cpu_wall_time_ratio': [0.3, 0.3, 0.3] - }, - 'story_3': { - 'averages': [20.0, 15.0, 22.0], - 'ci_095': [1.0, 0.8, 1.2], - 'cpu_wall_time_ratio': [0.5, 0.5, 0.49] - } - } - - sample_perf_results = create_sample_perf_results( - ['story_1', 'story_2', 'story_3'], [], BENCHMARK) - rerun = False - perf_test = perf_test_initializer() - perf_test.result_recorder[rerun].set_tests(sample_perf_results) - - perf_test.compare_values(values_per_story, rerun) - result_recorder = perf_test.result_recorder[rerun] - self.assertEquals(result_recorder.tests, 3) - # The failure for story_3 is invalidated (low cpu_wall_time_ratio) - self.assertEquals(result_recorder.failed_stories, set(['story_2'])) - (output, overall_return_code) = result_recorder.get_output(0) - self.assertEquals(overall_return_code, 1) - self.assertEquals(output['num_failures_by_type'].get('FAIL', 0), 1) - self.assertEquals(output['tests'][BENCHMARK]['story_1']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_2']['actual'], 'FAIL') - self.assertEquals(output['tests'][BENCHMARK]['story_3']['actual'], 'PASS') - - def test_compare_values_2(self): - values_per_story = { - 'story_1': { - 'averages': [16.0, 17.0, 21.0], - 'ci_095': [2.0, 15.0, 16.0], - 'cpu_wall_time_ratio': [0.45, 0.42], - }, - 'story_3': { # Two of the runs have acceptable CI but high averages. - 'averages': [10, 13], - 'ci_095': [14, 16, 12], - 'cpu_wall_time_ratio': [0.5, 0.52], - }, - 'story_4': { # All runs have high noise. - 'averages': [], - 'ci_095': [16, 17, 18], - 'cpu_wall_time_ratio': [], - }, - 'story_5': { # No recorded values. - 'averages': [], - 'ci_095': [], - 'cpu_wall_time_ratio': [], - } - } - - sample_perf_results = create_sample_perf_results( - ['story_1', 'story_3', 'story_4', 'story_5'], ['story_2'], BENCHMARK) - rerun = True - perf_test = perf_test_initializer() - perf_test.result_recorder[rerun].set_tests(sample_perf_results) - - self.assertEquals(perf_test.result_recorder[rerun].fails, 1) - - perf_test.compare_values(values_per_story, rerun) - result_recorder = perf_test.result_recorder[rerun] - self.assertEquals(result_recorder.tests, 5) - self.assertEquals(result_recorder.failed_stories, - set(['story_3', 'story_4', 'story_5'])) - self.assertTrue(result_recorder.is_control_stories_noisy) - - result_recorder.invalidate_failures(BENCHMARK) - (output, overall_return_code) = result_recorder.get_output(0) - - self.assertEquals(overall_return_code, 1) - self.assertEquals(output['num_failures_by_type'].get('FAIL', 0), 1) - self.assertEquals(output['tests'][BENCHMARK]['story_1']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_2']['actual'], 'FAIL') - self.assertEquals(output['tests'][BENCHMARK]['story_3']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_4']['actual'], 'PASS') - - # Invalidating failure as a result of noisy control test - def test_compare_values_3(self): - values_per_story = { - 'story_1': { - 'averages': [16.0, 17.0, 21.0], - 'ci_095': [2.0, 15.0, 16.0], - 'cpu_wall_time_ratio': [0.45, 0.42], - }, - 'story_3': { # Two of the runs have acceptable CI but high averages. - 'averages': [10, 13], - 'ci_095': [14, 16, 12], - 'cpu_wall_time_ratio': [0.5, 0.52], - }, - 'story_4': { # All runs have high noise. - 'averages': [], - 'ci_095': [16, 17, 18], - 'cpu_wall_time_ratio': [], - }, - 'story_5': { # No recorded values. - 'averages': [], - 'ci_095': [], - 'cpu_wall_time_ratio': [], - } - } - - sample_perf_results = create_sample_perf_results( - ['story_1', 'story_3', 'story_4', 'story_5'], [], BENCHMARK) - rerun = True - perf_test = perf_test_initializer() - perf_test.result_recorder[rerun].set_tests(sample_perf_results) - - self.assertEquals(perf_test.result_recorder[rerun].fails, 0) - - perf_test.compare_values(values_per_story, rerun) - result_recorder = perf_test.result_recorder[rerun] - self.assertEquals(result_recorder.tests, 4) - self.assertEquals(result_recorder.failed_stories, - set(['story_3', 'story_4', 'story_5'])) - self.assertTrue(result_recorder.is_control_stories_noisy) - - result_recorder.invalidate_failures(BENCHMARK) - (output, overall_return_code) = result_recorder.get_output(0) - - self.assertEquals(overall_return_code, 0) - self.assertEquals(output['num_failures_by_type'].get('FAIL', 0), 0) - self.assertEquals(output['tests'][BENCHMARK]['story_1']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_3']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_4']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_5']['actual'], 'PASS') - self.assertEquals( - output['tests'][BENCHMARK]['story_3']['invalidation_reason'], - 'Noisy control test') - self.assertEquals( - output['tests'][BENCHMARK]['story_4']['invalidation_reason'], - 'Noisy control test') - self.assertEquals( - output['tests'][BENCHMARK]['story_5']['invalidation_reason'], - 'Noisy control test') - - # Experimental stories should not fail the test - def test_compare_values_4(self): - values_per_story = { - 'story_1': { - 'averages': [16.0, 17.0, 21.0], - 'ci_095': [2.0, 15.0, 16.0], - 'cpu_wall_time_ratio': [0.45, 0.42, 0.44], - }, - 'story_7': - { # Experimental story with higher value than the upper limit. - 'averages': [20, 26], - 'ci_095': [14, 16], - 'cpu_wall_time_ratio': [0.45, 0.42, 0.44], - } - } - - sample_perf_results = create_sample_perf_results(['story_1', 'story_7'], [], - BENCHMARK) - rerun = False - perf_test = perf_test_initializer() - perf_test.result_recorder[rerun].set_tests(sample_perf_results) - - self.assertEquals(perf_test.result_recorder[rerun].fails, 0) - - perf_test.compare_values(values_per_story, rerun) - result_recorder = perf_test.result_recorder[rerun] - self.assertEquals(result_recorder.tests, 2) - self.assertEquals(result_recorder.failed_stories, set([])) - - (output, overall_return_code) = result_recorder.get_output(0) - - self.assertEquals(overall_return_code, 0) - self.assertEquals(output['num_failures_by_type'].get('FAIL', 0), 0) - self.assertEquals(output['tests'][BENCHMARK]['story_1']['actual'], 'PASS') - self.assertEquals(output['tests'][BENCHMARK]['story_7']['actual'], 'PASS') - - # Low cpu_wall_time_ratio invalidates the failure - def test_compare_values_5(self): - values_per_story = { - 'story_1': { - 'averages': [26.0, 27.0, 21.0], - 'ci_095': [2.0, 15.0, 16.0], - 'cpu_wall_time_ratio': [0.35, 0.42, 0.34], - # Higher avg than upper limit with low Cpu_wall_time_ratio - } - } - - sample_perf_results = create_sample_perf_results(['story_1'], [], BENCHMARK) - rerun = False - perf_test = perf_test_initializer() - perf_test.result_recorder[rerun].set_tests(sample_perf_results) - - self.assertEquals(perf_test.result_recorder[rerun].fails, 0) - - perf_test.compare_values(values_per_story, rerun) - result_recorder = perf_test.result_recorder[rerun] - self.assertEquals(result_recorder.tests, 1) - self.assertEquals(result_recorder.failed_stories, set([])) - - result_recorder.invalidate_failures(BENCHMARK) - (output, overall_return_code) = result_recorder.get_output(0) - - self.assertEquals(overall_return_code, 0) - self.assertEquals(output['num_failures_by_type'].get('FAIL', 0), 0) - self.assertEquals(output['tests'][BENCHMARK]['story_1']['actual'], 'PASS') - self.assertEquals( - output['tests'][BENCHMARK]['story_1']['invalidation_reason'], - 'Low cpu_wall_time_ratio')
diff --git a/ui/base/ui_base_features.cc b/ui/base/ui_base_features.cc index d45fc0a..9d45a0d 100644 --- a/ui/base/ui_base_features.cc +++ b/ui/base/ui_base_features.cc
@@ -123,9 +123,16 @@ // When enabled, the feature will query the OS for a default cursor size, // to be used in determining the concrete object size of a custom cursor in -// blink. +// blink. Currently enabled by default on Windows only. +// TODO(crbug.com/1333523) - Implement for other platforms. const base::Feature kSystemCursorSizeSupported{ - "SystemCursorSizeSupported", base::FEATURE_DISABLED_BY_DEFAULT}; + "SystemCursorSizeSupported", +#if BUILDFLAG(IS_WIN) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; bool IsSystemCursorSizeSupported() { return base::FeatureList::IsEnabled(kSystemCursorSizeSupported);
diff --git a/ui/events/ozone/evdev/event_device_info.cc b/ui/events/ozone/evdev/event_device_info.cc index ff50794..d728dba 100644 --- a/ui/events/ozone/evdev/event_device_info.cc +++ b/ui/events/ozone/evdev/event_device_info.cc
@@ -770,6 +770,7 @@ input_id_.product == kSteelSeriesStratusDuoBluetoothProductId) { return false; } + return HasRelXY() && !HasProp(INPUT_PROP_POINTING_STICK); }
diff --git a/ui/events/ozone/evdev/input_device_factory_evdev.cc b/ui/events/ozone/evdev/input_device_factory_evdev.cc index 766677af..59ceb06 100644 --- a/ui/events/ozone/evdev/input_device_factory_evdev.cc +++ b/ui/events/ozone/evdev/input_device_factory_evdev.cc
@@ -545,7 +545,9 @@ for (auto it = converters_.begin(); it != converters_.end(); ++it) { if (it->second->HasMouse()) { mice.push_back(it->second->input_device()); - has_mouse = true; + // Some I2C touchpads falsely claim to be mice, see b/205272718 + if (it->second->type() != ui::InputDeviceType::INPUT_DEVICE_INTERNAL) + has_mouse = true; } else if (it->second->HasPointingStick()) { mice.push_back(it->second->input_device()); has_pointing_stick = true;
diff --git a/ui/file_manager/integration_tests/file_manager/zip_files.js b/ui/file_manager/integration_tests/file_manager/zip_files.js index 80b3aac..5c70c32 100644 --- a/ui/file_manager/integration_tests/file_manager/zip_files.js +++ b/ui/file_manager/integration_tests/file_manager/zip_files.js
@@ -311,6 +311,14 @@ */ testcase.zipExtractShowPanel = async () => { const entry = ENTRIES.zipArchive; + const targetDirectoryName = entry.nameText.split('.')[0]; + + // Make sure the test extension handles the new window creation properly. + await sendTestMessage({ + name: 'expectFileTask', + fileNames: [targetDirectoryName], + openType: 'launch' + }); // Open files app. const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []); @@ -478,6 +486,14 @@ */ testcase.zipExtractCheckContent = async () => { const entry = ENTRIES.zipArchive; + const targetDirectoryName = entry.nameText.split('.')[0]; + + // Make sure the test extension handles the new window creation properly. + await sendTestMessage({ + name: 'expectFileTask', + fileNames: [targetDirectoryName], + openType: 'launch' + }); // Open files app. const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []); @@ -501,8 +517,7 @@ !!await remoteCall.callRemoteTestUtil('fakeMouseClick', appId, [extract]), 'fakeMouseClick failed'); - const directoryQuery = - '#file-list [file-name="' + entry.nameText.split('.')[0] + '"]'; + const directoryQuery = '#file-list [file-name="' + targetDirectoryName + '"]'; // Check: the extract directory should appear. await remoteCall.waitForElement(appId, directoryQuery); @@ -526,6 +541,11 @@ */ testcase.zipExtractCheckDuplicates = async () => { const entry = ENTRIES.zipArchive; + const directory = entry.nameText.split('.')[0]; + + // Make sure the test extension handles the new window creation properly. + await sendTestMessage( + {name: 'expectFileTask', fileNames: [directory], openType: 'launch'}); // Open files app. const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []); @@ -549,11 +569,14 @@ !!await remoteCall.callRemoteTestUtil('fakeMouseClick', appId, [extract]), 'fakeMouseClick failed'); - const directory = entry.nameText.split('.')[0]; let directoryQuery = '#file-list [file-name="' + directory + '"]'; // Check: the extract directory should appear. await remoteCall.waitForElement(appId, directoryQuery); + // Prepare for the second window being opened. + await sendTestMessage( + {name: 'expectFileTask', fileNames: [directory], openType: 'launch'}); + // Right-click the selected file. chrome.test.assertTrue( !!await remoteCall.callRemoteTestUtil( @@ -592,6 +615,14 @@ */ testcase.zipExtractCheckEncodings = async () => { const entry = ENTRIES.zipSJISArchive; + const targetDirectoryName = entry.nameText.split('.')[0]; + + // Make sure the test extension handles the new window creation properly. + await sendTestMessage({ + name: 'expectFileTask', + fileNames: [targetDirectoryName], + openType: 'launch' + }); // Open files app. const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []); @@ -615,8 +646,7 @@ !!await remoteCall.callRemoteTestUtil('fakeMouseClick', appId, [extract]), 'fakeMouseClick failed'); - const directoryQuery = - '#file-list [file-name="' + entry.nameText.split('.')[0] + '"]'; + const directoryQuery = '#file-list [file-name="' + targetDirectoryName + '"]'; // Check: the extract directory should appear. await remoteCall.waitForElement(appId, directoryQuery); @@ -717,6 +747,15 @@ */ testcase.zipExtractFromReadOnly = async () => { const entry = ENTRIES.readOnlyZipFile; + const targetDirectoryName = entry.nameText.split('.')[0]; + + // Make sure the test extension handles the new window creation properly. + await sendTestMessage({ + name: 'expectFileTask', + fileNames: [targetDirectoryName], + openType: 'launch' + }); + // Open files app. const appId = await setupAndWaitUntilReady(RootPath.DRIVE, [], [entry]); @@ -752,8 +791,7 @@ // Navigate to My Files. await navigateWithDirectoryTree(appId, '/My files'); - const directoryQuery = - '#file-list [file-name="' + entry.nameText.split('.')[0] + '"]'; + const directoryQuery = '#file-list [file-name="' + targetDirectoryName + '"]'; // Check: the extract directory should appear. await remoteCall.waitForElement(appId, directoryQuery);
diff --git a/ui/ozone/platform/wayland/BUILD.gn b/ui/ozone/platform/wayland/BUILD.gn index 64ece47..348a780b 100644 --- a/ui/ozone/platform/wayland/BUILD.gn +++ b/ui/ozone/platform/wayland/BUILD.gn
@@ -169,6 +169,8 @@ "host/wayland_zaura_shell.h", "host/wayland_zcr_cursor_shapes.cc", "host/wayland_zcr_cursor_shapes.h", + "host/wayland_zcr_touchpad_haptics.cc", + "host/wayland_zcr_touchpad_haptics.h", "host/wayland_zwp_linux_dmabuf.cc", "host/wayland_zwp_linux_dmabuf.h", "host/wayland_zwp_pointer_constraints.cc", @@ -251,6 +253,7 @@ "//third_party/wayland-protocols:stylus_protocol", "//third_party/wayland-protocols:text_input_extension_protocol", "//third_party/wayland-protocols:text_input_protocol", + "//third_party/wayland-protocols:touchpad_haptics_protocol", "//third_party/wayland-protocols:viewporter_protocol", "//third_party/wayland-protocols:wayland_drm_protocol", "//third_party/wayland-protocols:xdg_decoration_protocol",
diff --git a/ui/ozone/platform/wayland/common/wayland_object.cc b/ui/ozone/platform/wayland/common/wayland_object.cc index 3c04508..43f4feb 100644 --- a/ui/ozone/platform/wayland/common/wayland_object.cc +++ b/ui/ozone/platform/wayland/common/wayland_object.cc
@@ -26,6 +26,7 @@ #include <surface-augmenter-client-protocol.h> #include <text-input-extension-unstable-v1-client-protocol.h> #include <text-input-unstable-v1-client-protocol.h> +#include <touchpad-haptics-unstable-v1-client-protocol.h> #include <viewporter-client-protocol.h> #include <wayland-client-core.h> #include <wayland-cursor.h> @@ -184,6 +185,7 @@ IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_touch_stylus_v2) IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_stylus_v2) IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_text_input_extension_v1) +IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_touchpad_haptics_v1) IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_blending_v1) IMPLEMENT_WAYLAND_OBJECT_TRAITS(zcr_alpha_compositing_v1) IMPLEMENT_WAYLAND_OBJECT_TRAITS(zwp_idle_inhibit_manager_v1)
diff --git a/ui/ozone/platform/wayland/common/wayland_object.h b/ui/ozone/platform/wayland/common/wayland_object.h index 924716c..8d278bb 100644 --- a/ui/ozone/platform/wayland/common/wayland_object.h +++ b/ui/ozone/platform/wayland/common/wayland_object.h
@@ -166,6 +166,7 @@ DECLARE_WAYLAND_OBJECT_TRAITS(zcr_touch_stylus_v2) DECLARE_WAYLAND_OBJECT_TRAITS(zcr_stylus_v2) DECLARE_WAYLAND_OBJECT_TRAITS(zcr_text_input_extension_v1) +DECLARE_WAYLAND_OBJECT_TRAITS(zcr_touchpad_haptics_v1) DECLARE_WAYLAND_OBJECT_TRAITS(zwp_idle_inhibit_manager_v1) DECLARE_WAYLAND_OBJECT_TRAITS(zwp_idle_inhibitor_v1) DECLARE_WAYLAND_OBJECT_TRAITS(zwp_keyboard_shortcuts_inhibit_manager_v1)
diff --git a/ui/ozone/platform/wayland/host/wayland_connection.cc b/ui/ozone/platform/wayland/host/wayland_connection.cc index f432965b..8e9b1d43 100644 --- a/ui/ozone/platform/wayland/host/wayland_connection.cc +++ b/ui/ozone/platform/wayland/host/wayland_connection.cc
@@ -51,6 +51,7 @@ #include "ui/ozone/platform/wayland/host/wayland_window_drag_controller.h" #include "ui/ozone/platform/wayland/host/wayland_zaura_shell.h" #include "ui/ozone/platform/wayland/host/wayland_zcr_cursor_shapes.h" +#include "ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.h" #include "ui/ozone/platform/wayland/host/wayland_zwp_linux_dmabuf.h" #include "ui/ozone/platform/wayland/host/wayland_zwp_pointer_constraints.h" #include "ui/ozone/platform/wayland/host/wayland_zwp_pointer_gestures.h" @@ -184,6 +185,8 @@ &WaylandZAuraShell::Instantiate); RegisterGlobalObjectFactory(WaylandZcrCursorShapes::kInterfaceName, &WaylandZcrCursorShapes::Instantiate); + RegisterGlobalObjectFactory(WaylandZcrTouchpadHaptics::kInterfaceName, + &WaylandZcrTouchpadHaptics::Instantiate); RegisterGlobalObjectFactory(WaylandZwpLinuxDmabuf::kInterfaceName, &WaylandZwpLinuxDmabuf::Instantiate); RegisterGlobalObjectFactory(WaylandZwpPointerConstraints::kInterfaceName,
diff --git a/ui/ozone/platform/wayland/host/wayland_connection.h b/ui/ozone/platform/wayland/host/wayland_connection.h index 5918af2..b89866d6 100644 --- a/ui/ozone/platform/wayland/host/wayland_connection.h +++ b/ui/ozone/platform/wayland/host/wayland_connection.h
@@ -49,6 +49,7 @@ class WaylandShm; class WaylandZAuraShell; class WaylandZcrCursorShapes; +class WaylandZcrTouchpadHaptics; class WaylandZwpPointerConstraints; class WaylandZwpPointerGestures; class WaylandZwpRelativePointerManager; @@ -184,6 +185,10 @@ return zcr_cursor_shapes_.get(); } + WaylandZcrTouchpadHaptics* zcr_touchpad_haptics() const { + return zcr_touchpad_haptics_.get(); + } + WaylandZwpLinuxDmabuf* zwp_dmabuf() const { return zwp_dmabuf_.get(); } WaylandDrm* drm() const { return drm_.get(); } @@ -314,6 +319,7 @@ friend class WaylandSeat; friend class WaylandShm; friend class WaylandZAuraShell; + friend class WaylandZcrTouchpadHaptics; friend class WaylandZwpLinuxDmabuf; friend class WaylandZwpPointerConstraints; friend class WaylandZwpPointerGestures; @@ -391,6 +397,7 @@ std::unique_ptr<WaylandCursorPosition> wayland_cursor_position_; std::unique_ptr<WaylandZAuraShell> zaura_shell_; std::unique_ptr<WaylandZcrCursorShapes> zcr_cursor_shapes_; + std::unique_ptr<WaylandZcrTouchpadHaptics> zcr_touchpad_haptics_; std::unique_ptr<WaylandZwpPointerConstraints> wayland_zwp_pointer_constraints_; std::unique_ptr<WaylandZwpRelativePointerManager>
diff --git a/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.cc b/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.cc new file mode 100644 index 0000000..6d3f6121 --- /dev/null +++ b/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.cc
@@ -0,0 +1,80 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.h" + +#include <touchpad-haptics-unstable-v1-client-protocol.h> + +#include "base/logging.h" +#include "ui/ozone/platform/wayland/host/wayland_connection.h" + +namespace ui { + +namespace { +constexpr uint32_t kMinVersion = 1; +} + +// static +constexpr char WaylandZcrTouchpadHaptics::kInterfaceName[]; + +// static +void WaylandZcrTouchpadHaptics::Instantiate(WaylandConnection* connection, + wl_registry* registry, + uint32_t name, + const std::string& interface, + uint32_t version) { + DCHECK_EQ(interface, kInterfaceName); + + if (connection->zcr_touchpad_haptics_ || + !wl::CanBind(interface, version, kMinVersion, kMinVersion)) { + return; + } + + auto zcr_touchpad_haptics = + wl::Bind<zcr_touchpad_haptics_v1>(registry, name, kMinVersion); + if (!zcr_touchpad_haptics) { + LOG(ERROR) << "Failed to bind zcr_touchpad_haptics_v1"; + return; + } + connection->zcr_touchpad_haptics_ = + std::make_unique<WaylandZcrTouchpadHaptics>( + zcr_touchpad_haptics.release(), connection); +} + +WaylandZcrTouchpadHaptics::WaylandZcrTouchpadHaptics( + zcr_touchpad_haptics_v1* zcr_touchpad_haptics, + WaylandConnection* connection) + : obj_(zcr_touchpad_haptics), connection_(connection) { + DCHECK(obj_); + DCHECK(connection_); + static constexpr zcr_touchpad_haptics_v1_listener + zcr_touchpad_haptics_v1_listener = { + &WaylandZcrTouchpadHaptics::OnActivated, + &WaylandZcrTouchpadHaptics::OnDeactivated, + }; + zcr_touchpad_haptics_v1_add_listener(obj_.get(), + &zcr_touchpad_haptics_v1_listener, this); +} + +WaylandZcrTouchpadHaptics::~WaylandZcrTouchpadHaptics() = default; + +// static +void WaylandZcrTouchpadHaptics::OnActivated( + void* data, + struct zcr_touchpad_haptics_v1* zcr_touchpad_haptics_v1) { + NOTIMPLEMENTED_LOG_ONCE(); +} + +// static +void WaylandZcrTouchpadHaptics::OnDeactivated( + void* data, + struct zcr_touchpad_haptics_v1* zcr_touchpad_haptics_v1) { + NOTIMPLEMENTED_LOG_ONCE(); +} + +void WaylandZcrTouchpadHaptics::Play(int32_t effect, int32_t strength) { + zcr_touchpad_haptics_v1_play(obj_.get(), effect, strength); +} + +} // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.h b/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.h new file mode 100644 index 0000000..df30619 --- /dev/null +++ b/ui/ozone/platform/wayland/host/wayland_zcr_touchpad_haptics.h
@@ -0,0 +1,52 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_ZCR_TOUCHPAD_HAPTICS_H_ +#define UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_ZCR_TOUCHPAD_HAPTICS_H_ + +#include "ui/ozone/platform/wayland/common/wayland_object.h" + +namespace ui { + +class WaylandConnection; + +// Wraps the zcr_touchpad_haptics object. +class WaylandZcrTouchpadHaptics + : public wl::GlobalObjectRegistrar<WaylandZcrTouchpadHaptics> { + public: + static constexpr char kInterfaceName[] = "zcr_touchpad_haptics_v1"; + + static void Instantiate(WaylandConnection* connection, + wl_registry* registry, + uint32_t name, + const std::string& interface, + uint32_t version); + + WaylandZcrTouchpadHaptics(zcr_touchpad_haptics_v1* zcr_touchpad_haptics, + WaylandConnection* connection); + WaylandZcrTouchpadHaptics(const WaylandZcrTouchpadHaptics&) = delete; + WaylandZcrTouchpadHaptics& operator=(const WaylandZcrTouchpadHaptics&) = + delete; + virtual ~WaylandZcrTouchpadHaptics(); + + // Calls zcr_touchpad_haptics_v1_play(). See interface descriptions for values + // for |effect| and |strength| + void Play(int32_t effect, int32_t strength); + + private: + // zcr_touchpad_haptics_v1_listener + static void OnActivated( + void* data, + struct zcr_touchpad_haptics_v1* zcr_touchpad_haptics_v1); + static void OnDeactivated( + void* data, + struct zcr_touchpad_haptics_v1* zcr_touchpad_haptics_v1); + + wl::Object<zcr_touchpad_haptics_v1> obj_; + WaylandConnection* const connection_; +}; + +} // namespace ui + +#endif // UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_ZCR_TOUCHPAD_HAPTICS_H_
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index e4dae43..48a0a4c 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -905,6 +905,27 @@ } } +# TODO(crbug.com/1091985): Support CrOS. +if (is_win || is_mac || is_linux || is_chromeos_lacros) { + static_library("view_pixel_diff_test_support") { + testonly = true + sources = [ + "test/view_skia_gold_pixel_diff.cc", + "test/view_skia_gold_pixel_diff.h", + ] + + deps = [ + ":views", + "//base", + "//skia", + "//testing/gtest", + "//ui/base:pixel_diff_test_support", + "//ui/gfx", + "//ui/snapshot", + ] + } +} + source_set("test_support") { testonly = true sources = [ @@ -1403,6 +1424,11 @@ if (is_linux || is_chromeos) { sources += [ "color_chooser/color_chooser_unittest.cc" ] } + + if (is_win || is_mac || is_linux || is_chromeos_lacros) { + sources += [ "test/view_skia_gold_pixel_diff_unittest.cc" ] + deps += [ "//ui/views:view_pixel_diff_test_support" ] + } } # This target is added as a dependency of browser interactive_ui_tests. It must
diff --git a/ui/views/animation/scroll_animator.cc b/ui/views/animation/scroll_animator.cc index ce63f04b..df87952 100644 --- a/ui/views/animation/scroll_animator.cc +++ b/ui/views/animation/scroll_animator.cc
@@ -30,12 +30,7 @@ namespace views { ScrollAnimator::ScrollAnimator(ScrollDelegate* delegate) - : delegate_(delegate), - velocity_x_(0.0f), - velocity_y_(0.0f), - last_t_(0.0f), - duration_(0.0f), - acceleration_(kDefaultAcceleration) { + : delegate_(delegate), acceleration_(kDefaultAcceleration) { DCHECK(delegate); } @@ -48,8 +43,8 @@ acceleration_ = kDefaultAcceleration; float v = std::max(fabs(velocity_x), fabs(velocity_y)); last_t_ = 0.0f; - velocity_x_ = velocity_x; - velocity_y_ = velocity_y; + velocity_x_ = velocity_x * velocity_multiplier_; + velocity_y_ = velocity_y * velocity_multiplier_; duration_ = -v / acceleration_; // in seconds animation_ = std::make_unique<gfx::SlideAnimation>(this); animation_->SetSlideDuration(base::Seconds(duration_));
diff --git a/ui/views/animation/scroll_animator.h b/ui/views/animation/scroll_animator.h index 12399e4..6f75f10 100644 --- a/ui/views/animation/scroll_animator.h +++ b/ui/views/animation/scroll_animator.h
@@ -42,6 +42,11 @@ // Use this if you would prefer different acceleration than the default. void set_acceleration(float acceleration) { acceleration_ = acceleration; } + // Use this if you would prefer different velocity than the default. + void set_velocity_multiplier(float velocity_multiplier) { + velocity_multiplier_ = velocity_multiplier; + } + void Start(float velocity_x, float velocity_y); void Stop(); @@ -55,10 +60,11 @@ raw_ptr<ScrollDelegate> delegate_; - float velocity_x_; - float velocity_y_; - float last_t_; - float duration_; + float velocity_x_{0.f}; + float velocity_y_{0.f}; + float velocity_multiplier_{1.f}; + float last_t_{0.f}; + float duration_{0.f}; float acceleration_; std::unique_ptr<gfx::SlideAnimation> animation_;
diff --git a/ui/views/controls/scrollbar/scroll_bar.cc b/ui/views/controls/scrollbar/scroll_bar.cc index b5243007..733d799 100644 --- a/ui/views/controls/scrollbar/scroll_bar.cc +++ b/ui/views/controls/scrollbar/scroll_bar.cc
@@ -192,9 +192,7 @@ if (event->type() == ui::ET_SCROLL_FLING_START) { scroll_status_ = ScrollStatus::kScrollInEnding; - if (!scroll_animator_) - scroll_animator_ = std::make_unique<ScrollAnimator>(this); - scroll_animator_->Start( + GetOrCreateScrollAnimator()->Start( IsHorizontal() ? event->details().velocity_x() : 0.f, IsHorizontal() ? 0.f : event->details().velocity_y()); event->SetHandled(); @@ -381,6 +379,23 @@ } } +ScrollAnimator* ScrollBar::GetOrCreateScrollAnimator() { + if (!scroll_animator_) { + scroll_animator_ = std::make_unique<ScrollAnimator>(this); + scroll_animator_->set_velocity_multiplier(fling_multiplier_); + } + return scroll_animator_.get(); +} + +void ScrollBar::SetFlingMultiplier(float fling_multiplier) { + fling_multiplier_ = fling_multiplier; + // `scroll_animator_` is lazily created when needed. + if (!scroll_animator_) + return; + + GetOrCreateScrollAnimator()->set_velocity_multiplier(fling_multiplier_); +} + ScrollBar::ScrollBar(bool is_horiz) : is_horiz_(is_horiz), repeater_(base::BindRepeating(&ScrollBar::TrackClicked,
diff --git a/ui/views/controls/scrollbar/scroll_bar.h b/ui/views/controls/scrollbar/scroll_bar.h index 1e6c66f..c55a525 100644 --- a/ui/views/controls/scrollbar/scroll_bar.h +++ b/ui/views/controls/scrollbar/scroll_bar.h
@@ -173,6 +173,13 @@ // scrollbar. virtual int GetThickness() const = 0; + // Gets or creates ScrollAnimator if it does not exist. + ScrollAnimator* GetOrCreateScrollAnimator(); + + // Sets `fling_multiplier_` which is used to modify animation velocities + // in `scroll_animator_`. + void SetFlingMultiplier(float fling_multiplier); + bool is_scrolling() const { return scroll_status_ == ScrollStatus::kScrollInProgress; } @@ -266,6 +273,8 @@ int max_pos_ = 0; + float fling_multiplier_ = 1.f; + // An instance of a RepeatController which scrolls the scrollbar continuously // as the user presses the mouse button down on the up/down buttons or the // track. @@ -295,6 +304,7 @@ std::unique_ptr<ui::SimpleMenuModel> menu_model_; std::unique_ptr<MenuRunner> menu_runner_; + // Used to animate gesture flings on the scroll bar. std::unique_ptr<ScrollAnimator> scroll_animator_; };
diff --git a/ui/views/controls/webview/webview.cc b/ui/views/controls/webview/webview.cc index e259cf28..3a3f6e1 100644 --- a/ui/views/controls/webview/webview.cc +++ b/ui/views/controls/webview/webview.cc
@@ -106,8 +106,8 @@ wc_owner_.reset(); AttachWebContentsNativeView(); - if (replacement && replacement->GetMainFrame()->IsRenderFrameLive()) { - SetUpNewMainFrame(replacement->GetMainFrame()); + if (replacement && replacement->GetPrimaryMainFrame()->IsRenderFrameLive()) { + SetUpNewMainFrame(replacement->GetPrimaryMainFrame()); } else { LostMainFrame(); } @@ -138,8 +138,9 @@ DCHECK(!max_size.IsEmpty()); min_size_ = min_size; max_size_ = max_size; - if (web_contents() && web_contents()->GetMainFrame()->IsRenderFrameLive()) - MaybeEnableAutoResize(web_contents()->GetMainFrame()); + if (web_contents() && + web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive()) + MaybeEnableAutoResize(web_contents()->GetPrimaryMainFrame()); } void WebView::SetCrashedOverlayView(View* crashed_overlay_view) { @@ -316,7 +317,7 @@ void WebView::RenderFrameCreated(content::RenderFrameHost* render_frame_host) { // Only handle the initial main frame, not speculative ones. - if (render_frame_host != web_contents()->GetMainFrame()) + if (render_frame_host != web_contents()->GetPrimaryMainFrame()) return; SetUpNewMainFrame(render_frame_host); @@ -324,7 +325,7 @@ void WebView::RenderFrameDeleted(content::RenderFrameHost* render_frame_host) { // Only handle the active main frame, not speculative ones. - if (render_frame_host != web_contents()->GetMainFrame()) + if (render_frame_host != web_contents()->GetPrimaryMainFrame()) return; LostMainFrame(); @@ -334,7 +335,7 @@ content::RenderFrameHost* new_host) { // Since we skipped speculative main frames in RenderFrameCreated, we must // watch for them being swapped in by watching for RenderFrameHostChanged(). - if (new_host != web_contents()->GetMainFrame()) + if (new_host != web_contents()->GetPrimaryMainFrame()) return; // Ignore the initial main frame host, as there's no renderer frame for it // yet. If the DCHECK fires, then we would need to handle the initial main @@ -435,7 +436,7 @@ void WebView::NotifyAccessibilityWebContentsChanged() { content::RenderFrameHost* rfh = - web_contents() ? web_contents()->GetMainFrame() : nullptr; + web_contents() ? web_contents()->GetPrimaryMainFrame() : nullptr; GetViewAccessibility().OverrideChildTreeID(rfh ? rfh->GetAXTreeID() : ui::AXTreeIDUnknown()); NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, false);
diff --git a/ui/views/controls/webview/webview_unittest.cc b/ui/views/controls/webview/webview_unittest.cc index f33598a..edf636d 100644 --- a/ui/views/controls/webview/webview_unittest.cc +++ b/ui/views/controls/webview/webview_unittest.cc
@@ -361,7 +361,7 @@ tester->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1); EXPECT_TRUE(web_contents->IsCrashed()); static_cast<content::WebContentsObserver*>(web_view.get()) - ->RenderFrameDeleted(web_contents->GetMainFrame()); + ->RenderFrameDeleted(web_contents->GetPrimaryMainFrame()); EXPECT_TRUE(crashed_overlay_view->IsDrawn()); } @@ -386,7 +386,7 @@ tester->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1); EXPECT_TRUE(web_contents->IsCrashed()); static_cast<content::WebContentsObserver*>(web_view.get()) - ->RenderFrameDeleted(web_contents->GetMainFrame()); + ->RenderFrameDeleted(web_contents->GetPrimaryMainFrame()); EXPECT_TRUE(crashed_overlay_view->IsDrawn()); web_view->SetCrashedOverlayView(nullptr);
diff --git a/ui/views/test/DEPS b/ui/views/test/DEPS index ebb84a2..220fb85d 100644 --- a/ui/views/test/DEPS +++ b/ui/views/test/DEPS
@@ -7,4 +7,7 @@ "+mojo/core/embedder", "+ui/gl", ], + "view_skia_gold_pixel_diff.cc" : [ + "+ui/snapshot", + ], }
diff --git a/ui/views/test/OWNERS b/ui/views/test/OWNERS index a2d17a38..8226580 100644 --- a/ui/views/test/OWNERS +++ b/ui/views/test/OWNERS
@@ -1 +1,2 @@ per-file *x11*=thomasanderson@chromium.org +per-file *skia_gold_pixel*=file://chrome/test/pixel/OWNERS
diff --git a/chrome/test/pixel/browser_skia_gold_pixel_diff.cc b/ui/views/test/view_skia_gold_pixel_diff.cc similarity index 85% rename from chrome/test/pixel/browser_skia_gold_pixel_diff.cc rename to ui/views/test/view_skia_gold_pixel_diff.cc index 34d1d17..0c0d798b 100644 --- a/chrome/test/pixel/browser_skia_gold_pixel_diff.cc +++ b/ui/views/test/view_skia_gold_pixel_diff.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" +#include "ui/views/test/view_skia_gold_pixel_diff.h" #include "base/logging.h" #include "base/run_loop.h" @@ -17,6 +17,9 @@ #include "ui/snapshot/snapshot_aura.h" #endif +namespace views { + +namespace { void SnapshotCallback(base::RunLoop* run_loop, gfx::Image* ret_image, gfx::Image image) { @@ -24,28 +27,13 @@ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop->QuitClosure()); } +} // namespace -BrowserSkiaGoldPixelDiff::BrowserSkiaGoldPixelDiff() = default; +ViewSkiaGoldPixelDiff::ViewSkiaGoldPixelDiff() = default; -BrowserSkiaGoldPixelDiff::~BrowserSkiaGoldPixelDiff() = default; +ViewSkiaGoldPixelDiff::~ViewSkiaGoldPixelDiff() = default; -bool BrowserSkiaGoldPixelDiff::GrabWindowSnapshotInternal( - gfx::NativeWindow window, - const gfx::Rect& snapshot_bounds, - gfx::Image* image) const { - base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); -#if defined(USE_AURA) - ui::GrabWindowSnapshotAsyncAura( -#else - ui::GrabWindowSnapshotAsync( -#endif - window, snapshot_bounds, - base::BindOnce(&SnapshotCallback, &run_loop, image)); - run_loop.Run(); - return !image->IsEmpty(); -} - -bool BrowserSkiaGoldPixelDiff::CompareScreenshot( +bool ViewSkiaGoldPixelDiff::CompareViewScreenshot( const std::string& screenshot_name, views::View* view, const ui::test::SkiaGoldMatchingAlgorithm* algorithm) const { @@ -65,3 +53,21 @@ return SkiaGoldPixelDiff::CompareScreenshot(screenshot_name, *image.ToSkBitmap(), algorithm); } + +bool ViewSkiaGoldPixelDiff::GrabWindowSnapshotInternal( + gfx::NativeWindow window, + const gfx::Rect& snapshot_bounds, + gfx::Image* image) const { + base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); +#if defined(USE_AURA) + ui::GrabWindowSnapshotAsyncAura( +#else + ui::GrabWindowSnapshotAsync( +#endif + window, snapshot_bounds, + base::BindOnce(&SnapshotCallback, &run_loop, image)); + run_loop.Run(); + return !image->IsEmpty(); +} + +} // namespace views
diff --git a/chrome/test/pixel/browser_skia_gold_pixel_diff.h b/ui/views/test/view_skia_gold_pixel_diff.h similarity index 74% rename from chrome/test/pixel/browser_skia_gold_pixel_diff.h rename to ui/views/test/view_skia_gold_pixel_diff.h index 843787d..06fb238 100644 --- a/chrome/test/pixel/browser_skia_gold_pixel_diff.h +++ b/ui/views/test/view_skia_gold_pixel_diff.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_TEST_PIXEL_BROWSER_SKIA_GOLD_PIXEL_DIFF_H_ -#define CHROME_TEST_PIXEL_BROWSER_SKIA_GOLD_PIXEL_DIFF_H_ +#ifndef UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_ +#define UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_ #include <string> @@ -11,10 +11,6 @@ #include "ui/base/test/skia_gold_pixel_diff.h" #include "ui/gfx/native_widget_types.h" -namespace views { -class View; -} // namespace views - namespace gfx { class Rect; class Image; @@ -27,19 +23,22 @@ } // namespace test } // namespace ui -// This is the utility class for Skia Gold pixeltest. +namespace views { +class View; + +// This is the utility class to protect views with pixeltest based on Skia Gold. // For an example on how to write pixeltests, please refer to the demo. // NOTE: this class has to be initialized before using. A screenshot prefix and // a corpus string are required for initialization. Check // `SkiaGoldPixelDiff::Init()` for more details. -class BrowserSkiaGoldPixelDiff : public ui::test::SkiaGoldPixelDiff { +class ViewSkiaGoldPixelDiff : public ui::test::SkiaGoldPixelDiff { public: - BrowserSkiaGoldPixelDiff(); + ViewSkiaGoldPixelDiff(); - BrowserSkiaGoldPixelDiff(const BrowserSkiaGoldPixelDiff&) = delete; - BrowserSkiaGoldPixelDiff& operator=(const BrowserSkiaGoldPixelDiff&) = delete; + ViewSkiaGoldPixelDiff(const ViewSkiaGoldPixelDiff&) = delete; + ViewSkiaGoldPixelDiff& operator=(const ViewSkiaGoldPixelDiff&) = delete; - ~BrowserSkiaGoldPixelDiff() override; + ~ViewSkiaGoldPixelDiff() override; // Takes a screenshot then uploads to Skia Gold and compares it with the // remote golden image. Returns true if the screenshot is the same as the @@ -52,15 +51,19 @@ // E.g. 'ToolbarTest_BackButtonHover'. Here `screenshot_prefix` is passed as // an argument during initialization. // `view` is the view you want to take screenshot. - bool CompareScreenshot( + bool CompareViewScreenshot( const std::string& screenshot_name, views::View* view, const ui::test::SkiaGoldMatchingAlgorithm* algorithm = nullptr) const; protected: + // Takes a screenshot of `window` within the specified area and stores the + // screenshot in `image`. Returns true if succeeding. virtual bool GrabWindowSnapshotInternal(gfx::NativeWindow window, const gfx::Rect& snapshot_bounds, gfx::Image* image) const; }; -#endif // CHROME_TEST_PIXEL_BROWSER_SKIA_GOLD_PIXEL_DIFF_H_ +} // namespace views + +#endif // UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_
diff --git a/chrome/test/pixel/browser_skia_gold_pixel_diff_unittest.cc b/ui/views/test/view_skia_gold_pixel_diff_unittest.cc similarity index 73% rename from chrome/test/pixel/browser_skia_gold_pixel_diff_unittest.cc rename to ui/views/test/view_skia_gold_pixel_diff_unittest.cc index 1197e4e4..60503c4 100644 --- a/chrome/test/pixel/browser_skia_gold_pixel_diff_unittest.cc +++ b/ui/views/test/view_skia_gold_pixel_diff_unittest.cc
@@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/test/pixel/browser_skia_gold_pixel_diff.h" +#include "ui/views/test/view_skia_gold_pixel_diff.h" + +#include <memory> +#include <utility> #include "base/command_line.h" -#include "chrome/test/base/test_browser_window.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -16,7 +18,9 @@ using ::testing::_; using ::testing::Return; -class MockBrowserSkiaGoldPixelDiff : public BrowserSkiaGoldPixelDiff { +namespace views { + +class MockBrowserSkiaGoldPixelDiff : public ViewSkiaGoldPixelDiff { public: MockBrowserSkiaGoldPixelDiff() = default; MOCK_CONST_METHOD1(LaunchProcess, int(const base::CommandLine&)); @@ -30,25 +34,25 @@ } }; -class MockBrowserSkiaGoldPixelDiffMockUpload +class MockViewSkiaGoldPixelDiffMockUpload : public MockBrowserSkiaGoldPixelDiff { public: - MockBrowserSkiaGoldPixelDiffMockUpload() = default; + MockViewSkiaGoldPixelDiffMockUpload() = default; MOCK_CONST_METHOD3(UploadToSkiaGoldServer, bool(const base::FilePath&, const std::string&, const ui::test::SkiaGoldMatchingAlgorithm*)); }; -class BrowserSkiaGoldPixelDiffTest : public views::test::WidgetTest { +class ViewSkiaGoldPixelDiffTest : public views::test::WidgetTest { public: - BrowserSkiaGoldPixelDiffTest() { + ViewSkiaGoldPixelDiffTest() { auto* cmd_line = base::CommandLine::ForCurrentProcess(); cmd_line->AppendSwitchASCII("git-revision", "test"); } - BrowserSkiaGoldPixelDiffTest(const BrowserSkiaGoldPixelDiffTest&) = delete; - BrowserSkiaGoldPixelDiffTest& operator=(const BrowserSkiaGoldPixelDiffTest&) = + ViewSkiaGoldPixelDiffTest(const ViewSkiaGoldPixelDiffTest&) = delete; + ViewSkiaGoldPixelDiffTest& operator=(const ViewSkiaGoldPixelDiffTest&) = delete; views::View* AddChildViewToWidget(views::Widget* widget) { @@ -60,8 +64,8 @@ } }; -TEST_F(BrowserSkiaGoldPixelDiffTest, CompareScreenshotByView) { - MockBrowserSkiaGoldPixelDiffMockUpload mock_pixel; +TEST_F(ViewSkiaGoldPixelDiffTest, CompareScreenshotByView) { + MockViewSkiaGoldPixelDiffMockUpload mock_pixel; EXPECT_CALL( mock_pixel, UploadToSkiaGoldServer( @@ -71,12 +75,12 @@ views::Widget* widget = CreateTopLevelNativeWidget(); views::View* child_view = AddChildViewToWidget(widget); mock_pixel.Init("Prefix"); - bool ret = mock_pixel.CompareScreenshot("Demo", child_view); + bool ret = mock_pixel.CompareViewScreenshot("Demo", child_view); EXPECT_TRUE(ret); widget->CloseNow(); } -TEST_F(BrowserSkiaGoldPixelDiffTest, BypassSkiaGoldFunctionality) { +TEST_F(ViewSkiaGoldPixelDiffTest, BypassSkiaGoldFunctionality) { base::CommandLine::ForCurrentProcess()->AppendSwitch( "bypass-skia-gold-functionality"); @@ -85,7 +89,9 @@ views::Widget* widget = CreateTopLevelNativeWidget(); views::View* child_view = AddChildViewToWidget(widget); mock_pixel.Init("Prefix"); - bool ret = mock_pixel.CompareScreenshot("Demo", child_view); + bool ret = mock_pixel.CompareViewScreenshot("Demo", child_view); EXPECT_TRUE(ret); widget->CloseNow(); } + +} // namespace views
diff --git a/weblayer/browser/ad_tagging_browsertest.cc b/weblayer/browser/ad_tagging_browsertest.cc index 3c5a57a1..3994d265 100644 --- a/weblayer/browser/ad_tagging_browsertest.cc +++ b/weblayer/browser/ad_tagging_browsertest.cc
@@ -105,7 +105,7 @@ // Main frame. NavigateAndWaitForCompletion(GetURL("frame_factory.html"), shell()); EXPECT_FALSE(observer.GetIsAdSubframe( - web_contents()->GetMainFrame()->GetFrameTreeNodeId())); + web_contents()->GetPrimaryMainFrame()->GetFrameTreeNodeId())); // (1) Vanilla child. content::RenderFrameHost* vanilla_child = subresource_filter::CreateSrcFrame(
diff --git a/weblayer/browser/android/ad_density_intervention_browsertest.cc b/weblayer/browser/android/ad_density_intervention_browsertest.cc index 9763dfb7..1a70e6b1 100644 --- a/weblayer/browser/android/ad_density_intervention_browsertest.cc +++ b/weblayer/browser/android/ad_density_intervention_browsertest.cc
@@ -94,7 +94,8 @@ // blank_with_adiframe_writer loads a script tagged as an ad, verify it is not // loaded and the subresource filter UI for ad blocking is shown. - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); EXPECT_EQ(infobars::ContentInfoBarManager::FromWebContents(web_contents()) ->infobar_count(), 1u); @@ -146,7 +147,8 @@ // blank_with_adiframe_writer loads a script tagged as an ad, verify it is // loaded as ads are not blocked and the subresource filter UI is not // shown. - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); // No ads blocked infobar should be shown as we have not triggered the // intervention. @@ -215,7 +217,8 @@ // We are not enforcing ad blocking on ads violations, site should load // as expected without subresource filter UI. - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); // No ads blocked infobar should be shown as we have not triggered the // intervention.
diff --git a/weblayer/browser/browser_controls_navigation_state_handler.cc b/weblayer/browser/browser_controls_navigation_state_handler.cc index 3b8701a..afe0790a 100644 --- a/weblayer/browser/browser_controls_navigation_state_handler.cc +++ b/weblayer/browser/browser_controls_navigation_state_handler.cc
@@ -46,7 +46,7 @@ bool BrowserControlsNavigationStateHandler::IsRendererControllingOffsets() { if (IsRendererHungOrCrashed()) return false; - return !web_contents()->GetMainFrame()->GetProcess()->IsBlocked(); + return !web_contents()->GetPrimaryMainFrame()->GetProcess()->IsBlocked(); } void BrowserControlsNavigationStateHandler::DidStartNavigation( @@ -89,7 +89,7 @@ if (is_main_frame) ScheduleStopDelayedForceShow(); if (render_frame_host->IsActive() && - (render_frame_host == web_contents()->GetMainFrame())) { + (render_frame_host == web_contents()->GetPrimaryMainFrame())) { UpdateState(); } }
diff --git a/weblayer/browser/client_hints_browsertest.cc b/weblayer/browser/client_hints_browsertest.cc index 3ea034fa..f72494a8 100644 --- a/weblayer/browser/client_hints_browsertest.cc +++ b/weblayer/browser/client_hints_browsertest.cc
@@ -65,7 +65,7 @@ content::RenderProcessHost* child_process = static_cast<TabImpl*>(shell()->tab()) ->web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess(); content::RenderProcessHostWatcher crash_observer( child_process,
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java index 40bcb18..5b76ecf 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java
@@ -62,7 +62,7 @@ @Override public void dispatchAuthenticatedIntent(Intent intent) { // This method should never be invoked in WebLayer as this class always returns false for - // isIntentToInstantApp(). + // handlesInstantAppLaunchingInternally(). assert false; } @@ -181,11 +181,6 @@ } @Override - public boolean isIntentToInstantApp(Intent intent) { - return false; - } - - @Override public boolean isIntentToAutofillAssistant(Intent intent) { return false; }
diff --git a/weblayer/browser/large_sticky_ad_intervention_browsertest.cc b/weblayer/browser/large_sticky_ad_intervention_browsertest.cc index 34a5699..d54e638 100644 --- a/weblayer/browser/large_sticky_ad_intervention_browsertest.cc +++ b/weblayer/browser/large_sticky_ad_intervention_browsertest.cc
@@ -62,7 +62,8 @@ // ad script is loaded and that the subresource filter UI doesn't show up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0); @@ -88,7 +89,8 @@ // shows up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 1); @@ -134,7 +136,8 @@ // running in dry run mode. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0);
diff --git a/weblayer/browser/navigation_controller_impl.cc b/weblayer/browser/navigation_controller_impl.cc index fdff0f0..25564bb 100644 --- a/weblayer/browser/navigation_controller_impl.cc +++ b/weblayer/browser/navigation_controller_impl.cc
@@ -595,9 +595,10 @@ // any delays from surface sync, ie a frame submitted by renderer may not // be displayed immediately. Such situations should be rare however, so // this should be good enough for the purposes needed. - web_contents()->GetMainFrame()->InsertVisualStateCallback(base::BindOnce( - &NavigationControllerImpl::OldPageNoLongerRendered, - weak_ptr_factory_.GetWeakPtr(), navigation_handle->GetURL())); + web_contents()->GetPrimaryMainFrame()->InsertVisualStateCallback( + base::BindOnce(&NavigationControllerImpl::OldPageNoLongerRendered, + weak_ptr_factory_.GetWeakPtr(), + navigation_handle->GetURL())); navigation_map_.erase(navigation_map_.find(navigation_handle)); }
diff --git a/weblayer/browser/overlay_popup_ad_intervention_browsertest.cc b/weblayer/browser/overlay_popup_ad_intervention_browsertest.cc index e28caab..0424fe8 100644 --- a/weblayer/browser/overlay_popup_ad_intervention_browsertest.cc +++ b/weblayer/browser/overlay_popup_ad_intervention_browsertest.cc
@@ -70,7 +70,8 @@ // ad script is loaded and that the subresource filter UI doesn't show up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0); @@ -104,7 +105,8 @@ // shows up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 1); @@ -150,7 +152,8 @@ // running in dry run mode. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0);
diff --git a/weblayer/browser/safe_browsing/client_side_detection_service_browsertest.cc b/weblayer/browser/safe_browsing/client_side_detection_service_browsertest.cc index 6b5fa6af7..b25e1e8 100644 --- a/weblayer/browser/safe_browsing/client_side_detection_service_browsertest.cc +++ b/weblayer/browser/safe_browsing/client_side_detection_service_browsertest.cc
@@ -70,7 +70,7 @@ base::RunLoop run_loop; - content::RenderFrameHost* rfh = GetWebContents()->GetMainFrame(); + content::RenderFrameHost* rfh = GetWebContents()->GetPrimaryMainFrame(); mojo::Remote<safe_browsing::mojom::PhishingDetector> phishing_detector; rfh->GetRemoteInterfaces()->GetInterface( phishing_detector.BindNewPipeAndPassReceiver());
diff --git a/weblayer/browser/safe_browsing/safe_browsing_browsertest.cc b/weblayer/browser/safe_browsing/safe_browsing_browsertest.cc index 8b0bb99..df3e9e8 100644 --- a/weblayer/browser/safe_browsing/safe_browsing_browsertest.cc +++ b/weblayer/browser/safe_browsing/safe_browsing_browsertest.cc
@@ -268,7 +268,7 @@ content::RenderProcessHost* child_process = static_cast<TabImpl*>(shell()->tab()) ->web_contents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetProcess(); content::RenderProcessHostWatcher crash_observer( child_process,
diff --git a/weblayer/browser/site_isolation_browsertest.cc b/weblayer/browser/site_isolation_browsertest.cc index 96899df..d88b2f5b 100644 --- a/weblayer/browser/site_isolation_browsertest.cc +++ b/weblayer/browser/site_isolation_browsertest.cc
@@ -126,8 +126,9 @@ // foo.com should not be isolated to start with. Verify that a cross-site // iframe does not become an OOPIF. - EXPECT_FALSE( - contents->GetMainFrame()->GetSiteInstance()->RequiresDedicatedProcess()); + EXPECT_FALSE(contents->GetPrimaryMainFrame() + ->GetSiteInstance() + ->RequiresDedicatedProcess()); std::string kAppendIframe = R"( var i = document.createElement('iframe'); i.id = 'child'; @@ -135,7 +136,8 @@ EXPECT_TRUE(content::ExecJs(contents, kAppendIframe)); GURL bar_url(embedded_test_server()->GetURL("bar.com", "/simple_page.html")); EXPECT_TRUE(NavigateIframeToURL(contents, "child", bar_url)); - content::RenderFrameHost* child = ChildFrameAt(contents->GetMainFrame(), 0); + content::RenderFrameHost* child = + ChildFrameAt(contents->GetPrimaryMainFrame(), 0); EXPECT_FALSE(child->IsCrossProcessSubframe()); // Fill a form and submit through a <input type="submit"> button. @@ -151,11 +153,12 @@ // swapped BrowsingInstances and put the result of the form submission into a // dedicated process, locked to foo.com. Check that a cross-site iframe now // becomes an OOPIF. - EXPECT_TRUE( - contents->GetMainFrame()->GetSiteInstance()->RequiresDedicatedProcess()); + EXPECT_TRUE(contents->GetPrimaryMainFrame() + ->GetSiteInstance() + ->RequiresDedicatedProcess()); EXPECT_TRUE(ExecJs(contents, kAppendIframe)); EXPECT_TRUE(NavigateIframeToURL(contents, "child", bar_url)); - child = ChildFrameAt(contents->GetMainFrame(), 0); + child = ChildFrameAt(contents->GetPrimaryMainFrame(), 0); EXPECT_TRUE(child->IsCrossProcessSubframe()); } @@ -176,7 +179,7 @@ NavigateAndWaitForCompletion(saved_url, shell()); EXPECT_TRUE(GetWebContents() - ->GetMainFrame() + ->GetPrimaryMainFrame() ->GetSiteInstance() ->RequiresDedicatedProcess()); @@ -201,14 +204,17 @@ embedded_test_server()->GetURL("foo.com", "/simple_page3.html"); NavigateAndWaitForCompletion(saved_url, shell()); content::WebContents* contents = GetWebContents(); - EXPECT_TRUE( - contents->GetMainFrame()->GetSiteInstance()->RequiresDedicatedProcess()); + EXPECT_TRUE(contents->GetPrimaryMainFrame() + ->GetSiteInstance() + ->RequiresDedicatedProcess()); NavigateAndWaitForCompletion(saved2_url, shell()); - EXPECT_TRUE( - contents->GetMainFrame()->GetSiteInstance()->RequiresDedicatedProcess()); + EXPECT_TRUE(contents->GetPrimaryMainFrame() + ->GetSiteInstance() + ->RequiresDedicatedProcess()); NavigateAndWaitForCompletion(foo_url, shell()); - EXPECT_FALSE( - contents->GetMainFrame()->GetSiteInstance()->RequiresDedicatedProcess()); + EXPECT_FALSE(contents->GetPrimaryMainFrame() + ->GetSiteInstance() + ->RequiresDedicatedProcess()); } #endif
diff --git a/weblayer/browser/subresource_filter_browsertest.cc b/weblayer/browser/subresource_filter_browsertest.cc index 9c574c42..c83c037 100644 --- a/weblayer/browser/subresource_filter_browsertest.cc +++ b/weblayer/browser/subresource_filter_browsertest.cc
@@ -179,7 +179,8 @@ console_observer.Wait(); // ... but it should not have blocked the subframe from being loaded. - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Do a different-document navigation to ensure that that the next navigation // to |test_url| executes as desired (e.g., to avoid any optimizations from @@ -188,7 +189,8 @@ // seen flake on the Windows trybot that indicates that such optimizations are // occurring. NavigateAndWaitForCompletion(GURL("about:blank"), shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Verify that the "ad" subframe is blocked if it is flagged by the // ruleset. @@ -196,7 +198,8 @@ SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Do a different-document navigation to ensure that that the next navigation // to |test_url| executes as desired (e.g., to avoid any optimizations from @@ -205,12 +208,14 @@ // seen flake on the Windows trybot that indicates that such optimizations are // occurring. NavigateAndWaitForCompletion(GURL("about:blank"), shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // The main frame document should never be filtered. SetRulesetToDisallowURLsWithPathSuffix("frame_with_included_script.html"); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); } // Verifies that subframes are not blocked on non-activated URLs. @@ -227,7 +232,8 @@ "suffix-that-does-not-match-anything")); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Verify that the "ad" subframe is loaded if even it is flagged by the // ruleset as the URL is not activated. @@ -235,7 +241,8 @@ SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, @@ -250,7 +257,8 @@ ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); content::WebContentsConsoleObserver console_observer(web_contents); console_observer.SetPattern(subresource_filter::kActivationConsoleMessage); @@ -263,7 +271,8 @@ test_url, test_url, ContentSettingsType::ADS, CONTENT_SETTING_ALLOW); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // No message for allowlisted url. EXPECT_TRUE(console_observer.messages().empty()); @@ -281,7 +290,8 @@ ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); content::WebContentsConsoleObserver console_observer(web_contents); console_observer.SetPattern(subresource_filter::kActivationConsoleMessage); @@ -294,7 +304,8 @@ CONTENT_SETTING_ALLOW); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // No message for loads that are not activated. EXPECT_TRUE(console_observer.messages().empty()); @@ -360,14 +371,16 @@ ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Allowlist via a reload. content::TestNavigationObserver navigation_observer(web_contents, 1); GetPrimaryPageThrottleManager()->OnReloadRequested(); navigation_observer.Wait(); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, @@ -381,28 +394,32 @@ ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url); NavigateAndWaitForCompletion(test_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Allowlist via a reload. content::TestNavigationObserver navigation_observer(web_contents, 1); GetPrimaryPageThrottleManager()->OnReloadRequested(); navigation_observer.Wait(); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // Another navigation to the same domain should be allowed too. NavigateAndWaitForCompletion( embedded_test_server()->GetURL( "/subresource_filter/frame_with_included_script.html?query"), shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); // A cross site blocklisted navigation should stay activated, however. GURL a_url(embedded_test_server()->GetURL( "a.com", "/subresource_filter/frame_with_included_script.html")); ActivateSubresourceFilterInWebContentsForURL(web_contents, a_url); NavigateAndWaitForCompletion(a_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, @@ -425,7 +442,8 @@ // Should not trigger activation as the URL is not on the blocklist and // has no active ads interventions. NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0); histogram_tester.ExpectTotalCount(kTimeSinceAdsInterventionTriggeredHistogram, 0); @@ -436,11 +454,12 @@ // Trigger an ads violation and renavigate the page. Should trigger // subresource filter activation. GetPrimaryPageThrottleManager()->OnAdsViolationTriggered( - web_contents->GetMainFrame(), + web_contents->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30); NavigateAndWaitForCompletion(url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, static_cast<int>(subresource_filter::mojom::AdsViolation:: @@ -465,7 +484,8 @@ test_clock->Advance(subresource_filter::kAdsInterventionDuration.Get()); NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, static_cast<int>(subresource_filter::mojom::AdsViolation:: @@ -512,7 +532,8 @@ // Should not trigger activation as the URL is not on the blocklist and // has no active ads interventions. NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0); histogram_tester.ExpectTotalCount(kTimeSinceAdsInterventionTriggeredHistogram, 0); @@ -523,11 +544,12 @@ // Trigger an ads violation and renavigate the page. Should trigger // subresource filter activation. GetPrimaryPageThrottleManager()->OnAdsViolationTriggered( - web_contents->GetMainFrame(), + web_contents->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30); NavigateAndWaitForCompletion(url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, static_cast<int>(subresource_filter::mojom::AdsViolation:: @@ -553,7 +575,7 @@ test_clock->Advance(subresource_filter::kAdsInterventionDuration.Get() - base::Minutes(30)); GetPrimaryPageThrottleManager()->OnAdsViolationTriggered( - web_contents->GetMainFrame(), + web_contents->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30); // Advance the clock to to kAdsInterventionDuration from the first @@ -561,7 +583,8 @@ test_clock->Advance(base::Minutes(30)); NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, static_cast<int>(subresource_filter::mojom::AdsViolation:: @@ -620,7 +643,8 @@ // Should not trigger activation as the URL is not on the blocklist and // has no active ads interventions. NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); auto entries = ukm_recorder.GetEntriesByName( ukm::builders::AdsIntervention_LastIntervention::kEntryName); EXPECT_EQ(0u, entries.size()); @@ -628,14 +652,15 @@ // Trigger an ads violation and renavigate to the page. Interventions are not // enforced so no activation should occur. GetPrimaryPageThrottleManager()->OnAdsViolationTriggered( - web_contents->GetMainFrame(), + web_contents->GetPrimaryMainFrame(), subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30); const base::TimeDelta kRenavigationDelay = base::Hours(2); test_clock->Advance(kRenavigationDelay); NavigateAndWaitForCompletion(url, shell()); - EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_TRUE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, static_cast<int>(subresource_filter::mojom::AdsViolation:: @@ -687,7 +712,8 @@ // First load should trigger the UI. NavigateAndWaitForCompletion(a_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kSubresourceFilterActionsHistogram, @@ -698,7 +724,8 @@ // Second load should not trigger the UI, but should still filter content. NavigateAndWaitForCompletion(a_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kSubresourceFilterActionsHistogram, @@ -711,7 +738,8 @@ // Load to another domain should trigger the UI. NavigateAndWaitForCompletion(b_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kSubresourceFilterActionsHistogram, @@ -724,7 +752,8 @@ subresource_filter::SubresourceFilterContentSettingsManager:: kDelayBeforeShowingInfobarAgain); NavigateAndWaitForCompletion(a_url, shell()); - EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents->GetMainFrame())); + EXPECT_FALSE( + WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( kSubresourceFilterActionsHistogram,
diff --git a/weblayer/browser/tab_impl.cc b/weblayer/browser/tab_impl.cc index e8a3e098..32c971cc 100644 --- a/weblayer/browser/tab_impl.cc +++ b/weblayer/browser/tab_impl.cc
@@ -552,12 +552,12 @@ bool use_separate_isolate, JavaScriptResultCallback callback) { if (use_separate_isolate) { - web_contents_->GetMainFrame()->ExecuteJavaScriptInIsolatedWorld( + web_contents_->GetPrimaryMainFrame()->ExecuteJavaScriptInIsolatedWorld( script, std::move(callback), ISOLATED_WORLD_ID_WEBLAYER); } else { content::RenderFrameHost::AllowInjectingJavaScript(); - web_contents_->GetMainFrame()->ExecuteJavaScript(script, - std::move(callback)); + web_contents_->GetPrimaryMainFrame()->ExecuteJavaScript( + script, std::move(callback)); } } @@ -596,8 +596,8 @@ void TabImpl::ExecuteScriptWithUserGestureForTests( const std::u16string& script) { - web_contents_->GetMainFrame()->ExecuteJavaScriptWithUserGestureForTests( - script, base::NullCallback()); + web_contents_->GetPrimaryMainFrame() + ->ExecuteJavaScriptWithUserGestureForTests(script, base::NullCallback()); } std::unique_ptr<FaviconFetcher> TabImpl::CreateFaviconFetcher(
diff --git a/weblayer/browser/translate_client_impl.cc b/weblayer/browser/translate_client_impl.cc index d4bdbba..99c1b298 100644 --- a/weblayer/browser/translate_client_impl.cc +++ b/weblayer/browser/translate_client_impl.cc
@@ -148,16 +148,16 @@ // to the most recently committed primary main-frame navigation, if one exists // (see the call to SetPageLanguageInNavigation() in // ContentTranslateDriver::RegisterPage()); this corresponds to - // WebContents::GetMainFrame()::GetPage(). Note also that in certain corner - // cases (e.g., tab startup) there might not be such a committed primary - // main-frame navigation; in those cases there won't be a weblayer::Page - // corresponding to the primary page, as weblayer::Page objects are created - // only at navigation commit. + // WebContents::GetPrimaryMainFrame()::GetPage(). Note also that in certain + // corner cases (e.g., tab startup) there might not be such a committed + // primary main-frame navigation; in those cases there won't be a + // weblayer::Page corresponding to the primary page, as weblayer::Page objects + // are created only at navigation commit. // TODO(crbug.com/1231889): Rearchitect translate's renderer-browser Mojo // connection to be able to explicitly determine the document/content::Page // with which this language determination event is associated. PageImpl* page = - PageImpl::GetForPage(web_contents()->GetMainFrame()->GetPage()); + PageImpl::GetForPage(web_contents()->GetPrimaryMainFrame()->GetPage()); if (page) { std::string language = details.adopted_language;